<?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');

// Get admin name from session
$adminName = $_SESSION['SESS_FULLNAME_ADMIN'] ?? 'Administrator';

// School information
$schoolName = "Henzy Royal International School";
$schoolAddress = "No 17 Amadi Street, Amakohia, Uratta Owerri Imo State Nigeria";
$supportPhone = "+234 803 292 9756";
$supportEmail = "support@hris.com.ng";

// Initialize variables for form persistence
$exam_name = '';
$exam_description = '';
$exam_status = 'draft';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Get form data
    $exam_name = trim($_POST['exam_name'] ?? '');
    $exam_description = trim($_POST['exam_description'] ?? '');
    $exam_status = $_POST['exam_status'] ?? 'draft';
    
    // Validate inputs
    $errors = [];
    
    if (empty($exam_name)) {
        $errors[] = "Exam name is required.";
    } elseif (strlen($exam_name) > 255) {
        $errors[] = "Exam name must not exceed 255 characters.";
    }
    
    // Validate status
    $valid_statuses = ['draft', 'active', 'inactive'];
    if (!in_array($exam_status, $valid_statuses)) {
        $errors[] = "Invalid exam status selected.";
    }
    
    if (empty($errors)) {
        try {
            // Check if exam name already exists
            $stmt = $DBH->prepare("SELECT id FROM tbl_exam WHERE exam_name = :exam_name");
            $stmt->execute(['exam_name' => $exam_name]);
            $existing_exam = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($existing_exam) {
                $errors[] = "Exam name already exists. Please choose a different name.";
            } else {
                // Insert exam into tbl_exam with exam_status
                $stmt = $DBH->prepare("
                    INSERT INTO tbl_exam (
                        exam_name, 
                        exam_description, 
                        exam_status,
                        created_at, 
                        updated_at
                    ) VALUES (
                        :exam_name, 
                        :exam_description, 
                        :exam_status,
                        NOW(), 
                        NOW()
                    )
                ");
                
                $result = $stmt->execute([
                    'exam_name' => $exam_name,
                    'exam_description' => $exam_description,
                    'exam_status' => $exam_status
                ]);

                if ($result) {
                    // Store success message in session and redirect
                    $_SESSION['success'] = "Exam created successfully. You can now add subjects to this exam.";
                    header("Location: exam_class.php?exam_id=" . $DBH->lastInsertId());
                    exit();
                } else {
                    $errors[] = "Failed to create exam. Please try again.";
                }
            }
        } catch (PDOException $e) {
            // Log the actual error for debugging
            error_log("Database error in create_exam.php: " . $e->getMessage());
            $errors[] = "Database error occurred. Please try again later.";
        }
    }
    
    // If we got here, there were errors
    if (!empty($errors)) {
        $_SESSION['error'] = implode("\\n", $errors);
    }
}

// Get error/success messages from session
$error_message = $_SESSION['error'] ?? '';
$success_message = $_SESSION['success'] ?? '';

