<?php
require_once('source/session.php');
require_once('source/error.php');
require_once('source/dbconfig.php');
require_once('source/function.php');
require_once('source/restrict_admin.php');

// Create settings table if not exists (single row structure)
$DBH->exec("
    CREATE TABLE IF NOT EXISTS cbt_system_settings (
        id INT PRIMARY KEY DEFAULT 1,
        settings_data JSON NOT NULL,
        last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        CONSTRAINT singleton CHECK (id = 1)
    )
");

// Initialize default settings if not exists
$defaultSettings = [
    'cbt' => [
        'time_limit' => 60,
        'passing_score' => 50,
        'result_display' => 'immediate',
        'max_questions' => 50,
        'allow_retake' => false
    ],
    'page' => [
        'school_name' => 'British Kiddies Model School',
        'school_motto' => 'Excellence in Education',
        'logo_path' => '/assets/images/logo.png',
        'primary_color' => '#3498db',
        'admin_email' => 'admin@bkms.com.ng',
        'cbt_instructions' => 'Read all questions carefully before answering. You have limited time.'
    ]
];

// Check if settings exist
$settingsExist = $DBH->query("SELECT 1 FROM cbt_system_settings")->fetchColumn();

if (!$settingsExist) {
    $stmt = $DBH->prepare("INSERT INTO cbt_system_settings (settings_data) VALUES (:settings)");
    $stmt->execute(['settings' => json_encode($defaultSettings)]);
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        $DBH->beginTransaction();
        
        // Get current settings
        $currentSettings = $DBH->query("SELECT settings_data FROM cbt_system_settings")->fetchColumn();
        $settings = json_decode($currentSettings, true);
        
        if (isset($_POST['update_cbt_settings'])) {
            // Update CBT settings
            $settings['cbt'] = [
                'time_limit' => (int)$_POST['time_limit'],
                'passing_score' => (int)$_POST['passing_score'],
                'result_display' => $_POST['result_display'],
                'max_questions' => (int)$_POST['max_questions'],
                'allow_retake' => isset($_POST['allow_retake'])
            ];
        }
        
        if (isset($_POST['update_page_settings'])) {
            // Handle logo upload
            if (!empty($_FILES['logo']['name'])) {
                $uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/portal/coll_admin/uploads/logo/';
                if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
                
                $fileName = uniqid() . '_' . basename($_FILES['logo']['name']);
                $targetPath = $uploadDir . $fileName;
                
                if (move_uploaded_file($_FILES['logo']['tmp_name'], $targetPath)) {
                    $settings['page']['logo_path'] = '/portal/coll_admin/uploads/logo/' . $fileName;
                }
            }
            
            // Update page settings
            $settings['page'] = [
                'school_name' => $_POST['school_name'],
                'school_motto' => $_POST['school_motto'],
                'primary_color' => $_POST['primary_color'],
                'admin_email' => $_POST['admin_email'],
                'cbt_instructions' => $_POST['cbt_instructions'],
                'logo_path' => $settings['page']['logo_path'] // Keep existing if not changed
            ];
        }
        
        // Save all settings
        $stmt = $DBH->prepare("UPDATE cbt_system_settings SET settings_data = :settings WHERE id = 1");
        $stmt->execute(['settings' => json_encode($settings)]);
        
        $DBH->commit();
        $_SESSION['success'] = "Settings updated successfully!";
        header("Location: cbt_settings.php");
        exit();
    } catch (Exception $e) {
        $DBH->rollBack();
        $_SESSION['error'] = "Error updating settings: " . $e->getMessage();
        header("Location: cbt_settings.php");
        exit();
    }
}

