<?php
// Filename: admin_subjects.php
require 'config.php';
requireLogin();

// 1. PERMISSION CHECK
$uid = $_SESSION['user_id'];
$user_roles = explode(',', $_SESSION['role'] ?? '');
$allowed_roles = ['admin', 'principal', 'assistant', 'timetable_coord'];

if (empty(array_intersect($user_roles, $allowed_roles))) {
    header("Location: dashboard.php"); exit;
}

$msg = ''; $msg_type = '';

// 2. ACTIONS
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // SAVE SUBJECT (Add or Update)
    if (isset($_POST['action']) && $_POST['action'] === 'save_subject') {
        
        $id = $_POST['subject_id'] ?? null;
        $name = trim($_POST['subject_name']);
        $code = trim($_POST['subject_code']);
        $type = $_POST['type'] ?? 'core'; // New Field

        try {
            if ($id) {
                // UPDATE
                $stmt = $pdo->prepare("UPDATE subjects SET subject_name=?, subject_code=?, type=? WHERE id=?");
                $stmt->execute([$name, $code, $type, $id]);
                $msg = "Subject updated successfully.";
            } else {
                // INSERT
                $stmt = $pdo->prepare("INSERT INTO subjects (subject_name, subject_code, type) VALUES (?, ?, ?)");
                $stmt->execute([$name, $code, $type]);
                $msg = "Subject created successfully.";
            }
            $msg_type = "success";
        } catch (Exception $e) {
            $msg = "Error: " . $e->getMessage(); 
            $msg_type = "danger";
        }
    }

    // DELETE SUBJECT
    if (isset($_POST['action']) && $_POST['action'] === 'delete_subject') {
        $id = $_POST['delete_id'];
        try {
            $pdo->prepare("DELETE FROM subjects WHERE id=?")->execute([$id]);
            $msg = "Subject deleted."; $msg_type = "warning";
        } catch (Exception $e) {
            $msg = "Cannot delete: Subject is currently in use."; $msg_type = "danger";
        }
    }
}

// 3. FETCH DATA
$search = $_GET['search'] ?? '';
$sql = "SELECT * FROM subjects WHERE 1=1";
$params = [];

