<?php
// admin/academic/assign_subjects.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 ---
// Protect the page - allow both admin and subadmin
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'subadmin'])) {
    header("Location: ../../auth/login.php");
    exit();
}

$success = "";
$error = "";

// 1. HANDLE DELETE LOGIC
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $stmt = $pdo->prepare("DELETE FROM teacher_subjects WHERE id = ?");
    if ($stmt->execute([$id])) {
        header("Location: assign_subjects.php?success=Assignment removed successfully");
        exit();
    }
}

// 2. HANDLE ASSIGNMENT LOGIC
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['assign'])) {
    $teacher_id = $_POST['teacher_id'];
    $class_id = $_POST['class_id'];
    $subject_id = $_POST['subject_id'];

    if (!empty($teacher_id) && !empty($class_id) && !empty($subject_id)) {
        $check = $pdo->prepare("SELECT id FROM teacher_subjects WHERE teacher_id = ? AND class_id = ? AND subject_id = ?");
        $check->execute([$teacher_id, $class_id, $subject_id]);

        if ($check->rowCount() == 0) {
            $stmt = $pdo->prepare("INSERT INTO teacher_subjects (teacher_id, class_id, subject_id) VALUES (?, ?, ?)");
            if ($stmt->execute([$teacher_id, $class_id, $subject_id])) {
                $success = "Assignment created successfully!";
            } else {
                $error = "An error occurred while saving.";
            }
        } else {
            $error = "This teacher is already assigned to this subject for this class.";
        }
    } else {
        $error = "All fields are required.";
    }
}

// 3. FETCH DATA
$teachers = $pdo->query("SELECT id, fullname FROM users WHERE role = 'teacher' ORDER BY fullname ASC")->fetchAll();
$classes = $pdo->query("SELECT id, class_name FROM classes ORDER BY class_name ASC")->fetchAll();
$subjects = $pdo->query("SELECT id, subject_name FROM subjects ORDER BY subject_name ASC")->fetchAll();

$sql = "SELECT ts.id, u.fullname, c.class_name, s.subject_name 
        FROM teacher_subjects ts
        JOIN users u ON ts.teacher_id = u.id
        JOIN classes c ON ts.class_id = c.id
        JOIN subjects s ON ts.subject_id = s.id
        ORDER BY c.class_name ASC, s.subject_name ASC";
$assignments = $pdo->query($sql)->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Subject Allocation | Portal</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #2c3e50; --accent: #3498db; --bg: #f4f7f6; --danger: #e74c3c; }
        body { font-family: 'Inter', sans-serif; background: var(--bg); margin: 0; padding: 15px; color: #333; }
        .container { background: white; padding: 25px; border-radius: 12px; max-width: 1000px; margin: auto; box-shadow: 0 5px 25px rgba(0,0,0,0.05); }
        
        .header-area { border-bottom: 2px solid #eee; margin-bottom: 25px; padding-bottom: 15px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; }
        h2 { color: var(--primary); margin: 0; font-size: 22px; }
        
        .assignment-form { 
            display: grid; 
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); 
            gap: 15px; 
            margin-bottom: 35px; 
            background: #fdfdfd; 
            padding: 20px; 
            border-radius: 10px; 
            border: 1px solid #eee;
            align-items: end;
        }
        
        .form-group { display: flex; flex-direction: column; gap: 6px; }
        label { font-size: 11px; font-weight: 700; color: #7f8c8d; text-transform: uppercase; }
        select { padding: 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 14px; background: white; width: 100%; }
        
        button { padding: 13px; background: var(--accent); color: white; border: none; cursor: pointer; border-radius: 8px; font-weight: bold; transition: 0.3s; }
        button:hover { background: #2980b9; transform: translateY(-2px); }
        
        /* RESPONSIVE TABLE */
        table { width: 100%; border-collapse: collapse; }
        th { background: var(--primary); color: white; padding: 12px; text-align: left; font-size: 11px; text-transform: uppercase; }
        td { padding: 15px 12px; border-bottom: 1px solid #eee; font-size: 14px; }
        .badge-class { background: #e8f4fd; color: #2980b9; padding: 4px 10px; border-radius: 4px; font-weight: bold; font-size: 12px; }

        @media screen and (max-width: 768px) {
            .header-area { flex-direction: column; align-items: flex-start; }
            .assignment-form { 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: 15px; border-radius: 10px; padding: 10px; background: #fff; box-shadow: 0 2px 5px rgba(0,0,0,0.02); }
            td { border: none; border-bottom: 1px solid #f9f9f9; position: relative; padding-left: 45%; text-align: right; }
            td::before {
                content: attr(data-label);
                position: absolute; left: 10px; width: 40%; text-align: left;
                font-weight: 700; color: var(--primary); font-size: 11px; text-transform: uppercase;
            }
            td:last-child { border-bottom: none; text-align: center; padding-left: 12px; }
        }
    </style>
</head>
<body>

<div class="container">
    <div class="header-area">
        <div>
            <h2><i class="fa fa-link"></i> Subject Allocation</h2>
            <p style="color: #7f8c8d; font-size: 13px; margin: 5px 0 0 0;">Managing as: <strong><?= strtoupper($_SESSION['role']) ?></strong></p>
        </div>
        <a href="../dashboard.php" style="text-decoration:none; color:var(--accent); font-weight:bold; font-size: 14px;">
            <i class="fa fa-arrow-left"></i> Dashboard
        </a>
    </div>

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

    <form method="POST" class="assignment-form">
        <div class="form-group">
            <label>Teacher</label>
            <select name="teacher_id" required>
                <option value="">-- Select Teacher --</option>
                <?php foreach($teachers as $t): ?>
                    <option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['fullname']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group">
            <label>Class</label>
            <select name="class_id" required>
                <option value="">-- Select Class --</option>
                <?php foreach($classes as $c): ?>
                    <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['class_name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group">
            <label>Subject</label>
            <select name="subject_id" required>
                <option value="">-- Select Subject --</option>
                <?php foreach($subjects as $s): ?>
                    <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['subject_name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <button type="submit" name="assign"><i class="fa fa-plus-circle"></i> Assign</button>
    </form>

    <table>
        <thead>
            <tr>
                <th>Teacher</th>
                <th>Class</th>
                <th>Subject</th>
                <th style="text-align: center;">Action</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($assignments as $a): ?>
            <tr>
                <td data-label="Teacher" style="font-weight: 600;"><?= htmlspecialchars($a['fullname']) ?></td>
                <td data-label="Class"><span class="badge-class"><?= htmlspecialchars($a['class_name']) ?></span></td>
                <td data-label="Subject"><?= htmlspecialchars($a['subject_name']) ?></td>
                <td data-label="Action">
                    <a href="?delete=<?= $a['id'] ?>" 
                       style="color:var(--danger); text-decoration: none; font-weight: bold;"
                       onclick="return confirm('Remove this assignment?')">
                       <i class="fa fa-trash"></i> Remove
                    </a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

</body>
</html>