<?php
    header('Content-Type: application/json');
    $response = ['success' => false, 'settings' => [], 'message' => 'Gagal memuat pengaturan.'];

    require_once __DIR__ . '/../../../config/config.php';
    require_once __DIR__ . '/../../../includes/session.php';
    require_once __DIR__ . '/../../../lib/Auth.php';
    require_once __DIR__ . '/../../../includes/functions.php';
    require_once __DIR__ . '/../../../includes/db_connect.php';

    if (!Auth::isLoggedIn() || $_SESSION['user_role'] !== 'admin') {
        http_response_code(403);
        $response['message'] = 'Akses ditolak.';
        echo json_encode($response);
        exit;
    }

    if (!isset($pdo) || !$pdo instanceof PDO) {
        http_response_code(500);
        error_log("PDO object not available in get_website_settings.php");
        $response['message'] = 'Koneksi database gagal.';
        echo json_encode($response);
        exit;
    }

    try {
        $settingKeys = ['app_name', 'meta_description', 'app_logo', 'meta_keywords', 'contact_email', 'contact_phone'];
        $placeholders = implode(',', array_fill(0, count($settingKeys), '?'));

        $sql = "SELECT setting_key, setting_value FROM settings WHERE setting_key IN ({$placeholders})";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($settingKeys);
        $results = $stmt->fetchAll(PDO::FETCH_KEY_PAIR); 

        $settings = [];
        foreach ($settingKeys as $key) {
            $settings[$key] = $results[$key] ?? null; 
        }

        if (!empty($settings['app_logo'])) {
            if (!filter_var($settings['app_logo'], FILTER_VALIDATE_URL)) {
                 $settings['app_logo_url'] = base_url('uploads/logo/' . $settings['app_logo']);
            } else {
                 $settings['app_logo_url'] = $settings['app_logo'];
            }
        } else {
            $settings['app_logo_url'] = null;
        }


        $response['success'] = true;
        $response['settings'] = $settings;
        unset($response['message']);

    } catch (\PDOException $e) {
        error_log("Get Website Settings DB Error: " . $e->getMessage());
        $response['message'] = "Terjadi kesalahan database saat mengambil pengaturan.";
        http_response_code(500);
    } catch (\Throwable $e) {
        error_log("Get Website Settings General Error: " . $e->getMessage());
        $response['message'] = "Terjadi kesalahan internal server.";
        if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_php'] = $e->getMessage(); }
        http_response_code(500);
    }

    echo json_encode($response);
    exit;
    ?>
    