<?php
session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json; charset=utf-8');

$auth = new Auth();
if (!$auth->check() || !$auth->isSuperAdmin()) {
    jsonResponse(false, 'Unauthorized', [], 401);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(false, 'Invalid request method.');
}

$csrf = new CSRF();
if (!$csrf->verify($_POST['csrf_token'] ?? '')) {
    jsonResponse(false, 'Invalid CSRF token.');
}

$db = Database::getInstance();
$action = $_POST['action'] ?? 'save_settings';

if ($action === 'mark_read') {
    $enqId = (int) ($_POST['id'] ?? 0);
    if ($enqId > 0) {
        $db->update('enquiries', ['status' => 'read'], 'id = ? AND status = ?', [$enqId, 'new']);
        jsonResponse(true, 'Enquiry marked as read.');
    }
    jsonResponse(false, 'Invalid enquiry ID.');
}

if ($action === 'delete_enquiry') {
    $enqId = (int) ($_POST['id'] ?? 0);
    if ($enqId > 0) {
        $db->delete('enquiries', 'id = ?', [$enqId]);
        jsonResponse(true, 'Enquiry deleted.');
    }
    jsonResponse(false, 'Invalid enquiry ID.');
}

if ($action === 'save_section') {
    $sectionId = (int) ($_POST['section_id'] ?? 0);
    $title = trim($_POST['title'] ?? '');
    $subtitle = trim($_POST['subtitle'] ?? '');
    $content = trim($_POST['content'] ?? '');
    $isActive = isset($_POST['is_active']) ? 1 : 0;
    $sortOrder = (int) ($_POST['sort_order'] ?? 0);

    if ($sectionId > 0) {
        $db->update('website_sections', [
            'title' => $title,
            'subtitle' => $subtitle,
            'content' => $content,
            'is_active' => $isActive,
            'sort_order' => $sortOrder,
            'updated_at' => date('Y-m-d H:i:s'),
        ], 'id = ?', [$sectionId]);
    }
    jsonResponse(true, 'Section updated.');
}

if ($action === 'add_section') {
    $sectionKey = trim($_POST['section_key'] ?? '');
    $title = trim($_POST['title'] ?? '');
    $subtitle = trim($_POST['subtitle'] ?? '');

    if (empty($sectionKey)) {
        jsonResponse(false, 'Section key is required.');
    }

    $existing = $db->query("SELECT id FROM website_sections WHERE section_key = ?", [$sectionKey])->fetch();
    if ($existing) {
        jsonResponse(false, 'Section key already exists.');
    }

    $maxSort = $db->query("SELECT COALESCE(MAX(sort_order), 0) as ms FROM website_sections")->fetch()['ms'];
    $db->insert('website_sections', [
        'section_key' => $sectionKey,
        'title' => $title,
        'subtitle' => $subtitle,
        'is_active' => 1,
        'sort_order' => $maxSort + 1,
        'created_at' => date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s'),
    ]);
    jsonResponse(true, 'Section added.');
}

if ($action === 'delete_section') {
    $sectionId = (int) ($_POST['section_id'] ?? 0);
    if ($sectionId > 0) {
        $db->delete('website_sections', 'id = ?', [$sectionId]);
        jsonResponse(true, 'Section deleted.');
    }
    jsonResponse(false, 'Invalid section.');
}

$settingsData = $_POST['settings'] ?? null;
if ($settingsData !== null) {
    if (is_string($settingsData)) {
        $settingsData = json_decode($settingsData, true);
    }
    if (!is_array($settingsData)) {
        jsonResponse(false, 'Invalid settings data.');
    }

    foreach ($settingsData as $key => $value) {
        $existing = $db->query("SELECT id FROM website_settings WHERE setting_key = ?", [$key])->fetch();
        if ($existing) {
            $db->update('website_settings', ['setting_value' => $value, 'updated_at' => date('Y-m-d H:i:s')], 'setting_key = ?', [$key]);
        } else {
            $db->insert('website_settings', [
                'setting_key' => $key,
                'setting_value' => $value,
                'setting_type' => 'text',
                'group_name' => 'general',
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
        }
    }

    $activityLog = new ActivityLog();
    $activityLog->log($_SESSION['user_id'], null, 'cms', 'update', 'Updated website settings');
    jsonResponse(true, 'Settings saved successfully.');
}

jsonResponse(false, 'Invalid action.');
