<?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";

// Fetch available exams from tbl_exam
$stmt_exams = $DBH->query("SELECT * FROM tbl_exam");
$exams = $stmt_exams->fetchAll(PDO::FETCH_ASSOC);

// Fetch available sessions from tbl_session
$stmt_sessions = $DBH->query("SELECT * FROM tbl_session");
$sessions = $stmt_sessions->fetchAll(PDO::FETCH_ASSOC);

// Fetch available classes from tbl_class
$stmt_classes = $DBH->query("SELECT * FROM tbl_class");
$classes = $stmt_classes->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $exam_id = $_POST['exam_id'];
    $selected_classes = $_POST['class'];
    $term = $_POST['term'];
    $session = $_POST['session'];

    try {
        $DBH->beginTransaction();
        
        $success_count = 0;
        $error_messages = [];
        
        foreach ($selected_classes as $class) {
            // Check if the combination already exists
            $stmt = $DBH->prepare("SELECT id FROM tbl_exam_class WHERE exam_id = :exam_id AND class = :class AND term = :term AND session = :session");
            $stmt->execute([
                'exam_id' => $exam_id,
                'class' => $class,
                'term' => $term,
                'session' => $session
            ]);
            
            if ($stmt->fetch(PDO::FETCH_ASSOC)) {
                $error_messages[] = "Exam already linked to $class";
                continue;
            }
            
            // Insert the new combination
            $stmt = $DBH->prepare("INSERT INTO tbl_exam_class (exam_id, class, term, session, created_at, updated_at) VALUES (:exam_id, :class, :term, :session, NOW(), NOW())");
            $stmt->execute([
                'exam_id' => $exam_id,
                'class' => $class,
                'term' => $term,
                'session' => $session
            ]);
            
            $success_count++;
        }
        
        $DBH->commit();
        
        if ($success_count > 0) {
            $_SESSION['success'] = "Successfully linked exam to $success_count class(es)";
        }
        if (!empty($error_messages)) {
            $_SESSION['error'] = implode("<br>", $error_messages);
        }
        
        header("Location: exam_class.php");
        exit();
        
    } catch (PDOException $e) {
        $DBH->rollBack();
        $_SESSION['error'] = "Database error: " . $e->getMessage();
        header("Location: exam_class.php");
        exit();
    }
}

