<?php
// NOTE: config (3).php handles session_start() and error reporting.
// We must include the config file first to get the database connection ($pdo) 
// and utility functions (like is_admin()).
require_once 'config.php'; 

// Include the layout file (assuming layouts.php exists and defines rendering functions)
require_once 'layouts.php';

// 1. Check Admin Permissions
// The require_admin() function from config (3).php can be used here.
// However, since we are using a custom redirect logic below, we'll keep the
// explicit check for clarity.
if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    // Redirect non-admins to the base URL, as defined in the config.
    header("Location: " . BASE_URL); 
    exit();
}

$message = "";

// 2. Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_features'])) {
    global $pdo; // Access the global PDO connection established in config (3).php

    try {
        $xmas_status = isset($_POST['xmas_mode']) ? 1 : 0;
        $vesak_status = isset($_POST['vesak_mode']) ? 1 : 0;

        // Start transaction for atomic updates
        $pdo->beginTransaction();

        // Prepare the statement for updating features
        $stmt = $pdo->prepare("UPDATE system_features SET is_active = :status WHERE feature_key = :key");
        
        // Update Xmas
        $stmt->execute([':status' => $xmas_status, ':key' => 'xmas_mode']);

        // Update Vesak
        $stmt->execute([':status' => $vesak_status, ':key' => 'vesak_mode']);
        
        $pdo->commit();
        $message = "Features updated successfully!";
        
    } catch (PDOException $e) {
        $pdo->rollBack();
        // Log the error and show a user-friendly message
        error_log("Feature Update Error: " . $e->getMessage());
        $message = "Error updating features: A database error occurred.";
    }
}

// 3. Fetch Current Settings
$features = ['xmas_mode' => 0, 'vesak_mode' => 0];
global $pdo; // Access the global PDO connection
try {
    // Fetch all active features
    $stmt = $pdo->query("SELECT feature_key, is_active FROM system_features");
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $features[$row['feature_key']] = $row['is_active'];
    }
} catch (PDOException $e) {
    error_log("Feature Fetch Error: " . $e->getMessage());
    // Fallback to default values if fetching fails
}

// --- Render Page ---
// Assuming layouts.php is included and these functions exist
render_header('Feature Control');
// The user role is already set in the session by config (3).php
render_sidebar($_SESSION['user_role'], 'admin_features.php');
render_topbar('System Features');
?>

<div class="max-w-4xl mx-auto">
    
    <?php if ($message): ?>
        <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 mb-6 rounded shadow-sm" role="alert">
            <p><?php echo htmlspecialchars($message); ?></p>
        </div>
    <?php endif; ?>

    <div class="bg-white rounded-2xl shadow-xl overflow-hidden">
        <div class="p-8 border-b border-gray-100">
            <h2 class="text-2xl font-bold text-gray-800">Seasonal Features</h2>
            <p class="text-gray-500 mt-1">Toggle special visual effects for the application.</p>
        </div>

        <form method="POST" action="" class="p-8 space-y-8">
            
            <!-- Xmas Feature Card -->
            <div class="flex items-center justify-between p-6 bg-blue-50 rounded-xl border border-blue-100 hover:shadow-md transition">
                <div class="flex items-center space-x-4">
                    <div class="w-12 h-12 bg-blue-500 rounded-full flex items-center justify-center text-white text-xl">
                        <i class="fa-regular fa-snowflake"></i>
                    </div>
                    <div>
                        <h3 class="font-bold text-gray-800 text-lg">Christmas Mode</h3>
                        <p class="text-sm text-gray-600">Enables falling snow effect and festive colors.</p>
                    </div>
                </div>
                <label class="relative inline-flex items-center cursor-pointer">
                    <input type="checkbox" name="xmas_mode" class="sr-only peer" <?php echo $features['xmas_mode'] ? 'checked' : ''; ?>>
                    <div class="w-14 h-7 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-0.5 after:left-[4px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-6 after:w-6 after:transition-all peer-checked:bg-blue-600"></div>
                </label>
            </div>

            <!-- Vesak Feature Card -->
            <div class="flex items-center justify-between p-6 bg-yellow-50 rounded-xl border border-yellow-100 hover:shadow-md transition">
                <div class="flex items-center space-x-4">
                    <div class="w-12 h-12 bg-yellow-500 rounded-full flex items-center justify-center text-white text-xl">
                        <i class="fa-solid fa-dharmachakra"></i>
                    </div>
                    <div>
                        <h3 class="font-bold text-gray-800 text-lg">Vesak Mode</h3>
                        <p class="text-sm text-gray-600">Enables lantern decorations and serene theme.</p>
                    </div>
                </div>
                <label class="relative inline-flex items-center cursor-pointer">
                    <input type="checkbox" name="vesak_mode" class="sr-only peer" <?php echo $features['vesak_mode'] ? 'checked' : ''; ?>>
                    <div class="w-14 h-7 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-yellow-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-0.5 after:left-[4px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-6 after:w-6 after:transition-all peer-checked:bg-yellow-500"></div>
                </label>
            </div>

            <div class="pt-4 flex justify-end">
                <button type="submit" name="update_features" class="px-6 py-3 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-xl transition shadow-lg transform hover:scale-105">
                    Save Changes
                </button>
            </div>
        </form>
    </div>
</div>

<?php 
render_main_content_end();
render_footer(); 
?>