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

// 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) VALUES (:exam_id, :class, :term, :session)");
            $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);
?>

<!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 - VERBUM DEI INT'L COLLEGE CBT Management</title>
    
    <!-- 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">
    
    <!-- Custom CSS -->
    <style>
        :root {
            --light-green: #e8f5e9;
            --primary-green: #2e7d32;
            --dark-green: #1b5e20;
            --accent-red: #A10A3F;
        }
        
        body {
            background-color: var(--light-green);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .admin-header {
            background-color: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .action-card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 2px 15px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }
        
        .action-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        }
        
        .btn-exam {
            background-color: var(--primary-green);
            color: white;
        }
        
        .form-control:focus {
            border-color: var(--primary-green);
            box-shadow: 0 0 0 0.25rem rgba(46, 125, 50, 0.25);
        }
        
        .table-responsive {
            border-radius: 10px;
            overflow: hidden;
        }
        
        .table thead {
            background-color: var(--primary-green);
            color: white;
        }

        .img-fluid {
              width: 100px;
              height:100px;
            }
    </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="assets/images/coll_logo.jpg.png" alt="VDA Logo" class="img-fluid">
                    </div>
                    <div>
                        <h1 class="h4 mb-0">VERBUM DEI INT'L COLLEGE CBT Management</h1>
                        <small class="text-muted">Link Exams to Classes</small>
                    </div>
                </div>
                <div class="dropdown">
                    <button class="btn btn-outline-secondary dropdown-toggle" type="button" id="adminDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="fas fa-user-circle me-1"></i> <?= htmlspecialchars($_SESSION['SESS_FULLNAME_ADMIN']) ?>
                    </button>
                    <ul class="dropdown-menu" aria-labelledby="adminDropdown">
                        <li><a class="dropdown-item" href="#"><i class="fas fa-user me-2"></i> Profile</a></li>
                        <li><a class="dropdown-item" href="#"><i class="fas fa-cog me-2"></i> Settings</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="../admin/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">
                <div class="card action-card mb-4">
                    <div class="card-header bg-white">
                        <h3 class="mb-0"><i class="fas fa-link me-2"></i> Link Exam to Multiple Classes</h3>
                    </div>
                    <div class="card-body">
                        <?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" aria-label="Close"></button>
                            </div>
                            <?php unset($_SESSION['error']); ?>
                        <?php endif; ?>
                        
                        <?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" aria-label="Close"></button>
                            </div>
                            <?php unset($_SESSION['success']); ?>
                        <?php endif; ?>

                        <form method="POST" id="examClassForm">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="exam_id" class="form-label">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'] ?>"><?= $exam['exam_name'] ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label for="session" class="form-label">Select Session</label>
                                    <select name="session" class="form-select" required>
                                        <option value="">-- Select Session --</option>
                                        <?php foreach ($sessions as $session): ?>
                                            <option value="<?= $session['session'] ?>"><?= $session['session'] ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="term" class="form-label">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">Select Classes</label>
                                    <select name="class[]" class="form-select" multiple="multiple" required>
                                        <?php foreach ($classes as $class): ?>
                                            <option value="<?= $class['class'] ?>"><?= $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>
                
                <div class="card action-card">
                    <div class="card-header bg-white">
                        <h3 class="mb-0"><i class="fas fa-list me-2"></i> Existing Exam-Class Links</h3>
                    </div>
                    <div class="card-body">
                        <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><?= $ec['exam_name'] ?></td>
                                            <td><?= $ec['class'] ?></td>
                                            <td><?= $ec['term'] ?></td>
                                            <td><?= $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>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="footer mt-5">
        <div class="container">
            <div class="row">
                <div class="col-md-8">
                    <p class="mb-1">VERBUM DEI INT'L COLLEGE, OWERRI</p>
                    <p class="mb-0">Powered By <a href="https://dataswift.com.ng" target="_blank" class="text-white">DataSwift</a> 
                    <img src="assets/images/dataswift_logo.png" alt="DataSwift Logo" style="height: 20px; margin-left: 5px;"></p>
                </div>
                <div class="col-md-4 text-md-end">
                    <p class="mb-0">&copy; <?= date('Y') ?> All Rights Reserved</p>
                </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>