<?php
session_start();

// Check if user is logged in and is admin
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

require_once '../config/db.php';

$conn = $connection;

if ($conn->connect_error) {
    echo json_encode(['success' => false, 'message' => 'Connection failed: ' . $conn->connect_error]);
    exit;
}

$action = isset($_POST['action']) ? $_POST['action'] : '';

if ($action === 'update_settings') {
    $site_name = isset($_POST['site_name']) ? trim($_POST['site_name']) : '';
    $contact_email = isset($_POST['contact_email']) ? trim($_POST['contact_email']) : '';
    $support_phone = isset($_POST['support_phone']) ? trim($_POST['support_phone']) : '';
    $maintenance_mode = isset($_POST['maintenance_mode']) ? (int)$_POST['maintenance_mode'] : 0;

    // Validate email
    if ($contact_email && !filter_var($contact_email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['success' => false, 'message' => 'Invalid email format']);
        exit;
    }

    // Create settings table if it doesn't exist
    $create_table = "CREATE TABLE IF NOT EXISTS site_settings (
        id INT PRIMARY KEY AUTO_INCREMENT,
        setting_key VARCHAR(100) UNIQUE NOT NULL,
        setting_value TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        updated_by INT,
        FOREIGN KEY (updated_by) REFERENCES users(id) ON DELETE SET NULL
    )";

    $conn->query($create_table);

    // Update settings
    $settings = [
        'site_name' => $site_name,
        'contact_email' => $contact_email,
        'support_phone' => $support_phone,
        'maintenance_mode' => $maintenance_mode
    ];

    $all_success = true;
    foreach ($settings as $key => $value) {
        $insert_query = $conn->prepare(
            "INSERT INTO site_settings (setting_key, setting_value, updated_by) 
             VALUES (?, ?, ?) 
             ON DUPLICATE KEY UPDATE setting_value = ?, updated_by = ?"
        );
        
        if (!$insert_query) {
            $all_success = false;
            break;
        }

        $user_id = $_SESSION['user_id'];
        $insert_query->bind_param('ssiii', $key, $value, $user_id, $value, $user_id);
        
        if (!$insert_query->execute()) {
            $all_success = false;
            $insert_query->close();
            break;
        }
        $insert_query->close();
    }

    if ($all_success) {
        echo json_encode(['success' => true, 'message' => 'Settings saved successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to save settings: ' . $conn->error]);
    }

} else {
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
}

$conn->close();
?>
