<?php
session_start();
require_once("public/connection.php");

if (!isset($_SESSION['staff'])) {
    die("Access denied");
}

$staff_id = (int)$_SESSION['staff'];

/* =========================
   FETCH SUBJECT → CLASS MAP
========================= */
$subjectClassMap = [];
$stmt = $connection->prepare("
    SELECT subject, class 
    FROM subject_teacher 
    WHERE staff_id = ?
");
$stmt->bind_param("i", $staff_id);
$stmt->execute();
$res = $stmt->get_result();
while ($r = $res->fetch_assoc()) {
    $subjectClassMap[$r['subject']][] = $r['class'];
}
$stmt->close();

/* =========================
   DOWNLOAD HANDLER
========================= */
if (isset($_POST['download_id'])) {
    $id = (int)$_POST['download_id'];

    $stmt = $connection->prepare("
        SELECT lp.file_path 
        FROM lesson_plans lp
        INNER JOIN subject_teacher st 
            ON lp.subject = st.subject 
           AND lp.class = st.class
        WHERE lp.id = ? AND st.staff_id = ?
    ");
    $stmt->bind_param("ii", $id, $staff_id);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($res->num_rows === 1) {
        $file = $res->fetch_assoc()['file_path'];
        $base = realpath($_SERVER['DOCUMENT_ROOT'] . "/uploads/lesson_plans/");
        $full = realpath($base . "/" . basename($file));

        if ($full && strpos($full, $base) === 0 && file_exists($full)) {
            header("Content-Type: application/pdf");
            header("Content-Disposition: attachment; filename=\"" . basename($full) . "\"");
            header("Content-Length: " . filesize($full));
            readfile($full);
            exit;
        }
    }

    $_SESSION['msg'] = "File not found or access denied";
    $_SESSION['type'] = "danger";
    header("Location: teacher_lesson_plans");
    exit;
}

/* =========================
   UPLOAD HANDLER
========================= */
if (isset($_POST['upload_btn'])) {

    $subject = trim($_POST['subject']);
    $class   = trim($_POST['class']);
    $term    = trim($_POST['term']);
    $session = trim($_POST['session']);

    // validate teacher assignment
    $check = $connection->prepare("
        SELECT id FROM subject_teacher 
        WHERE staff_id = ? AND subject = ? AND class = ?
    ");
    $check->bind_param("iss", $staff_id, $subject, $class);
    $check->execute();
    $check->store_result();

    if ($check->num_rows === 0) {
        $_SESSION['msg'] = "You are not assigned to this subject/class";
        $_SESSION['type'] = "danger";
        header("Location: teacher_lesson_plans");
        exit;
    }
    $check->close();

    $file = $_FILES['file'] ?? null;

    if ($file && $file['name']) {
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

        if ($ext !== 'pdf') {
            $_SESSION['msg'] = "Only PDF files allowed";
            $_SESSION['type'] = "danger";
        } else {
            $newName = time() . "_" . basename($file['name']);
            $path = "uploads/lesson_plans/" . $newName;

            if (move_uploaded_file($file['tmp_name'], $path)) {
                $stmt = $connection->prepare("
                    INSERT INTO lesson_plans
                    (file_name, file_path, subject, class, term, session, upload_date)
                    VALUES (?, ?, ?, ?, ?, ?, NOW())
                ");
                $stmt->bind_param(
                    "ssssss",
                    $file['name'], $path, $subject, $class, $term, $session
                );
                $stmt->execute();
                $stmt->close();

                $_SESSION['msg'] = "Lesson plan uploaded successfully";
                $_SESSION['type'] = "success";
            }
        }
    }

    header("Location: teacher_lesson_plans");
    exit;
}
?>

<!-- =========================
     PAGE UI
========================= -->

<div class="page-title">
    <h3><i class="fa fa-book"></i> Teacher Lesson Plans</h3>
</div>

<?php if(isset($_SESSION['msg'])): ?>
<div class="alert alert-<?= $_SESSION['type']; ?>">
    <?= $_SESSION['msg']; ?>
</div>
<?php unset($_SESSION['msg'], $_SESSION['type']); endif; ?>

<div class="card">
<div class="panel panel-primary">
<div class="panel-heading text-center">
    <h4>Upload Lesson Plan</h4>
</div>

<div class="panel-body">
<form method="POST" enctype="multipart/form-data">
<div class="row">

<div class="col-md-3">
    <label>Subject</label>
    <select class="form-control" name="subject" id="subjectSelect" required>
        <option value="">Select Subject</option>
        <?php foreach ($subjectClassMap as $sub => $cls): ?>
            <option value="<?= htmlspecialchars($sub) ?>"><?= htmlspecialchars($sub) ?></option>
        <?php endforeach; ?>
    </select>
</div>

<div class="col-md-3">
    <label>Class</label>
    <select class="form-control" name="class" id="classSelect" required>
        <option>Select subject first</option>
    </select>
</div>

<div class="col-md-2">
    <label>Term</label>
    <select class="form-control" name="term" required>
        <option>First Term</option>
        <option>Second Term</option>
        <option>Third Term</option>
    </select>
</div>

<div class="col-md-2">
    <label>Session</label>
    <select class="form-control" name="session" required>
        <?php
        $q = mysqli_query($connection, "SELECT current_session FROM current_season");
        while ($r = mysqli_fetch_assoc($q)) {
            echo "<option>{$r['current_session']}</option>";
        }
        ?>
    </select>
</div>

<div class="col-md-6">
    <input type="file" name="file" class="form-control" required>
</div>

<div class="col-md-2">
    <button name="upload_btn" class="btn btn-primary">Upload</button>
</div>

</div>
</form>
</div>
</div>
</div>

<!-- =========================
     DISPLAY LESSON PLANS
========================= -->

<div class="card">
<div class="panel panel-primary">
<div class="panel-heading text-center">
    <h4>My Lesson Plans</h4>
</div>

<div class="panel-body table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
    <th>File</th>
    <th>Subject</th>
    <th>Class</th>
    <th>Term</th>
    <th>Session</th>
    <th>Date</th>
    <th>Download</th>
</tr>
</thead>
<tbody>

<?php
$stmt = $connection->prepare("
    SELECT lp.*
    FROM lesson_plans lp
    INNER JOIN subject_teacher st 
        ON lp.subject = st.subject 
       AND lp.class = st.class
    WHERE st.staff_id = ?
    ORDER BY lp.upload_date DESC
");
$stmt->bind_param("i", $staff_id);
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()):
?>
<tr>
    <td><?= htmlspecialchars($row['file_name']) ?></td>
    <td><?= htmlspecialchars($row['subject']) ?></td>
    <td><?= htmlspecialchars($row['class']) ?></td>
    <td><?= htmlspecialchars($row['term']) ?></td>
    <td><?= htmlspecialchars($row['session']) ?></td>
    <td><?= htmlspecialchars($row['upload_date']) ?></td>
    <td>
        <form method="POST">
            <input type="hidden" name="download_id" value="<?= $row['id'] ?>">
            <button class="btn btn-success btn-sm">Download</button>
        </form>
    </td>
</tr>
<?php endwhile; ?>

</tbody>
</table>
</div>
</div>
</div>

<script>
const map = <?= json_encode($subjectClassMap); ?>;

document.getElementById('subjectSelect').addEventListener('change', function () {
    const cls = document.getElementById('classSelect');
    cls.innerHTML = '<option>Select Class</option>';

    if (map[this.value]) {
        map[this.value].forEach(c => {
            cls.innerHTML += `<option value="${c}">${c}</option>`;
        });
    }
});
</script>
