<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

session_start();

require_once __DIR__ . '/../includes/db_config.php';

if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

$in = json_decode(file_get_contents('php://input'), true);
if (empty($in['setting_key']) || !isset($in['setting_value'])) { echo json_encode(['success'=>false,'error'=>'Invalid data']); exit; }

try {
    $db = getDBConnection();

    $exists = $db->query("SHOW TABLES LIKE 'system_settings'")->rowCount() > 0;
    if (!$exists) {
        $db->exec("CREATE TABLE IF NOT EXISTS system_settings (
            id INT AUTO_INCREMENT PRIMARY KEY,
            setting_key VARCHAR(255) NOT NULL UNIQUE,
            setting_value TEXT,
            setting_type VARCHAR(50) DEFAULT 'text',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
    }

    $sel = $db->prepare("SELECT id FROM system_settings WHERE setting_key = ?");
    $sel->execute([$in['setting_key']]);

    if ($sel->fetch()){
        $up = $db->prepare("UPDATE system_settings SET setting_value = ?, updated_at = NOW() WHERE setting_key = ?");
        $up->execute([$in['setting_value'], $in['setting_key']]);
    } else {
        $ins = $db->prepare("INSERT INTO system_settings (setting_key, setting_value) VALUES (?, ?)");
        $ins->execute([$in['setting_key'], $in['setting_value']]);
    }

    echo json_encode(['success'=>true]);

} catch (PDOException $e) {
    error_log('DB Error: '.$e->getMessage());
    echo json_encode(['success'=>false,'error'=>'Failed to save settings']);
}
?>