// Clear messages from session only after displaying
if (isset($_SESSION['error'])) {
    unset($_SESSION['error']);
}
if (isset($_SESSION['success'])) {
    unset($_SESSION['success']);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Exam - Henzy Royal International School CBT</title>
    <link rel="icon" type="image/png" href="../coll_logo.png">
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Google Fonts - Poppins -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- Custom CSS -->
    <style>
        :root {
            --primary-blue: #1a4b8c;    /* Royal Blue */
            --secondary-gold: #FFD700;    /* Gold */
            --dark-blue: #0f2b4f;         /* Dark Blue */
            --light-blue: #4a7db5;         /* Medium Blue */
            --light-gold: #FFF1B8;          /* Light Gold */
            --bg-light: #f5f9ff;
            --success-green: #28a745;
            --info-blue: #17a2b8;
            --warning-orange: #fd7e14;
            --danger-red: #dc3545;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            background-color: var(--bg-light);
            color: #333;
            padding-bottom: 60px;
        }
        
        /* Header Styles */
        .admin-header {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            box-shadow: 0 2px 15px rgba(26, 75, 140, 0.3);
            border-bottom: 3px solid var(--secondary-gold);
            color: white;
            margin-bottom: 2rem;
        }
        
        .logo-container {
            background: white;
            border-radius: 10px;
            padding: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        }
        
        .img-fluid {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 8px;
        }
        
        .header-title h1 {
            font-weight: 700;
            margin-bottom: 0;
            font-size: 1.5rem;
            color: white;
        }
        
        .header-title small {
            color: var(--secondary-gold);
            font-weight: 500;
        }
        
        /* Dropdown Styles */
        .admin-dropdown {
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 215, 0, 0.3);
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 50px;
            transition: all 0.3s ease;
        }
        
        .admin-dropdown:hover {
            background: rgba(255, 215, 0, 0.2);
            border-color: var(--secondary-gold);
        }
        
        .dropdown-menu {
            border: 1px solid var(--secondary-gold);
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .dropdown-item:hover {
            background-color: var(--light-gold);
            color: var(--dark-blue);
        }
        
        .dropdown-item i {
            color: var(--primary-blue);
        }
        
        /* Card Styles */
        .action-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 4px 20px rgba(26, 75, 140, 0.1);
            transition: all 0.3s ease;
            background: white;
            border: 1px solid rgba(255, 215, 0, 0.2);
            overflow: hidden;
        }
        
        .action-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(26, 75, 140, 0.2);
            border-color: var(--secondary-gold);
        }
        
        .card-header {
            background: linear-gradient(135deg, var(--light-gold), #ffffff);
            border-bottom: 2px solid var(--secondary-gold);
            padding: 1.5rem;
        }
        
        .card-header h3 {
            color: var(--dark-blue);
            font-weight: 700;
            margin: 0;
        }
        
        .card-header i {
            color: var(--secondary-gold);
        }
        
        .card-body {
            padding: 2rem;
        }
        
        /* Form Styles */
        .form-label {
            font-weight: 600;
            color: var(--dark-blue);
            margin-bottom: 0.5rem;
        }
        
        .form-label i {
            color: var(--secondary-gold);
            margin-right: 0.5rem;
        }
        
        .form-control, .form-select {
            border: 1px solid #ced4da;
            border-radius: 10px;
            padding: 0.75rem 1rem;
            font-size: 0.95rem;
            transition: all 0.3s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--secondary-gold);
            box-shadow: 0 0 0 0.25rem rgba(255, 215, 0, 0.25);
            outline: none;
        }
        
        .form-text {
            color: #6c757d;
            font-size: 0.85rem;
            margin-top: 0.25rem;
        }
        
        .input-group-text {
            background: linear-gradient(135deg, var(--light-gold), #ffffff);
            border: 1px solid #ced4da;
            border-radius: 10px 0 0 10px;
            color: var(--primary-blue);
            font-weight: 500;
        }
        
        /* Buttons */
        .btn-custom {
            padding: 0.75rem 1.5rem;
            border-radius: 50px;
            font-weight: 500;
            transition: all 0.3s ease;
            border: none;
        }
        
        .btn-exam {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            color: white;
        }
        
        .btn-exam:hover {
            background: linear-gradient(135deg, var(--dark-blue), #0a1f3a);
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(26, 75, 140, 0.3);
            color: white;
        }
        
        .btn-outline-secondary {
            border: 2px solid #6c757d;
            color: #6c757d;
            background: transparent;
            padding: 0.75rem 1.5rem;
            border-radius: 50px;
            font-weight: 500;
        }
        
        .btn-outline-secondary:hover {
            background: #6c757d;
            color: white;
            transform: translateY(-2px);
        }
        
        /* Alert Styles */
        .alert {
            border-radius: 10px;
            border: none;
            padding: 1rem;
            margin-bottom: 1.5rem;
            position: relative;
        }
        
        .alert-success {
            background: linear-gradient(135deg, #d4edda, #c3e6cb);
            color: #155724;
            border-left: 4px solid #28a745;
        }
        
        .alert-danger {
            background: linear-gradient(135deg, #f8d7da, #f5c6cb);
            color: #721c24;
            border-left: 4px solid #dc3545;
        }
        
        .alert-warning {
            background: linear-gradient(135deg, #fff3cd, #ffeaa7);
            color: #856404;
            border-left: 4px solid #ffc107;
        }
        
        .alert i {
            margin-right: 0.5rem;
        }
        
        /* Status badges */
        .status-badge {
            display: inline-block;
            padding: 0.35rem 0.75rem;
            border-radius: 50px;
            font-size: 0.85rem;
            font-weight: 500;
        }
        
        .status-draft {
            background: #6c757d;
            color: white;
        }
        
        .status-active {
            background: #28a745;
            color: white;
        }
        
        .status-inactive {
            background: #dc3545;
            color: white;
        }
        
        /* Footer */
        .footer {
            background: linear-gradient(135deg, var(--dark-blue), var(--primary-blue));
            color: white;
            padding: 1.5rem 0;
            margin-top: 3rem;
            border-top: 3px solid var(--secondary-gold);
            position: fixed;
            bottom: 0;
            width: 100%;
        }
        
        .footer a {
            color: var(--secondary-gold);
            text-decoration: none;
            font-weight: 500;
        }
        
        .footer a:hover {
            text-decoration: underline;
        }
        
        .footer img {
            height: 25px;
            margin-left: 5px;
            filter: brightness(0) invert(1);
        }
        
        /* Info Box */
        .info-box {
            background: linear-gradient(135deg, var(--light-gold), #ffffff);
            border-left: 4px solid var(--secondary-gold);
            padding: 1rem;
            border-radius: 10px;
            margin-top: 1rem;
        }
        
        .info-box i {
            color: var(--primary-blue);
            margin-right: 0.5rem;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .header-title h1 {
                font-size: 1.2rem;
            }
            
            .admin-dropdown {
                padding: 0.4rem 0.8rem;
                font-size: 0.9rem;
            }
            
            .card-header h3 {
                font-size: 1.3rem;
            }
            
            .card-body {
                padding: 1.5rem;
            }
            
            .footer {
                position: relative;
            }
            
            body {
                padding-bottom: 0;
            }
        }
    </style>
</head>
<body>
    <!-- Header -->
    <header class="admin-header py-3">
        <div class="container">
            <div class="d-flex justify-content-between align-items-center">
                <div class="d-flex align-items-center">
                    <div class="logo-container me-3">
                        <img src="../coll_logo.png" alt="Henzy Royal International School Logo" class="img-fluid">
                    </div>
                    <div class="header-title">
                        <h1 class="h4 mb-0">HENZY ROYAL INT'L SCHOOL</h1>
                        <small>CBT - Create New Exam</small>
                    </div>
                </div>
                <div class="dropdown">
                    <button class="btn admin-dropdown dropdown-toggle" type="button" id="adminDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="fas fa-user-circle me-1"></i> <?= htmlspecialchars($adminName) ?>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="adminDropdown">
                        <li><a class="dropdown-item" href="profile.php"><i class="fas fa-user me-2"></i> Profile</a></li>
                        <li><a class="dropdown-item" href="settings.php"><i class="fas fa-cog me-2"></i> Settings</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="cbt_admin_home.php"><i class="fas fa-home me-2"></i> CBT Dashboard</a></li>
                        <li><a class="dropdown-item" href="../main.php"><i class="fas fa-tachometer-alt me-2"></i> Main Dashboard</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="../logout.php"><i class="fas fa-sign-out-alt me-2"></i> Logout</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <div class="container py-4">
        <div class="row justify-content-center">
            <div class="col-md-10 col-lg-8">
                <!-- Breadcrumb -->
                <nav aria-label="breadcrumb" class="mb-4">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="cbt_admin_home.php" class="text-decoration-none" style="color: var(--primary-blue);">CBT Dashboard</a></li>
                        <li class="breadcrumb-item active" aria-current="page">Create New Exam</li>
                    </ol>
                </nav>
                
                <!-- Main Card -->
                <div class="card action-card">
                    <div class="card-header">
                        <h3 class="mb-0"><i class="fas fa-plus-circle me-2"></i> Create New Exam</h3>
                    </div>
                    <div class="card-body">
                        <?php if ($error_message): ?>
                            <div class="alert alert-danger">
                                <i class="fas fa-exclamation-circle"></i> 
                                <?= nl2br(htmlspecialchars($error_message)) ?>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($success_message): ?>
                            <div class="alert alert-success">
                                <i class="fas fa-check-circle"></i> 
                                <?= htmlspecialchars($success_message) ?>
                            </div>
                        <?php endif; ?>
                        
                        <form method="POST" onsubmit="return validateForm()">
                            <!-- Exam Name -->
                            <div class="mb-4">
                                <label for="exam_name" class="form-label">
                                    <i class="fas fa-book-open"></i> Exam Name <span class="text-danger">*</span>
                                </label>
                                <input type="text" class="form-control" id="exam_name" name="exam_name" 
                                       value="<?= htmlspecialchars($exam_name) ?>"
                                       placeholder="e.g., First Term Examination 2024" 
                                       required maxlength="255">
                                <div class="form-text">Enter a unique and descriptive name for this exam (max 255 characters)</div>
                            </div>
                            
                            <!-- Exam Description -->
                            <div class="mb-4">
                                <label for="exam_description" class="form-label">
                                    <i class="fas fa-align-left"></i> Exam Description
                                </label>
                                <textarea class="form-control" id="exam_description" name="exam_description" 
                                          rows="4" placeholder="Enter exam description, instructions, or notes"><?= htmlspecialchars($exam_description) ?></textarea>
                                <div class="form-text">Optional: Add any additional information about this exam</div>
                            </div>
                            
                            <!-- Exam Status -->
                            <div class="mb-4">
                                <label for="exam_status" class="form-label">
                                    <i class="fas fa-toggle-on"></i> Exam Status <span class="text-danger">*</span>
                                </label>
                                <select class="form-select" id="exam_status" name="exam_status" required>
                                    <option value="draft" <?= $exam_status == 'draft' ? 'selected' : '' ?>>Draft - Not Visible to Students</option>
                                    <option value="active" <?= $exam_status == 'active' ? 'selected' : '' ?>>Active - Available for Students</option>
                                    <option value="inactive" <?= $exam_status == 'inactive' ? 'selected' : '' ?>>Inactive - Temporarily Unavailable</option>
                                </select>
                                <div class="form-text">Choose when to make this exam available to students</div>
                            </div>
                            
                            <!-- Status Preview -->
                            <div class="mb-4">
                                <label class="form-label">Status Preview:</label>
                                <div>
                                    <?php
                                    $status_classes = [
                                        'draft' => 'status-draft',
                                        'active' => 'status-active',
                                        'inactive' => 'status-inactive'
                                    ];
                                    $status_labels = [
                                        'draft' => 'Draft',
                                        'active' => 'Active',
                                        'inactive' => 'Inactive'
                                    ];
                                    foreach ($status_classes as $value => $class):
                                    ?>
                                    <span class="status-badge <?= $class ?> me-2">
                                        <i class="fas fa-<?= $value == 'active' ? 'check-circle' : ($value == 'draft' ? 'clock' : 'ban') ?> me-1"></i>
                                        <?= $status_labels[$value] ?>
                                    </span>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            
                            <!-- Info Box -->
                            <div class="info-box mb-4">
                                <h6 class="mb-2"><i class="fas fa-info-circle"></i> About Exam Creation</h6>
                                <ul class="small mb-0">
                                    <li>Exam name must be unique - this helps identify the exam easily</li>
                                    <li>You can add subjects and their schedules after creating the exam</li>
                                    <li class="fw-bold">Status meanings:</li>
                                    <ul>
                                        <li><span class="status-badge status-draft">Draft</span> - Exam in preparation, not visible to students</li>
                                        <li><span class="status-badge status-active">Active</span> - Exam is live and available to students</li>
                                        <li><span class="status-badge status-inactive">Inactive</span> - Exam temporarily unavailable</li>
                                    </ul>
                                </ul>
                            </div>
                            
                            <div class="d-grid gap-3">
                                <button type="submit" class="btn btn-custom btn-exam btn-lg">
                                    <i class="fas fa-save me-2"></i> Create Exam
                                </button>
                                <a href="cbt_admin_home.php" class="btn btn-outline-secondary">
                                    <i class="fas fa-arrow-left me-2"></i> Back to Dashboard
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="footer">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <p class="mb-1"><i class="fas fa-crown me-2" style="color: var(--secondary-gold);"></i><strong>Henzy Royal International School</strong> - Computer Based Test System</p>
                    <p class="mb-0 small"><i class="fas fa-map-marker-alt me-1" style="color: var(--secondary-gold);"></i> <?= $schoolAddress ?></p>
                </div>
                <div class="col-md-4 text-md-end">
                    <p class="mb-0">Powered By <a href="https://dataswift.com.ng" target="_blank">DataSwift Coders</a> 
                    <img src="../datalogo.png" alt="DataSwift Logo"></p>
                    <small>&copy; <?= date('Y') ?> All Rights Reserved</small>
                </div>
            </div>
        </div>
    </footer>

    <!-- JavaScript Libraries -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <!-- Custom Scripts -->
    <script>
        // Form validation
        function validateForm() {
            const examName = document.getElementById('exam_name').value.trim();
            const examStatus = document.getElementById('exam_status').value;
            
            if (examName === '') {
                alert('Please enter an exam name');
                document.getElementById('exam_name').focus();
                return false;
            }
            
            if (examName.length > 255) {
                alert('Exam name must not exceed 255 characters');
                document.getElementById('exam_name').focus();
                return false;
            }
            
            if (!examStatus) {
                alert('Please select an exam status');
                document.getElementById('exam_status').focus();
                return false;
            }
            
            return true;
        }
        
        // Character counter for exam name
        document.getElementById('exam_name').addEventListener('input', function() {
            const maxLength = 255;
            const currentLength = this.value.length;
            const remaining = maxLength - currentLength;
            
            // Create or update counter element
            let counter = document.getElementById('nameCounter');
            if (!counter) {
                counter = document.createElement('small');
                counter.id = 'nameCounter';
                counter.className = 'form-text float-end';
                this.parentNode.appendChild(counter);
            }
            
            counter.textContent = `${remaining} characters remaining`;
            counter.style.color = remaining < 20 ? '#dc3545' : '#6c757d';
        });
    </script>
</body>
</html>