<?php
// admin/academic/classes.php
$projectRoot = dirname(dirname(__DIR__));
require_once $projectRoot . '/config/database.php';
require_once $projectRoot . '/config/config.php';

if (session_status() === PHP_SESSION_NONE) { session_start(); }

// --- UPDATED AUTH CHECK ---
// Allow both admin and subadmin roles
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'subadmin'])) {
    header("Location: ../../auth/login.php");
    exit();
}

// Handle Add Class
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_class'])) {
    $class_name = trim($_POST['class_name']);
    $section_id = $_POST['section_id'];

    if (!empty($class_name) && !empty($section_id)) {
        $stmt = $pdo->prepare("INSERT INTO classes (class_name, section_id) VALUES (?, ?)");
        $stmt->execute([$class_name, $section_id]);
        $success = "Class created successfully!";
    }
}

// Handle Delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $pdo->prepare("DELETE FROM classes WHERE id = ?")->execute([$id]);
    header("Location: classes.php?success=Class removed");
    exit();
}

$sections = $pdo->query("SELECT * FROM sections")->fetchAll();
$classes = $pdo->query("
    SELECT classes.*, sections.section_name 
    FROM classes 
    JOIN sections ON classes.section_id = sections.id 
    ORDER BY sections.id ASC, classes.class_name ASC
")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Classes | <?php echo htmlspecialchars($school_name); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #2c3e50; --success: #27ae60; --danger: #e74c3c; --accent: #3498db; }
        
        body { font-family: 'Inter', 'Segoe UI', sans-serif; background: #f4f7f6; margin: 0; padding: 10px; color: #333; }
        .container { background: white; padding: 20px; border-radius: 12px; max-width: 900px; margin: 10px auto; box-shadow: 0 5px 20px rgba(0,0,0,0.05); }
        
        h2 { font-size: 1.5rem; color: var(--primary); margin: 15px 0; }
        
        /* RESPONSIVE FORM GRID */
        .form-grid { 
            display: grid; 
            grid-template-columns: 2fr 1fr auto; 
            gap: 10px; 
            background: #f8f9fa; 
            padding: 20px; 
            border-radius: 8px; 
            margin-bottom: 25px;
            border: 1px solid #eee;
        }

        input, select { padding: 12px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; width: 100%; box-sizing: border-box; }
        
        .btn-add { 
            background: var(--success); 
            color: white; 
            border: none; 
            padding: 12px 25px; 
            border-radius: 6px; 
            font-weight: bold; 
            cursor: pointer;
            transition: 0.3s;
        }
        .btn-add:hover { background: #219150; }

        /* TABLE STYLING */
        table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        th { background: var(--primary); color: white; padding: 15px; text-align: left; font-size: 13px; }
        td { padding: 15px; border-bottom: 1px solid #eee; font-size: 14px; }
        
        .badge { padding: 5px 12px; border-radius: 20px; font-size: 11px; color: white; font-weight: bold; text-transform: uppercase; }
        .bg-nursery { background: #8e44ad; }
        .bg-primary { background: #2980b9; }
        .bg-secondary { background: #27ae60; }

        /* MOBILE RESPONSIVE QUERIES */
        @media (max-width: 768px) {
            .form-grid { grid-template-columns: 1fr; } 
            
            table, thead, tbody, th, td, tr { display: block; }
            thead tr { position: absolute; top: -9999px; left: -9999px; }
            tr { border: 1px solid #eee; margin-bottom: 10px; border-radius: 8px; padding: 10px; background: #fff; }
            td { border: none; position: relative; padding-left: 50%; text-align: right; }
            td:before { 
                position: absolute; left: 15px; width: 45%; padding-right: 10px; 
                white-space: nowrap; text-align: left; font-weight: bold; color: #7f8c8d;
                content: attr(data-label); 
            }
        }
        
        .back-link { text-decoration: none; color: var(--accent); font-weight: 600; font-size: 14px; }
    </style>
</head>
<body>

<div class="container">
    <a href="../dashboard.php" class="back-link"><i class="fa fa-arrow-left"></i> Dashboard</a>
    
    <div style="display: flex; justify-content: space-between; align-items: center;">
        <h2>Manage Classes</h2>
        <span style="font-size: 12px; color: #7f8c8d;">Role: <strong><?= strtoupper($_SESSION['role']) ?></strong></span>
    </div>

    <?php if(isset($success) || isset($_GET['success'])): ?>
        <div style="background: #d4edda; color: #155724; padding: 12px; border-radius: 6px; margin-bottom: 20px; font-size: 14px;">
            <i class="fa fa-check-circle"></i> <?= $success ?? $_GET['success'] ?>
        </div>
    <?php endif; ?>

    <form method="POST" class="form-grid">
        <input type="text" name="class_name" placeholder="Class Name (e.g. JSS 1)" required>
        <select name="section_id" required>
            <option value="">-- Section --</option>
            <?php foreach($sections as $sec): ?>
                <option value="<?= $sec['id'] ?>"><?= $sec['section_name'] ?></option>
            <?php endforeach; ?>
        </select>
        <button type="submit" name="add_class" class="btn-add">Create Class</button>
    </form>

    <table>
        <thead>
            <tr>
                <th>S/N</th>
                <th>Class Name</th>
                <th>Section</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php $sn=1; foreach($classes as $c): 
                $style = ($c['section_name'] == 'Nursery') ? 'bg-nursery' : (($c['section_name'] == 'Primary') ? 'bg-primary' : 'bg-secondary');
            ?>
            <tr>
                <td data-label="S/N"><?= $sn++ ?></td>
                <td data-label="Class"><strong><?= htmlspecialchars($c['class_name']) ?></strong></td>
                <td data-label="Section"><span class="badge <?= $style ?>"><?= $c['section_name'] ?></span></td>
                <td data-label="Action">
                    <a href="?delete=<?= $c['id'] ?>" style="color:var(--danger); text-decoration: none; font-weight: bold;" onclick="return confirm('Remove this class?')">
                        <i class="fa fa-trash"></i> Delete
                    </a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

</body>
</html>