<?php
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
    header('Location: admin-login.php');
    exit;
}

// Get admin data
$stmt = $pdo->prepare("SELECT a.*, u.email FROM admins a JOIN users u ON a.id = u.id WHERE a.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin) {
    die("Admin profile not found.");
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $setting_key = $_POST['setting_key'] ?? '';
    $setting_value = $_POST['setting_value'] ?? '';
    
    if ($setting_key && $setting_value) {
        try {
            $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value, setting_group, is_public, updated_at) 
                                  VALUES (?, ?, 'system', 0, NOW()) 
                                  ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = NOW()");
            $stmt->execute([$setting_key, $setting_value]);
            
            $success = "System setting updated successfully!";
            
        } catch (Exception $e) {
            $error = "Failed to update system setting. Please try again.";
        }
    } else {
        $error = "Please fill in all required fields.";
    }
}

// Get system settings
$system_settings = [
    'site_name' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'site_name'")->fetchColumn() ?: 'JV Overseas Education',
    'site_email' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'site_email'")->fetchColumn() ?: 'info@jveducation.com',
    'contact_phone' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'contact_phone'")->fetchColumn() ?: '+256 788 289 235',
    'office_hours' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'office_hours'")->fetchColumn() ?: 'Mon-Fri: 8:00 AM - 5:00 PM EAT',
    'address' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'address'")->fetchColumn() ?: 'Kampala, Uganda',
    'google_analytics_id' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'google_analytics_id'")->fetchColumn() ?: '',
    'facebook_pixel_id' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'facebook_pixel_id'")->fetchColumn() ?: '',
    'smtp_host' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'smtp_host'")->fetchColumn() ?: '',
    'smtp_port' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'smtp_port'")->fetchColumn() ?: '587',
    'smtp_username' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'smtp_username'")->fetchColumn() ?: '',
    'smtp_password' => $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'smtp_password'")->fetchColumn() ?: '',
];

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>System Settings - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .settings-section {
            border: 1px solid #eee;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 30px;
        }
        .section-title {
            border-bottom: 2px solid #3fb7fe;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>

<?php include 'admin-navbar.php'; ?>

<div class="container py-5">
    <div class="section-title position-relative mb-4">
        <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">System Settings</h6>
        <h1 class="display-5">Configure System Settings</h1>
    </div>

    <?php if (isset($error)): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    
    <?php if (isset($success)): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <form method="POST">
        <!-- General Settings -->
        <div class="settings-section">
            <h5 class="section-title">General Settings</h5>
            
            <div class="form-group">
                <label>Site Name</label>
                <input type="text" name="setting_value" value="<?= htmlspecialchars($system_settings['site_name']) ?>" 
                       class="form-control" data-key="site_name">
                <small class="form-text text-muted">Name of your education consultancy</small>
            </div>
            
            <div class="form-group">
                <label>Site Email</label>
                <input type="email" name="setting_value" value="<?= htmlspecialchars($system_settings['site_email']) ?>" 
                       class="form-control" data-key="site_email">
                <small class="form-text text-muted">Email address for system notifications</small>
            </div>
            
            <div class="form-group">
                <label>Contact Phone</label>
               