<?php
// admin/academic/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(); }

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

$user_role = $_SESSION['role'];
$success = "";
$error = "";

// 1. CREATE NEW SUBJECT
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_new_subject'])) {
    $new_name = trim($_POST['new_subject_name']);
    if (!empty($new_name)) {
        $check = $pdo->prepare("SELECT id FROM subjects WHERE subject_name = ?");
        $check->execute([$new_name]);
        if ($check->rowCount() == 0) {
            $stmt = $pdo->prepare("INSERT INTO subjects (subject_name) VALUES (?)");
            $stmt->execute([$new_name]);
            $success = "New subject '$new_name' added to library!";
        } else {
            $error = "Subject already exists in library.";
        }
    }
}

// 2. DELETE SUBJECT FROM MASTER LIBRARY
if (isset($_GET['delete_master'])) {
    $master_id = (int)$_GET['delete_master'];
    $check_usage = $pdo->prepare("SELECT id FROM teacher_subjects WHERE subject_id = ?");
    $check_usage->execute([$master_id]);
    
    if ($check_usage->rowCount() > 0) {
        $error = "Cannot delete: This subject is currently allocated to classes.";
    } else {
        $stmt = $pdo->prepare("DELETE FROM subjects WHERE id = ?");
        if ($stmt->execute([$master_id])) {
            header("Location: subjects.php?success=Subject removed");
            exit();
        }
    }
}

// 3. HANDLE ALLOCATION
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_allocation'])) {
    $subject_id = $_POST['subject_id'] ?? '';
    $class_id = $_POST['class_id'] ?? '';
    $teacher_id = $_POST['teacher_id'] ?? 0;

    if (!empty($subject_id) && !empty($class_id)) {
        $check = $pdo->prepare("SELECT id FROM teacher_subjects WHERE subject_id = ? AND class_id = ?");
        $check->execute([$subject_id, $class_id]);
        
        if ($check->rowCount() == 0) {
            $stmt = $pdo->prepare("INSERT INTO teacher_subjects (subject_id, class_id, teacher_id) VALUES (?, ?, ?)");
            $stmt->execute([$subject_id, $class_id, $teacher_id]);
            $success = "Subject successfully allocated!";
        } else {
            $error = "Already assigned to this class.";
        }
    }
}

// 4. HANDLE DELETE ALLOCATION
if (isset($_GET['delete_link'])) {
    $id = (int)$_GET['delete_link'];
    $pdo->prepare("DELETE FROM teacher_subjects WHERE id = ?")->execute([$id]);
    header("Location: subjects.php?success=Allocation removed");
    exit();
}

