<?php
// Upload curriculum
if (isset($_POST['upload_curriculum'])) {
    $title = $_POST['title'];
    $subject = $_POST['subject'];
    $class = $_POST['class'];
    $term = $_POST['term'];
    $sessionVal = $_POST['session'];
    $uploaded_by = $_SESSION['admin_name'] ?? 'Admin';

    $file = $_FILES['curriculum_file'];
    $filename = time() . "_" . basename($file['name']);
    $target = "uploads/curriculums/" . $filename;

    if (move_uploaded_file($file['tmp_name'], $target)) {
        $stmt = $connection->prepare("INSERT INTO curriculum (title, subject, class, term, session, file_path, uploaded_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sssssss", $title, $subject, $class, $term, $sessionVal, $target, $uploaded_by);
        if ($stmt->execute()) {
            $_SESSION['msg'] = "Curriculum uploaded successfully.";
            $_SESSION['type'] = "success";
        } else {
            $_SESSION['msg'] = "Upload failed: " . $stmt->error;
            $_SESSION['type'] = "danger";
        }
    } else {
        $_SESSION['msg'] = "Error uploading file.";
        $_SESSION['type'] = "danger";
    }
    header("Location: curriculum");
    exit;
}

// Delete curriculum
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $stmt = $connection->prepare("SELECT file_path FROM curriculum WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res->num_rows === 1) {
        $file = $res->fetch_assoc()['file_path'];
        if (file_exists($file)) unlink($file);
        $del = $connection->prepare("DELETE FROM curriculum WHERE id = ?");
        $del->bind_param("i", $id);
        $del->execute();
        $_SESSION['msg'] = "Curriculum deleted.";
        $_SESSION['type'] = "success";
    } else {
        $_SESSION['msg'] = "Curriculum not found.";
        $_SESSION['type'] = "danger";
    }
    header("Location: curriculum");
    exit;
}

// Download curriculum
if (isset($_GET['download'])) {
    $id = (int)$_GET['download'];
    $stmt = $connection->prepare("SELECT file_path FROM curriculum WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($res->num_rows === 1) {
        $file = $res->fetch_assoc()['file_path'];

        // Construct absolute file path
        $base_dir = realpath($_SERVER['DOCUMENT_ROOT'] . '/uploads/curriculums/'); // Adjust path as needed
        $full_path = realpath($base_dir . '/' . basename($file));

        // Validate that the file exists and is within the intended directory
        if ($full_path && strpos($full_path, $base_dir) === 0 && file_exists($full_path)) {
            // Clear output buffer to prevent any prior output
            ob_clean();
            flush();

            // Set headers for PDF download
            header('Content-Description: File Transfer');
            header('Content-Type: application/pdf');
            header('Content-Disposition: attachment; filename="' . basename($full_path) . '"');
            header('Content-Length: ' . filesize($full_path));
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');

            // Read the file
            readfile($full_path);
            exit;
        } else {
            $_SESSION['msg'] = "File not found or access denied.";
            $_SESSION['type'] = "danger";
        }
    } else {
        $_SESSION['msg'] = "Curriculum not found.";
        $_SESSION['type'] = "danger";
    }

    // Redirect to curriculum page on error
    header("Location: curriculum");
    exit;
}


// Fetch curriculum
$result = $connection->query("SELECT * FROM curriculum ORDER BY uploaded_at DESC");
?>

<div class="card">
    <div class='row'>
        <div class='col-xs-12 col-sm-12 col-md-12'>
            <div class='panel panel-primary ch'>
                <div class='panel-heading'>
                    <h4 class='text-center'>CURRICULUM MANAGEMENT</h4>
                </div>
                <div class='panel-body'>
                    <div class='mb-3 text-right'>
                        <button class='btn btn-sm btn-success' data-toggle='modal' data-target='#addCurriculumModal'>➕ Upload Curriculum</button>
                    </div>

                    <?php if ($result->num_rows > 0): ?>
                        <div class="table-responsive">
                            <table class="table">
                                <thead class="bg-primary text-white">
                                    <tr>
                                        <th>Title</th>
                                        <th>Subject</th>
                                        <th>Class</th>
                                        <th>Term</th>
                                        <th>Session</th>
                                        <th>Uploaded</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($row = $result->fetch_assoc()): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($row['title']) ?></td>
                                            <td><?= htmlspecialchars($row['subject']) ?></td>
                                            <td><?= htmlspecialchars($row['class']) ?></td>
                                            <td><?= htmlspecialchars($row['term']) ?></td>
                                            <td><?= htmlspecialchars($row['session']) ?></td>
                                            <td><?= date("d-M-Y", strtotime($row['uploaded_at'])) ?></td>
                                            <td>
                                                <a href="?download=<?= $row['id'] ?>" class="btn btn-xs btn-success">Download</a>
                                                <a href="?delete=<?= $row['id'] ?>" onclick="return confirm('Are you sure?')" class="btn btn-xs btn-danger">Delete</a>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <p class="text-danger text-center">No curriculum uploaded yet.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Upload Modal -->
<div class="modal fade" id="addCurriculumModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <form method="POST" enctype="multipart/form-data">
      <div class="modal-content">
        <div class="modal-header bg-primary text-white">
          <h5 class="modal-title">Upload Curriculum</h5>
          <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
        </div>

        <div class="modal-body">
            <input type="text" name="title" class="form-control mb-2" placeholder="Curriculum Title" required>

            <select name="subject" class="form-control mb-2" required>
                <option value="" disabled selected>Select Subject</option>
                <?php
                $subjects = $connection->query("SELECT DISTINCT subjects FROM school_subjects");
                while ($s = $subjects->fetch_assoc()) {
                    echo "<option value='{$s['subjects']}'>{$s['subjects']}</option>";
                }
                ?>
            </select>

            <select name="class" class="form-control mb-2" required>
                <option value="" disabled selected>Select Class</option>
                <?php
                $classes = $connection->query("SELECT DISTINCT classes FROM classes");
                while ($c = $classes->fetch_assoc()) {
                    echo "<option value='{$c['classes']}'>{$c['classes']}</option>";
                }
                ?>
            </select>

            <select name="term" class="form-control mb-2" required>
                <option value="" disabled selected>Select Term</option>
                <option>First Term</option>
                <option>Second Term</option>
                <option>Third Term</option>
            </select>

            <select name="session" class="form-control mb-2" required>
                <option value="" disabled selected>Select Session</option>
                <?php
                $sessions = $connection->query("SELECT sessions FROM sessions ORDER BY id DESC");
                while ($r = $sessions->fetch_assoc()) {
                    echo "<option value='{$r['sessions']}'>{$r['sessions']}</option>";
                }
                ?>
            </select>

            <input type="file" name="curriculum_file" class="form-control" required>
        </div>

        <div class="modal-footer">
          <button type="submit" name="upload_curriculum" class="btn btn-success">Upload</button>
        </div>
      </div>
    </form>
  </div>
</div>