// Get current settings
$settings = json_decode($DBH->query("SELECT settings_data FROM cbt_system_settings")->fetchColumn(), true);
$cbtSettings = $settings['cbt'];
$pageSettings = $settings['page'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>System Settings</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        :root {
            --primary-color: <?= $pageSettings['primary_color'] ?>;
        }
        .nav-tabs .nav-link.active {
            border-bottom: 3px solid var(--primary-color);
            color: var(--primary-color);
        }
        .logo-preview {
            max-height: 80px;
            max-width: 200px;
        }
        .color-preview {
            width: 25px;
            height: 25px;
            display: inline-block;
            border: 1px solid #dee2e6;
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <?php if (isset($_SESSION['success'])): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <?= $_SESSION['success'] ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php unset($_SESSION['success']); ?>
        <?php endif; ?>
        
        <?php if (isset($_SESSION['error'])): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <?= $_SESSION['error'] ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php unset($_SESSION['error']); ?>
        <?php endif; ?>

        <div class="card shadow">
            <div class="card-header bg-primary text-white">
                <h3 class="mb-0"><i class="bi bi-gear me-2"></i>System Settings</h3>
            </div>
            
            <div class="card-body">
                <ul class="nav nav-tabs mb-4">
                    <li class="nav-item">
                        <a class="nav-link active" data-bs-toggle="tab" href="#cbt-settings">CBT Settings</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" data-bs-toggle="tab" href="#page-settings">Page Settings</a>
                    </li>
                </ul>
                
                <div class="tab-content">
                    <!-- CBT Settings Tab -->
                    <div class="tab-pane fade show active" id="cbt-settings">
                        <form method="POST">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">Exam Time Limit (minutes)</label>
                                    <input type="number" name="time_limit" class="form-control" value="<?= $cbtSettings['time_limit'] ?>" min="1">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Passing Score (%)</label>
                                    <input type="number" name="passing_score" class="form-control" value="<?= $cbtSettings['passing_score'] ?>" min="1" max="100">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Result Display</label>
                                    <select name="result_display" class="form-select">
                                        <option value="immediate" <?= $cbtSettings['result_display'] == 'immediate' ? 'selected' : '' ?>>Immediately</option>
                                        <option value="after_exam" <?= $cbtSettings['result_display'] == 'after_exam' ? 'selected' : '' ?>>After Exam Period</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Max Questions</label>
                                    <input type="number" name="max_questions" class="form-control" value="<?= $cbtSettings['max_questions'] ?>" min="1">
                                </div>
                                <div class="col-12">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="allow_retake" id="allowRetake" <?= $cbtSettings['allow_retake'] ? 'checked' : '' ?>>
                                        <label class="form-check-label" for="allowRetake">Allow Exam Retake</label>
                                    </div>
                                </div>
                            </div>
                            <div class="mt-4">
                                <button type="submit" name="update_cbt_settings" class="btn btn-primary">
                                    <i class="bi bi-save me-1"></i> Save CBT Settings
                                </button>
                            </div>
                        </form>
                    </div>
                    
                    <!-- Page Settings Tab -->
                    <div class="tab-pane fade" id="page-settings">
                        <form method="POST" enctype="multipart/form-data">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">School Name</label>
                                    <input type="text" name="school_name" class="form-control" value="<?= htmlspecialchars($pageSettings['school_name']) ?>">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">School Motto</label>
                                    <input type="text" name="school_motto" class="form-control" value="<?= htmlspecialchars($pageSettings['school_motto']) ?>">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Primary Color</label>
                                    <div class="input-group">
                                        <input type="color" name="primary_color" class="form-control form-control-color" value="<?= $pageSettings['primary_color'] ?>">
                                        <span class="input-group-text"><?= $pageSettings['primary_color'] ?></span>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Admin Email</label>
                                    <input type="email" name="admin_email" class="form-control" value="<?= $pageSettings['admin_email'] ?>">
                                </div>
                                <div class="col-12">
                                    <label class="form-label">School Logo</label>
                                    <input type="file" name="logo" class="form-control" accept="image/*">
                                    <?php if ($pageSettings['logo_path'] && file_exists($_SERVER['DOCUMENT_ROOT'] . $pageSettings['logo_path'])): ?>
                                        <div class="mt-2">
                                            <img src="<?= $pageSettings['logo_path'] ?>" class="logo-preview" alt="Current Logo">
                                            <small class="d-block text-muted">Current logo</small>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <div class="col-12">
                                    <label class="form-label">CBT Instructions</label>
                                    <textarea name="cbt_instructions" class="form-control" rows="3"><?= htmlspecialchars($pageSettings['cbt_instructions']) ?></textarea>
                                </div>
                            </div>
                            <div class="mt-4">
                                <button type="submit" name="update_page_settings" class="btn btn-primary">
                                    <i class="bi bi-save me-1"></i> Save Page Settings
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Update color code display when color picker changes
        document.querySelector('input[name="primary_color"]').addEventListener('input', function() {
            this.nextElementSibling.textContent = this.value;
        });
    </script>
</body>
</html>