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

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';

define('LOGO_UPLOAD_DIR', PUBLIC_ROOT . '/uploads/logo/');
define('LOGO_MAX_FILE_SIZE', 1 * 1024 * 1024); // 1MB
$logoAllowedTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/svg+xml'];

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 update_website_settings.php");
    $response['message'] = 'Koneksi database gagal.';
    echo json_encode($response);
    exit;
}

 if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    $response['message'] = 'Metode request tidak valid.';
    echo json_encode($response);
    exit;
}

if (!is_dir(LOGO_UPLOAD_DIR) && !mkdir(LOGO_UPLOAD_DIR, 0775, true)) {
    http_response_code(500);
    error_log("Failed to create logo upload directory: " . LOGO_UPLOAD_DIR);
    $response['message'] = 'Kesalahan server: Gagal membuat direktori upload logo.';
    echo json_encode($response);
    exit;
}
 if (!is_writable(LOGO_UPLOAD_DIR)) {
    http_response_code(500);
    error_log("Logo upload directory is not writable: " . LOGO_UPLOAD_DIR);
    $response['message'] = 'Kesalahan server: Direktori upload logo tidak dapat ditulis.';
    echo json_encode($response);
    exit;
}


try {
    $settingsToUpdate = [];
    $errors = [];
    $newLogoFilename = null;
    $oldLogoFilename = null;
    $removeLogo = filter_input(INPUT_POST, 'remove_logo', FILTER_VALIDATE_BOOLEAN);

    $settingsToUpdate['app_name'] = sanitize_input($_POST['app_name'] ?? '');
    $settingsToUpdate['meta_description'] = sanitize_input($_POST['meta_description'] ?? '');
    $settingsToUpdate['meta_keywords'] = sanitize_input($_POST['meta_keywords'] ?? '');
    $settingsToUpdate['contact_email'] = filter_input(INPUT_POST, 'contact_email', FILTER_VALIDATE_EMAIL) ?: null;
    $settingsToUpdate['contact_phone'] = sanitize_input($_POST['contact_phone'] ?? '');

    if (empty($settingsToUpdate['app_name'])) {
        $errors['setting_app_name'] = 'Nama Aplikasi wajib diisi.';
    }
    if ($settingsToUpdate['contact_email'] === null && !empty($_POST['contact_email'])) {
         $errors['setting_contact_email'] = 'Format email kontak tidak valid.';
    }

    $stmtOldLogo = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'app_logo'");
    $stmtOldLogo->execute();
    $oldLogoFilename = $stmtOldLogo->fetchColumn();

    if ($removeLogo && $oldLogoFilename) {
        $logoPath = LOGO_UPLOAD_DIR . $oldLogoFilename;
        if (file_exists($logoPath)) {
            unlink($logoPath);
        }
        $settingsToUpdate['app_logo'] = null;
        $oldLogoFilename = null;
    }
    elseif (isset($_FILES['app_logo']) && $_FILES['app_logo']['error'] == UPLOAD_ERR_OK) {
        $fileTmpPath = $_FILES['app_logo']['tmp_name'];
        $fileName = $_FILES['app_logo']['name'];
        $fileSize = $_FILES['app_logo']['size'];
        $fileType = $_FILES['app_logo']['type'];
        $fileNameCmps = explode(".", $fileName);
        $fileExtension = strtolower(end($fileNameCmps));

        if ($fileSize > LOGO_MAX_FILE_SIZE) {
            $errors['setting_app_logo'] = 'Ukuran file logo terlalu besar (Maks 1MB).';
        } elseif (!in_array($fileType, $logoAllowedTypes)) {
            $errors['setting_app_logo'] = 'Format file logo tidak diizinkan (PNG, JPG, GIF, SVG).';
        } else {
            $newLogoFilename = 'logo_' . time() . '.' . $fileExtension;
            $dest_path = LOGO_UPLOAD_DIR . $newLogoFilename;

            if (move_uploaded_file($fileTmpPath, $dest_path)) {
                if ($oldLogoFilename && file_exists(LOGO_UPLOAD_DIR . $oldLogoFilename)) {
                    unlink(LOGO_UPLOAD_DIR . $oldLogoFilename);
                }
                $settingsToUpdate['app_logo'] = $newLogoFilename;
            } else {
                $errors['setting_app_logo'] = 'Gagal memindahkan file logo.';
                error_log("Failed to move logo file to: " . $dest_path);
                $newLogoFilename = null;
            }
        }
    } elseif (isset($_FILES['app_logo']) && $_FILES['app_logo']['error'] != UPLOAD_ERR_NO_FILE) {
        $uploadErrors = [ UPLOAD_ERR_INI_SIZE => 'Ukuran file melebihi batas server.', UPLOAD_ERR_FORM_SIZE => 'Ukuran file melebihi batas form.', UPLOAD_ERR_PARTIAL => 'File hanya terunggah sebagian.', UPLOAD_ERR_CANT_WRITE => 'Gagal menulis file ke disk.', UPLOAD_ERR_EXTENSION => 'Ekstensi PHP menghentikan unggahan file.', ];
        $errorCode = $_FILES['app_logo']['error'];
        $errors['setting_app_logo'] = $uploadErrors[$errorCode] ?? 'Terjadi kesalahan saat mengunggah logo.';
        error_log("Logo upload error code: " . $errorCode);
    }


    if (!empty($errors)) {
        http_response_code(400);
        $response['message'] = 'Periksa kembali input Anda.';
        $response['errors'] = $errors;
        if ($newLogoFilename && file_exists(LOGO_UPLOAD_DIR . $newLogoFilename)) {
            unlink(LOGO_UPLOAD_DIR . $newLogoFilename);
        }
    } else {
        $pdo->beginTransaction();
        $sql = "INSERT INTO settings (setting_key, setting_value, updated_at) VALUES (:key, :value_insert, NOW())
                ON DUPLICATE KEY UPDATE setting_value = :value_update, updated_at = NOW()";
        $stmt = $pdo->prepare($sql);

        $allSuccess = true;
        foreach ($settingsToUpdate as $key => $value) {
            $stmt->bindValue(':key', $key);
            $stmt->bindValue(':value_insert', $value);
            $stmt->bindValue(':value_update', $value); 

            if (!$stmt->execute()) {
                $allSuccess = false;
                error_log("Failed to update setting '{$key}': " . implode(", ", $stmt->errorInfo()));
                break;
            }
        }
        if ($allSuccess) {
            $pdo->commit();
            $response['success'] = true;
            $response['message'] = 'Pengaturan website berhasil disimpan.';
             if ($newLogoFilename) {
                $response['new_logo_url'] = base_url('uploads/logo/' . $newLogoFilename);
            } elseif ($removeLogo) {
                $response['new_logo_url'] = null;
            }
        } else {
            $pdo->rollBack();
            if ($newLogoFilename && file_exists(LOGO_UPLOAD_DIR . $newLogoFilename)) {
                unlink(LOGO_UPLOAD_DIR . $newLogoFilename);
            }
            http_response_code(500);
            $response['message'] = 'Gagal menyimpan beberapa pengaturan ke database.';
        }
    }

} catch (\PDOException $e) {
    if ($pdo->inTransaction()) { $pdo->rollBack(); }
    if (isset($newLogoFilename) && $newLogoFilename && file_exists(LOGO_UPLOAD_DIR . $newLogoFilename)) { unlink(LOGO_UPLOAD_DIR . $newLogoFilename); }
    error_log("Update Website Settings DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan database.";
    http_response_code(500);
} catch (\Throwable $e) {
    if ($pdo->inTransaction()) { $pdo->rollBack(); }
    if (isset($newLogoFilename) && $newLogoFilename && file_exists(LOGO_UPLOAD_DIR . $newLogoFilename)) { unlink(LOGO_UPLOAD_DIR . $newLogoFilename); }
    error_log("Update 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;
?>
