<?php
// admin/academic/promote_students.php
session_start(); // Mandatory to access $_SESSION

$projectRoot = dirname(dirname(__DIR__));
require_once $projectRoot . '/config/database.php';
require_once $projectRoot . '/config/config.php';

// 1. SECURITY CHECK
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../../auth/login.php"); 
    exit();
}

// 2. Handle Promotion Logic
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['promote'])) {
    $target_class = $_POST['target_class'];
    $student_ids = $_POST['student_ids'] ?? [];

    if (!empty($student_ids) && !empty($target_class)) {
        try {
            $pdo->beginTransaction();
            
            // If target is 'graduated', we set class_id to 0
            $final_class_id = ($target_class === 'graduated') ? 0 : $target_class;
            
            $stmt = $pdo->prepare("UPDATE students SET class_id = ? WHERE id = ?");
            
            foreach ($student_ids as $id) {
                $stmt->execute([$final_class_id, $id]);
            }
            
            $pdo->commit();
            $success = "Successfully processed " . count($student_ids) . " students!";
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = "Error during promotion: " . $e->getMessage();
        }
    } else {
        $error = "Please select students and a target class.";
    }
}

// 3. Fetch classes for dropdowns
$classes = $pdo->query("SELECT * FROM classes ORDER BY id ASC")->fetchAll();

// 4. Fetch students with JOIN to show class names
$selected_class = $_GET['view_class'] ?? null;
$search_query = $_GET['search'] ?? '';
$students = [];

if ($selected_class) {
    $sql = "SELECT s.*, c.class_name 
            FROM students s 
            JOIN classes c ON s.class_id = c.id 
            WHERE s.class_id = :class_id";
    
    if (!empty($search_query)) {
        $sql .= " AND (s.fullname LIKE :search OR s.reg_number LIKE :search)";
    }
    
    $sql .= " ORDER BY s.fullname ASC";
    
    $stmt = $pdo->prepare($sql);
    $params = [':class_id' => $selected_class];
    if (!empty($search_query)) {
        $params[':search'] = "%$search_query%";
    }
    
    $stmt->execute($params);
    $students = $stmt->fetchAll();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Promote Students | <?php echo htmlspecialchars($school_name ?? 'School Portal'); ?></title>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f4f4f4; padding: 20px; color: #333; }
        .container { background: white; padding: 30px; border-radius: 8px; max-width: 1100px; margin: auto; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .flex-form { display: flex; gap: 15px; margin-bottom: 20px; align-items: flex-end; background: #f9f9f9; padding: 15px; border-radius: 5px; border: 1px solid #eee; }
        .flex-form div { flex: 1; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
        th { background-color: #2c3e50; color: white; font-size: 13px; text-transform: uppercase; }
        tr:nth-child(even) { background-color: #fcfcfc; }
        tr:hover { background-color: #f1f1f1; }
        .btn { padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; font-weight: bold; text-decoration: none; display: inline-block; font-size: 14px; transition: 0.3s; }
        .btn-promote { background: #27ae60; color: white; }
        .btn-promote:hover { background: #219150; }
        .btn-view { background: #3498db; color: white; }
        .btn-view:hover { background: #2980b9; }
        .back-link { text-decoration: none; color: #3498db; margin-bottom: 20px; display: inline-block; font-weight: 600; }
        input[type="text"], select { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; }
        .badge { padding: 4px 8px; background: #e8f4fd; color: #2b6cb0; border-radius: 4px; font-size: 12px; font-weight: bold; font-family: monospace; }
        .alert { padding: 12px; border-radius: 4px; margin-bottom: 20px; font-weight: bold; }
        .alert-success { background: #e6fffa; color: #234e52; border: 1px solid #b2f5ea; }
        .alert-error { background: #fff5f5; color: #742a2a; border: 1px solid #feb2b2; }
    </style>
</head>
<body>

<div class="container">
    <a href="../dashboard.php" class="back-link">← Back to Dashboard</a>
    <h2>Student Promotion Manager</h2>
    <p style="color: #666; margin-bottom: 25px;">Move students to their next grade or mark them as graduated.</p>

    <?php if(isset($success)): ?>
        <div class="alert alert-success"><?php echo $success; ?></div>
    <?php endif; ?>

    <?php if(isset($error)): ?>
        <div class="alert alert-error"><?php echo $error; ?></div>
    <?php endif; ?>

    <form method="GET" class="flex-form">
        <div>
            <label><strong>1. Current Class:</strong></label>
            <select name="view_class" required>
                <option value="">-- Choose Class --</option>
                <?php foreach($classes as $c): ?>
                    <option value="<?php echo $c['id']; ?>" <?php echo ($selected_class == $c['id']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($c['class_name']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label><strong>2. Search (Optional):</strong></label>
            <input type="text" name="search" value="<?php echo htmlspecialchars($search_query); ?>" placeholder="Name or Reg No...">
        </div>
        <button type="submit" class="btn btn-view">Load Students</button>
    </form>

    <?php if ($selected_class): ?>
        <?php if (!empty($students)): ?>
            <form method="POST">
                <div style="background: #2d3748; padding: 20px; border-radius: 8px; margin-top: 20px; color: white;">
                    <div style="display: flex; align-items: center; gap: 20px; flex-wrap: wrap;">
                        <span><strong>Step 3: Choose Target Action</strong></span>
                        <select name="target_class" required style="width: auto; min-width: 250px; color: black;">
                            <option value="">-- Select Target Class --</option>
                            <?php foreach($classes as $c): ?>
                                <option value="<?php echo $c['id']; ?>">Promote to: <?php echo htmlspecialchars($c['class_name']); ?></option>
                            <?php endforeach; ?>
                            <option value="graduated">Move to Alumni (Graduated)</option>
                        </select>
                        <button type="submit" name="promote" class="btn btn-promote" onclick="return confirm('Execute promotion for selected students?')">Process Promotion</button>
                    </div>
                </div>

                <table>
                    <thead>
                        <tr>
                            <th style="width: 40px;"><input type="checkbox" id="selectAll" checked title="Select All"></th>
                            <th>Full Name</th>
                            <th>Registration Number</th>
                            <th>Current Class</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($students as $s): ?>
                        <tr>
                            <td><input type="checkbox" name="student_ids[]" value="<?php echo $s['id']; ?>" class="student-checkbox" checked></td>
                            <td><strong><?php echo htmlspecialchars($s['fullname']); ?></strong></td>
                            <td><span class="badge"><?php echo htmlspecialchars($s['reg_number']); ?></span></td>
                            <td><?php echo htmlspecialchars($s['class_name']); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </form>
        <?php else: ?>
            <div style="text-align: center; padding: 60px; background: #f9f9f9; border: 1px dashed #ccc; border-radius: 8px; margin-top: 20px;">
                <p style="color: #888; font-size: 16px;">No students found in this class matching your criteria.</p>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</div>

<script>
// Select/Deselect all checkboxes logic
const selectAll = document.getElementById('selectAll');
if (selectAll) {
    selectAll.addEventListener('change', function() {
        const checkboxes = document.getElementsByClassName('student-checkbox');
        for (let checkbox of checkboxes) {
            checkbox.checked = this.checked;
        }
    });
}
</script>

</body>
</html>