<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
require_once 'db.php';

$message = "";

// 1. HANDLER: SAVE ALLOCATION MAP MATRIX PARAMETERS
if (isset($_POST['allocate_course'])) {
    try {
        $stmt = $pdo->prepare("INSERT INTO course_allocations (course_id, department, level, program, session) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([
            intval($_POST['course_id']),
            trim($_POST['dept_val']),
            trim($_POST['lvl_val']),
            trim($_POST['program_val']),
            trim($_POST['session_val'])
        ]);
        $message = "<div class='alert alert-success'>✅ Success: Course successfully allocated to specified Class Level Cohort matrix!</div>";
    } catch (\PDOException $e) {
        $message = "<div class='alert alert-danger'>❌ Allocation Error: Mapping path duplicate or invalid parameters. " . htmlspecialchars($e->getMessage()) . "</div>";
    }
}

// 2. FETCH ACTIVE DATA LOGS FOR DISPLAY 
try {
    $courses = $pdo->query("SELECT * FROM courses ORDER BY course_code ASC")->fetchAll();
    $allocations = $pdo->query("SELECT a.*, c.course_code, c.course_title FROM course_allocations a JOIN courses c ON a.course_id = c.id ORDER BY a.created_at DESC")->fetchAll();
} catch (\PDOException $e) {
    $courses = []; $allocations = [];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Assign Course to Class Level</title>
    <style>
        body { font-family: Arial, sans-serif; background: #fff; padding: 15px; color: #333; margin: 0; }
        .card { background: #fdfdfd; padding: 22px; border: 1px solid #dee2e6; border-radius: 6px; margin-bottom: 20px; border-top: 4px solid #6f42c1; }
        input, select { width: 100%; padding: 11px; margin: 8px 0; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px; font-size: 14px; }
        table { width: 100%; border-collapse: collapse; margin-top: 15px; background: white; }
        th, td { border: 1px solid #dee2e6; padding: 11px; text-align: left; font-size: 13px; } th { background: #e9ecef; }
        .btn { padding: 11px 20px; background: #6f42c1; color: white; border: none; cursor: pointer; border-radius: 4px; font-weight: bold; font-size: 14px; width: 100%; }
        .btn:hover { background: #5a32a3; }
        .alert { padding: 12px; border-radius: 4px; margin-bottom: 18px; font-weight: bold; font-size: 14px; }
        .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .alert-danger { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
    </style>
</head>
<body>

    <h2 style="color: #333; border-bottom: 1px solid #eee; padding-bottom: 8px; font-size: 20px;">Course Allocation Manager</h2>
    <?php echo $message; ?>

    <div class="grid" style="display: grid; grid-template-columns: 1fr; gap: 20px;">
        <!-- INPUT COMPONENT BLOCK -->
        <div class="card">
            <h4 style="margin-top:0; color:#6f42c1; font-size: 15px;">Allocate Course Target to Student Cohort Class Profile</h4>
            <form method="POST" action="assign_class.php">
                <label style="font-size:12px; font-weight:bold;">Select Target Course Unit Code:</label>
                <select name="course_id" required>
                    <?php foreach ($courses as $c) { ?>
                        <option value="<?php echo $c['id']; ?>">[<?php echo htmlspecialchars($c['course_code']); ?>] - <?php echo htmlspecialchars($c['course_title']); ?></option>
                    <?php } ?>
                </select>

                <input type="text" name="dept_val" placeholder="Target Department (e.g., Computer Science)" required>
                <input type="text" name="lvl_val" placeholder="Target Class Level (e.g., ND I)" required>
                <input type="text" name="program_val" placeholder="Target Program Model (e.g., Full-Time)" required>
                <input type="text" name="session_val" placeholder="Target Active Session (e.g., 2025/2026)" required>
                
                <button type="submit" name="allocate_course" class="btn">Link Course to Class Cohort</button>
            </form>
        </div>

        <!-- MAPPED LEDGER LIST COMPONENT -->
        <div class="card" style="border-top-color: #343a40;">
            <h4 style="margin-top:0; color:#343a40; font-size: 15px;">Active Registered Allocation Mappings Table</h4>
            <?php if (empty($allocations)) { ?>
                <p style="color:#666; font-style:italic;">No course units have been assigned to class cohorts yet.</p>
            <?php } else { ?>
                <table>
                    <thead>
                        <tr>
                            <th>Course Assigned</th>
                            <th>Department Cohort</th>
                            <th>Level</th>
                            <th>Program</th>
                            <th>Session Year</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($allocations as $row) { ?>
                        <tr>
                            <td><span style="background: #eef2f7; padding: 4px 8px; border-radius: 4px; font-weight: bold; color: #0056b3;"><?php echo htmlspecialchars($row['course_code']); ?></span></td>
                            <td><?php echo htmlspecialchars($row['department']); ?></td>
                            <td><strong><?php echo htmlspecialchars($row['level']); ?></strong></td>
                            <td><?php echo htmlspecialchars($row['program']); ?></td>
                            <td><?php echo htmlspecialchars($row['session']); ?></td>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>
            <?php } ?>
        </div>
    </div>

</body>
</html>