if ($search) {
    $sql .= " AND (subject_name LIKE ? OR subject_code LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$sql .= " ORDER BY subject_name ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$subjects = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>Manage Subjects</title>
    
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">

    <style>
        :root { --primary-grad: <?= getHeaderTheme() ?>; --bg-color: #f8f9fd; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 90px; }

        /* HEADER */
        .app-header {
            background: var(--primary-grad); padding: 30px 20px 80px 20px;
            border-radius: 0 0 35px 35px; color: white; text-align: center;
        }

        /* FLOATING CARD */
        .floating-card {
            background: white; margin: -60px 20px 20px 20px;
            border-radius: 24px; padding: 20px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.08);
            position: relative; z-index: 10;
        }

        /* SUBJECT ITEM */
        .subject-item { 
            background: white; border-radius: 16px; padding: 15px; margin-bottom: 10px; 
            border: 1px solid #f1f5f9; display: flex; align-items: center; justify-content: space-between;
            transition: transform 0.2s;
        }
        .subject-item:active { transform: scale(0.98); background: #f8fafc; }

        .icon-box {
            width: 45px; height: 45px; border-radius: 12px; flex-shrink: 0;
            display: flex; align-items: center; justify-content: center; margin-right: 15px;
            font-size: 1.2rem; background: #e0f2fe; color: #0ea5e9;
        }
        
        /* New Badge Styles */
        .badge-core { background: #e0f2fe; color: #0284c7; border: 1px solid #bae6fd; }
        .badge-elective { background: #fdf2f8; color: #db2777; border: 1px solid #fbcfe8; }

        /* FORM ELEMENTS */
        .form-control, .form-select { border-radius: 12px; padding: 10px; border: 1px solid #e2e8f0; background: #f8fafc; font-size: 0.9rem; }
        .form-control:focus, .form-select:focus { border-color: #8B5CF6; background: white; box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.1); }
        .form-label { font-size: 0.75rem; font-weight: 700; color: #64748b; margin-bottom: 4px; text-transform: uppercase; }

        /* BOTTOM NAV 
        .bottom-nav { position: fixed; bottom: 0; left: 0; right: 0; background: white; padding: 10px 30px 18px 30px; display: flex; justify-content: space-between; border-radius: 30px 30px 0 0; box-shadow: 0 -5px 20px rgba(0,0,0,0.05); z-index: 100; }
        .nav-btn { display: flex; flex-direction: column; align-items: center; color: #94a3b8; text-decoration: none; font-size: 0.7rem; font-weight: 600; }
        .nav-btn.active { color: #8B5CF6; }
        .nav-btn i { font-size: 1.4rem; margin-bottom: 4px; } */
    </style>
</head>
<body>

    <div class="app-header">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="admin_dashboard.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold fs-5">Subjects</div>
            <div style="width: 24px;"></div>
        </div>
        <div class="opacity-75 small">Manage Academic Courses</div>
    </div>

    <div class="floating-card">
        <?php if($msg): ?><div class="alert alert-<?= $msg_type ?> border-0 shadow-sm rounded-3 text-center small mb-3"><?= $msg ?></div><?php endif; ?>

        <div class="d-flex justify-content-between align-items-center mb-3">
            <h6 class="fw-bold text-dark m-0">Total Subjects: <?= count($subjects) ?></h6>
            <button class="btn btn-sm btn-primary rounded-pill fw-bold px-3 shadow-sm" onclick="openModal()">
                <i class="bi bi-plus-lg me-1"></i> Add New
            </button>
        </div>

        <form method="GET">
            <div class="input-group">
                <span class="input-group-text bg-light border-0 ps-3 rounded-start-pill"><i class="bi bi-search text-muted"></i></span>
                <input type="text" name="search" class="form-control border-0 bg-light rounded-end-pill fw-bold" placeholder="Search subjects..." value="<?= htmlspecialchars($search) ?>">
            </div>
        </form>
    </div>

    <div class="px-3 pb-4">
        <?php if(empty($subjects)): ?>
            <div class="text-center py-5 text-muted small opacity-50">
                <i class="bi bi-book display-1"></i><br>No subjects found.
            </div>
        <?php else: ?>
            <div class="d-flex flex-column gap-2">
                <?php foreach($subjects as $s): 
                    $badgeClass = ($s['type'] === 'elective') ? 'badge-elective' : 'badge-core';
                    $badgeText = ($s['type'] === 'elective') ? 'Elective' : 'Core';
                ?>
                <div class="subject-item">
                    <div class="d-flex align-items-center overflow-hidden">
                        <div class="icon-box">
                            <span style="font-size:0.8rem; font-weight:800;"><?= substr($s['subject_name'], 0, 2) ?></span>
                        </div>
                        <div class="text-truncate">
                            <div class="fw-bold text-dark text-truncate" style="max-width: 180px;"><?= htmlspecialchars($s['subject_name']) ?></div>
                            <div class="d-flex gap-2 align-items-center mt-1">
                                <span class="badge bg-light text-secondary border"><?= htmlspecialchars($s['subject_code']) ?></span>
                                <span class="badge <?= $badgeClass ?> rounded-pill"><?= $badgeText ?></span>
                            </div>
                        </div>
                    </div>
                    <div class="d-flex gap-2 ms-2">
                        <button class="btn btn-light border btn-sm rounded-circle text-primary" onclick='editSubject(<?= json_encode($s) ?>)'>
                            <i class="bi bi-pencil-fill"></i>
                        </button>
                        <form method="POST" onsubmit="return confirm('Delete this subject? Timetables using it may break.')" style="margin:0;">
                            <input type="hidden" name="action" value="delete_subject">
                            <input type="hidden" name="delete_id" value="<?= $s['id'] ?>">
                            <button class="btn btn-light border btn-sm rounded-circle text-danger">
                                <i class="bi bi-trash-fill"></i>
                            </button>
                        </form>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <div class="modal fade" id="subjectModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 shadow rounded-4">
                <div class="modal-header border-0 bg-primary text-white">
                    <h6 class="modal-title fw-bold" id="modalTitle">Add Subject</h6>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="save_subject">
                    <input type="hidden" name="subject_id" id="inp_id">
                    
                    <div class="modal-body p-4">
                        <div class="mb-3">
                            <label class="form-label text-muted">Subject Name</label>
                            <input type="text" name="subject_name" id="inp_name" class="form-control" placeholder="e.g. Mathematics" required>
                        </div>
                        
                        <div class="row g-2 mb-3">
                            <div class="col-6">
                                <label class="form-label text-muted">Code</label>
                                <input type="text" name="subject_code" id="inp_code" class="form-control" placeholder="e.g. MAT" required>
                            </div>
                            <div class="col-6">
                                <label class="form-label text-muted">Type</label>
                                <select name="type" id="inp_type" class="form-select">
                                    <option value="core">Core (All)</option>
                                    <option value="elective">Elective (Selected)</option>
                                </select>
                            </div>
                        </div>

                        <div class="alert alert-info small border-0 py-2">
                            <i class="bi bi-info-circle me-1"></i> <strong>Elective:</strong> Use for subjects that split classes (e.g., Biology/Physics at the same time).
                        </div>

                    </div>
                    <div class="modal-footer border-0 pt-0">
                        <button type="button" class="btn btn-light text-muted fw-bold rounded-pill" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary fw-bold rounded-pill px-4 flex-grow-1">Save Subject</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'menu.php'; ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const modal = new bootstrap.Modal(document.getElementById('subjectModal'));

        function openModal() {
            document.getElementById('modalTitle').innerText = "Add New Subject";
            document.getElementById('inp_id').value = "";
            document.getElementById('inp_name').value = "";
            document.getElementById('inp_code').value = "";
            document.getElementById('inp_type').value = "core";
            modal.show();
        }

        function editSubject(s) {
            document.getElementById('modalTitle').innerText = "Edit Subject";
            document.getElementById('inp_id').value = s.id;
            document.getElementById('inp_name').value = s.subject_name;
            document.getElementById('inp_code').value = s.subject_code;
            document.getElementById('inp_type').value = s.type || 'core';
            modal.show();
        }
    </script>
</body>
</html>