// 5. DATA FETCHING
$subject_library = $pdo->query("SELECT * FROM subjects ORDER BY subject_name ASC")->fetchAll();
$teachers = $pdo->query("SELECT id, fullname FROM users WHERE role = 'teacher' ORDER BY fullname ASC")->fetchAll();
$classes_dropdown = $pdo->query("SELECT c.*, s.section_name FROM classes c JOIN sections s ON c.section_id = s.id ORDER BY s.id, c.class_name ASC")->fetchAll();
$allocations = $pdo->query("SELECT ts.id as allocation_id, s.subject_name, c.class_name, u.fullname as teacher_name, sec.section_name FROM teacher_subjects ts JOIN subjects s ON ts.subject_id = s.id JOIN classes c ON ts.class_id = c.id JOIN sections sec ON c.section_id = sec.id LEFT JOIN users u ON ts.teacher_id = u.id ORDER BY c.class_name ASC, s.subject_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>Subject Management | Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { font-family: 'Inter', sans-serif; background: #f4f7f6; padding: 15px; color: #333; margin: 0; }
        .container { background: white; padding: 25px; border-radius: 12px; max-width: 1150px; margin: auto; box-shadow: 0 10px 30px rgba(0,0,0,0.05); }
        
        .forms-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 25px; margin-bottom: 30px; }
        .form-box { background: #f8f9fa; padding: 20px; border-radius: 10px; border: 1px solid #e9ecef; }
        
        h2 { font-size: 22px; margin-bottom: 20px; }
        h3 { margin-top: 0; font-size: 16px; color: #2c3e50; border-bottom: 2px solid #3498db; display: inline-block; padding-bottom: 5px; margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-size: 12px; font-weight: bold; color: #666; }
        
        input, select { padding: 10px; border: 1px solid #ddd; border-radius: 6px; width: 100%; box-sizing: border-box; margin-bottom: 12px; font-size: 14px; }
        
        .btn { padding: 10px 20px; border: none; border-radius: 6px; cursor: pointer; font-weight: bold; width: 100%; transition: 0.3s; }
        .btn-blue { background: #3498db; color: white; }
        .btn-green { background: #2ecc71; color: white; }

        table { width: 100%; border-collapse: collapse; margin-top: 15px; }
        th { background: #34495e; color: white; padding: 12px; text-align: left; font-size: 11px; text-transform: uppercase; }
        td { padding: 12px; border-bottom: 1px solid #eee; font-size: 14px; }
        
        .badge { padding: 4px 8px; border-radius: 4px; font-size: 11px; color: white; font-weight: bold; }
        .bg-cls { background: #9b59b6; }
        .bg-teacher { background: #34495e; }
        
        .master-list { max-height: 150px; overflow-y: auto; background: white; border: 1px solid #ddd; border-radius: 6px; padding: 10px; }
        .master-item { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #f1f1f1; font-size: 13px; }

        /* RESPONSIVE DESIGN */
        @media (max-width: 850px) {
            .forms-grid { grid-template-columns: 1fr; }
            .container { padding: 15px; }
        }

        @media (max-width: 600px) {
            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: 8px; padding: 10px; background: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.02); }
            td { border: none; position: relative; padding-left: 50%; text-align: right; min-height: 35px; }
            td:before { 
                position: absolute; left: 10px; width: 45%; padding-right: 10px; 
                white-space: nowrap; text-align: left; font-weight: bold; color: #7f8c8d;
                content: attr(data-label); 
            }
        }
    </style>
</head>
<body>

<div class="container">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
        <a href="../dashboard.php" style="text-decoration:none; color:#3498db; font-size: 14px;"><i class="fa fa-arrow-left"></i> Dashboard</a>
        <span style="font-size: 11px; background: #eee; padding: 3px 8px; border-radius: 4px;">Role: <?= strtoupper($user_role) ?></span>
    </div>

    <h2><i class="fa fa-book-open"></i> Subject Management</h2>

    <?php if($success || isset($_GET['success'])): ?>
        <div style="padding:12px; 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; ?>

    <div class="forms-grid">
        <div class="form-box">
            <h3>1. Subject Library</h3>
            <form method="POST">
                <label>Add New Name</label>
                <div style="display:flex; gap:5px;">
                    <input type="text" name="new_subject_name" placeholder="e.g. Physics" required style="margin-bottom:0;">
                    <button type="submit" name="create_new_subject" class="btn btn-blue" style="width:auto;">Add</button>
                </div>
            </form>
            <br>
            <label>Master Library</label>
            <div class="master-list">
                <?php foreach($subject_library as $sl): ?>
                    <div class="master-item">
                        <span><?= htmlspecialchars($sl['subject_name']) ?></span>
                        <a href="?delete_master=<?= $sl['id'] ?>" style="color:#e74c3c;" onclick="return confirm('Delete from library?')">
                            <i class="fa fa-times-circle"></i>
                        </a>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="form-box">
            <h3>2. Link Subject to Class</h3>
            <form method="POST">
                <div style="display:grid; grid-template-columns: 1fr 1fr; gap:10px;">
                    <div>
                        <label>Subject</label>
                        <select name="subject_id" required>
                            <option value="">-- Select --</option>
                            <?php foreach($subject_library as $sl): ?>
                                <option value="<?= $sl['id'] ?>"><?= htmlspecialchars($sl['subject_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label>Target Class</label>
                        <select name="class_id" required>
                            <option value="">-- Select --</option>
                            <?php 
                            $curr_sec = "";
                            foreach($classes_dropdown as $cl): 
                                if($curr_sec != $cl['section_name']):
                                    if($curr_sec != "") echo "</optgroup>";
                                    echo "<optgroup label='".$cl['section_name']."'>";
                                    $curr_sec = $cl['section_name'];
                                endif;
                            ?>
                                <option value="<?= $cl['id'] ?>"><?= $cl['class_name'] ?></option>
                            <?php endforeach; if($curr_sec != "") echo "</optgroup>"; ?>
                        </select>
                    </div>
                </div>
                <label>Assign Teacher (Optional)</label>
                <select name="teacher_id">
                    <option value="0">-- Select Teacher --</option>
                    <?php foreach($teachers as $t): ?>
                        <option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['fullname']) ?></option>
                    <?php endforeach; ?>
                </select>
                <button type="submit" name="add_allocation" class="btn btn-green">Link to Class</button>
            </form>
        </div>
    </div>

    <h3><i class="fa fa-list"></i> Class Allocations</h3>
    
    <table>
        <thead>
            <tr>
                <th>Subject</th>
                <th>Class</th>
                <th>Section</th>
                <th>Teacher</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($allocations as $a): ?>
            <tr>
                <td data-label="Subject"><strong><?= htmlspecialchars($a['subject_name']) ?></strong></td>
                <td data-label="Class"><span class="badge bg-cls"><?= $a['class_name'] ?></span></td>
                <td data-label="Section"><?= $a['section_name'] ?></td>
                <td data-label="Teacher"><span class="badge bg-teacher"><?= $a['teacher_name'] ?? 'Unassigned' ?></span></td>
                <td data-label="Action">
                    <a href="?delete_link=<?= $a['allocation_id'] ?>" style="color:#e74c3c; font-weight:bold; text-decoration:none;" onclick="return confirm('Unlink subject?')">
                        <i class="fa fa-trash"></i> Unlink
                    </a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

</body>
</html>