// Fetch all exam-class combinations to display in a table
$stmt_exam_classes = $DBH->query("
    SELECT ec.id, e.exam_name, ec.class, ec.term, ec.session 
    FROM tbl_exam_class ec
    JOIN tbl_exam e ON ec.exam_id = e.id
    ORDER BY e.exam_name, ec.class, ec.term
");
$exam_classes = $stmt_exam_classes->fetchAll(PDO::FETCH_ASSOC);

// Get error/success messages from session
$error_message = $_SESSION['error'] ?? '';
$success_message = $_SESSION['success'] ?? '';
unset($_SESSION['error'], $_SESSION['success']);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Link Exam to Classes - 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;
        }
        
        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;
            margin-bottom: 2rem;
        }
        
        .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;
        }
        
        /* Buttons */
        .btn-exam {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 50px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .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;
            transition: all 0.3s ease;
        }
        
        .btn-outline-secondary:hover {
            background: #6c757d;
            color: white;
            transform: translateY(-2px);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #28a745, #218838);
            border: none;
            color: white;
        }
        
        .btn-success:hover {
            background: linear-gradient(135deg, #218838, #1e7e34);
        }
        
        .btn-danger {
            background: linear-gradient(135deg, #dc3545, #c82333);
            border: none;
            color: white;
        }
        
        .btn-danger:hover {
            background: linear-gradient(135deg, #c82333, #bd2130);
        }
        
        .btn-sm {
            padding: 0.4rem 0.8rem;
            font-size: 0.85rem;
            border-radius: 8px;
        }
        
        /* Alert Styles */
        .alert {
            border-radius: 10px;
            border: none;
            padding: 1rem;
            margin-bottom: 1.5rem;
            border-left: 4px solid transparent;
        }
        
        .alert-success {
            background: linear-gradient(135deg, #d4edda, #c3e6cb);
            color: #155724;
            border-left-color: #28a745;
        }
        
        .alert-danger {
            background: linear-gradient(135deg, #f8d7da, #f5c6cb);
            color: #721c24;
            border-left-color: #dc3545;
        }
        
        .alert i {
            margin-right: 0.5rem;
        }
        
        .alert .btn-close {
            filter: brightness(0.5);
        }
        
        /* Table Styles */
        .table-responsive {
            border-radius: 10px;
            overflow: hidden;
        }
        
        .table {
            margin-bottom: 0;
        }
        
        .table thead {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            color: white;
        }
        
        .table thead th {
            font-weight: 600;
            border: none;
            padding: 1rem;
        }
        
        .table tbody td {
            padding: 1rem;
            vertical-align: middle;
        }
        
        .table tbody tr:hover {
            background-color: var(--light-gold);
        }
        
        /* 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);
        }
        
        .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);
        }
        
        /* 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;
            }
            
            .table thead th {
                font-size: 0.9rem;
                padding: 0.75rem;
            }
            
            .table tbody td {
                padding: 0.75rem;
                font-size: 0.9rem;
            }
            
            .btn-sm {
                padding: 0.25rem 0.5rem;
                font-size: 0.8rem;
            }
        }
    </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 - Link Exams to Classes</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">
            <div class="col-md-12">
                <!-- 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">Link Exams to Classes</li>
                    </ol>
                </nav>
                
                <?php if ($error_message): ?>
                    <div class="alert alert-danger alert-dismissible fade show">
                        <i class="fas fa-exclamation-circle me-2"></i> <?= $error_message ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                
                <?php if ($success_message): ?>
                    <div class="alert alert-success alert-dismissible fade show">
                        <i class="fas fa-check-circle me-2"></i> <?= $success_message ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <!-- Link Form Card -->
                <div class="card action-card mb-4">
                    <div class="card-header">
                        <h3 class="mb-0"><i class="fas fa-link me-2"></i> Link Exam to Multiple Classes</h3>
                    </div>
                    <div class="card-body">
                        <form method="POST" id="examClassForm">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="exam_id" class="form-label"><i class="fas fa-book-open me-1"></i> Select Exam</label>
                                    <select name="exam_id" class="form-select" required>
                                        <option value="">-- Select Exam --</option>
                                        <?php foreach ($exams as $exam): ?>
                                            <option value="<?= $exam['id'] ?>"><?= htmlspecialchars($exam['exam_name']) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label for="session" class="form-label"><i class="fas fa-calendar-alt me-1"></i> Select Session</label>
                                    <select name="session" class="form-select" required>
                                        <option value="">-- Select Session --</option>
                                        <?php foreach ($sessions as $session): ?>
                                            <option value="<?= htmlspecialchars($session['session']) ?>"><?= htmlspecialchars($session['session']) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="term" class="form-label"><i class="fas fa-calendar-check me-1"></i> Select Term</label>
                                    <select name="term" class="form-select" required>
                                        <option value="1st Term">1st Term</option>
                                        <option value="2nd Term">2nd Term</option>
                                        <option value="3rd Term">3rd Term</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label for="class" class="form-label"><i class="fas fa-users me-1"></i> Select Classes</label>
                                    <select name="class[]" class="form-select" multiple="multiple" required>
                                        <?php foreach ($classes as $class): ?>
                                            <option value="<?= htmlspecialchars($class['class']) ?>"><?= htmlspecialchars($class['class']) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <small class="text-muted">Hold CTRL/CMD to select multiple classes</small>
                                </div>
                            </div>
                            
                            <div class="d-grid gap-2">
                                <button type="submit" class="btn btn-exam">
                                    <i class="fas fa-save me-2"></i> Link Selected Classes
                                </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>
                
                <!-- Existing Links Card -->
                <div class="card action-card">
                    <div class="card-header">
                        <h3 class="mb-0"><i class="fas fa-list me-2"></i> Existing Exam-Class Links</h3>
                    </div>
                    <div class="card-body">
                        <?php if (empty($exam_classes)): ?>
                            <div class="text-center py-4">
                                <i class="fas fa-link fa-3x mb-3" style="color: #ccc;"></i>
                                <h5 class="text-muted">No links found</h5>
                                <p>Use the form above to create your first exam-class link.</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Exam Name</th>
                                            <th>Class</th>
                                            <th>Term</th>
                                            <th>Session</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($exam_classes as $ec): ?>
                                            <tr>
                                                <td><strong><?= htmlspecialchars($ec['exam_name']) ?></strong></td>
                                                <td><span class="badge bg-info text-dark"><?= htmlspecialchars($ec['class']) ?></span></td>
                                                <td><?= htmlspecialchars($ec['term']) ?></td>
                                                <td><?= htmlspecialchars($ec['session']) ?></td>
                                                <td>
                                                    <div class="btn-group" role="group">
                                                        <a href="set_questions.php?exam_class_id=<?= $ec['id'] ?>" class="btn btn-sm btn-success">
                                                            <i class="fas fa-question-circle me-1"></i> Set Questions
                                                        </a>
                                                        <a href="delete_link.php?id=<?= $ec['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to remove this link?')">
                                                            <i class="fas fa-trash-alt me-1"></i> Remove
                                                        </a>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            
                            <div class="mt-3 text-muted small">
                                <i class="fas fa-info-circle me-1"></i> Total: <?= count($exam_classes) ?> link(s) found
                            </div>
                        <?php endif; ?>
                    </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>
    
    <script>
        $(document).ready(function() {
            // Initialize multiple select with better UX
            $('select[name="class[]"]').attr('size', '5');
            
            // Form validation
            $('#examClassForm').on('submit', function() {
                if ($('select[name="class[]"]').val() === null) {
                    alert('Please select at least one class');
                    return false;
                }
                return true;
            });
        });
    </script>
</body>
</html>