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

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

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

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

// 2. DELETE FROM MASTER LIST
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    // Check if it's being used in assignments first to prevent database errors
    $checkUsage = $pdo->prepare("SELECT id FROM teacher_subjects WHERE subject_id = ?");
    $checkUsage->execute([$id]);
    if ($checkUsage->rowCount() > 0) {
        $error = "Cannot delete! This subject is currently assigned to classes. Remove assignments first.";
    } else {
        $stmt = $pdo->prepare("DELETE FROM subjects WHERE id = ?");
        $stmt->execute([$id]);
        header("Location: subject_library.php?success=Deleted");
        exit();
    }
}

// 3. FETCH ALL MASTER SUBJECTS
$subjects = $pdo->query("SELECT * FROM subjects ORDER BY subject_name ASC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Subject Library | <?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; --bg: #f4f7f6; }
        body { font-family: 'Inter', sans-serif; background: var(--bg); padding: 20px; }
        .container { background: white; padding: 30px; border-radius: 12px; max-width: 800px; margin: auto; box-shadow: 0 5px 20px rgba(0,0,0,0.05); }
        .header { border-bottom: 2px solid #eee; padding-bottom: 15px; margin-bottom: 25px; }
        .lib-form { display: flex; gap: 10px; margin-bottom: 30px; }
        input { flex: 1; padding: 12px; border: 1px solid #ddd; border-radius: 6px; }
        .btn-add { background: #27ae60; color: white; border: none; padding: 12px 25px; border-radius: 6px; cursor: pointer; font-weight: bold; }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 15px; text-align: left; border-bottom: 1px solid #eee; }
        th { background: #f8f9fa; color: #7f8c8d; font-size: 12px; text-transform: uppercase; }
        .back-link { text-decoration: none; color: #3498db; font-size: 14px; margin-bottom: 15px; display: inline-block; }
    </style>
</head>
<body>

<div class="container">
    <a href="../dashboard.php" class="back-link"><i class="fa fa-arrow-left"></i> Back to Dashboard</a>
    
    <div class="header">
        <h2><i class="fa fa-book"></i> Master Subject Library</h2>
        <p style="color: #666; font-size: 14px;">Manage the clean list of subjects used across the entire school.</p>
    </div>

    <?php if($success || isset($_GET['success'])): ?>
        <div style="background: #d4edda; color: #155724; padding: 10px; border-radius: 5px; margin-bottom: 20px;">
            <i class="fa fa-check"></i> Subject added/updated successfully.
        </div>
    <?php endif; ?>

    <?php if($error): ?>
        <div style="background: #f8d7da; color: #721c24; padding: 10px; border-radius: 5px; margin-bottom: 20px;">
            <i class="fa fa-exclamation-circle"></i> <?php echo $error; ?>
        </div>
    <?php endif; ?>

    <form method="POST" class="lib-form">
        <input type="text" name="subject_name" placeholder="Enter clean name (e.g. Mathematics)" required>
        <button type="submit" name="add_master" class="btn-add">Add to Library</button>
    </form>

    <table>
        <thead>
            <tr>
                <th width="10%">ID</th>
                <th>Subject Name</th>
                <th width="15%">Action</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($subjects as $s): ?>
            <tr>
                <td>#<?php echo $s['id']; ?></td>
                <td><strong><?php echo htmlspecialchars($s['subject_name']); ?></strong></td>
                <td>
                    <a href="?delete=<?php echo $s['id']; ?>" 
                       style="color: #e74c3c; text-decoration: none;"
                       onclick="return confirm('Delete this subject from the whole system?')">
                       <i class="fa fa-trash"></i>
                    </a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

</body>
</html>