<?php
ob_start(); // optional safety
require '../includes/db.php';
include 'includes/header.php'; 
include 'includes/sidebar.php';

// 🔐 Protect admin
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}

$success = "";

// 🔥 SAVE SETTINGS
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $site_url = mysqli_real_escape_string($conn, $_POST['site_url']);

    // Check if exists
    $check = mysqli_query($conn, "
        SELECT * FROM system_settings 
        WHERE setting_key='site_url' LIMIT 1
    ");

    if (mysqli_num_rows($check) > 0) {

        // Update
        mysqli_query($conn, "
            UPDATE system_settings 
            SET setting_value='$site_url'
            WHERE setting_key='site_url'
        ");

    } else {

        // Insert
        mysqli_query($conn, "
            INSERT INTO system_settings (setting_key, setting_value)
            VALUES ('site_url', '$site_url')
        ");
    }

    $success = "✅ Website URL updated successfully!";
}

// 🔥 GET CURRENT VALUE
$res = mysqli_query($conn, "
    SELECT setting_value FROM system_settings 
    WHERE setting_key='site_url' LIMIT 1
");

$row = mysqli_fetch_assoc($res);
$current_url = $row['setting_value'] ?? '';
?>

<!DOCTYPE html>
<html>
<head>
<title>Admin Settings</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
body {
    background:#020617;
    color:#fff;
}
.card {
    background:#0f172a;
    border-radius:12px;
}
.form-control {
    background:#020617;
    color:#fff;
    border:1px solid #1e293b;
}
.btn-primary {
    background:linear-gradient(135deg,#3b82f6,#2563eb);
    border:none;
}
</style>

</head>
<body>

<div class="container mt-5">
    <div class="col-md-6 mx-auto">

        <div class="card p-4">

            <h4 class="text-center text-primary mb-4">⚙️ Website Settings</h4>

            <?php if($success): ?>
                <div class="alert alert-success"><?php echo $success; ?></div>
            <?php endif; ?>

            <form method="POST">

                <!-- Site URL -->
                <div class="mb-3">
                    <label>Website URL</label>
                    <input 
                        type="text" 
                        name="site_url" 
                        class="form-control"
                        value="<?php echo htmlspecialchars($current_url); ?>"
                        placeholder="https://yourdomain.com"
                        required
                    >
                </div>

                <button class="btn btn-primary w-100">
                    Save Settings
                </button>

            </form>

        </div>

    </div>
</div>

</body>
</html>