<?php
session_start();
require_once(__DIR__ . '/../config.php');

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'lecturer') {
    header("Location: dashboard.php");
    exit();
}

include(__DIR__ . '/../header/header.php');

$user_id = $_SESSION['user_id'];
$error = '';
$success = '';

$preselected_course_id = isset($_GET['course_id']) ? $_GET['course_id'] : '';
$preselected_module_id = isset($_GET['module_id']) ? $_GET['module_id'] : '';
$preselected_unit_id = isset($_GET['unit_id']) ? $_GET['unit_id'] : '';

$stmt = $pdo->prepare("SELECT id, course_name FROM courses WHERE lecturer_id = ?");
$stmt->execute([$user_id]);
$courses = $stmt->fetchAll();

$preselected_modules = [];
if ($preselected_course_id) {
    $stmt = $pdo->prepare("SELECT id, module_name FROM modules WHERE course_id = ?");
    $stmt->execute([$preselected_course_id]);
    $preselected_modules = $stmt->fetchAll();
}

$preselected_units = [];
if ($preselected_module_id) {
    $stmt = $pdo->prepare("SELECT id, unit_name FROM units WHERE module_id = ?");
    $stmt->execute([$preselected_module_id]);
    $preselected_units = $stmt->fetchAll();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $course_id = $_POST['course_id'] ?? null;
    $module_id = $_POST['module_id'] ?? null;
    $unit_id   = $_POST['unit_id'] ?? null;

    if (!$course_id || !$module_id || !$unit_id) {
        $error = "Please select course, module and unit.";
    } elseif (!isset($_FILES['note_file'])) {
        $error = "Please select a file.";
    } else {

        $file = $_FILES['note_file'];

        $file_name  = $file['name'];
        $file_tmp   = $file['tmp_name'];
        $file_size  = $file['size'];
        $file_error = $file['error'];

        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        $allowed = ['pdf','doc','docx','ppt','pptx','txt'];

        if (!in_array($file_ext, $allowed)) {
            $error = "Invalid file type.";
        } elseif ($file_error !== 0) {
            $error = "Upload error.";
        } elseif ($file_size > 5000000) {
            $error = "File too large (Max 5MB).";
        } else {

            $new_name = uniqid('note_', true) . "." . $file_ext;
            $destination = __DIR__ . '/../uploads/' . $new_name;

            if (move_uploaded_file($file_tmp, $destination)) {

                $stmt = $pdo->prepare("
                    INSERT INTO notes 
                    (course_id, module_id, unit_id, lecturer_id, file_name, file_path)
                    VALUES (?, ?, ?, ?, ?, ?)
                ");

                if ($stmt->execute([
                    $course_id,
                    $module_id,
                    $unit_id,
                    $user_id,
                    $file_name,
                    $new_name
                ])) {
                    $success = "File uploaded successfully!";
                } else {
                    $error = "Database error.";
                }

            } else {
                $error = "Failed to save file.";
            }
        }
    }
}
?>

<div class="container py-5">
<div class="row justify-content-center">
<div class="col-md-6">

<div class="card shadow-sm border-0">
<div class="card-body p-5">

<h2 class="fw-bold text-center mb-4">Upload Lecture Notes</h2>

<?php if($error): ?>
<div class="alert alert-danger"><?= $error ?></div>
<?php endif; ?>

<?php if($success): ?>
<div class="alert alert-success"><?= $success ?></div>
<div class="d-grid gap-2 mt-3">
    <a href="upload_notes.php?course_id=<?= $course_id; ?>&module_id=<?= $module_id; ?>&unit_id=<?= $unit_id; ?>" class="btn btn-secondary py-2 fw-bold">Upload Another Note</a>
    <a href="dashboard.php" class="btn btn-outline-primary py-2 fw-bold">Back to Dashboard</a>
</div>
<?php endif; ?>

<?php if(!$success): ?>
<form method="POST" enctype="multipart/form-data">

<!-- COURSE -->
<div class="mb-3">
<label>Select Course</label>
<select id="course" name="course_id" class="form-select" required>
<option value="">-- Select Course --</option>
<?php foreach($courses as $c): ?>
<option value="<?= $c['id'] ?>" <?= ($c['id'] == $preselected_course_id) ? 'selected' : ''; ?>>
<?= htmlspecialchars($c['course_name']) ?>
</option>
<?php endforeach; ?>
</select>
</div>
<!-- MODULE -->
<div class="mb-3">
<label>Select Module</label>
<select id="module" name="module_id" class="form-select" required>
<option value="">-- Select Module --</option>
<?php foreach($preselected_modules as $m): ?>
<option value="<?= $m['id'] ?>" <?= ($m['id'] == $preselected_module_id) ? 'selected' : ''; ?>>
<?= htmlspecialchars($m['module_name']) ?>
</option>
<?php endforeach; ?>
</select>
</div>
<!-- UNIT -->
<div class="mb-3">
<label>Select Unit</label>
<select id="unit" name="unit_id" class="form-select" required>
<option value="">-- Select Unit --</option>
<?php foreach($preselected_units as $u): ?>
<option value="<?= $u['id'] ?>" <?= ($u['id'] == $preselected_unit_id) ? 'selected' : ''; ?>>
<?= htmlspecialchars($u['unit_name']) ?>
</option>
<?php endforeach; ?>
</select>
</div>
<!-- FILE -->
<div class="mb-3">
<label>Upload File</label>
<input type="file" name="note_file" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary w-100">Upload Note</button>
</form>
<div class="text-center mt-3">
<a href="dashboard.php">Back to Dashboard</a>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
</div>
<script>
// LOAD MODULES
document.getElementById("course").addEventListener("change", function(){

    let course_id = this.value;

    fetch("get_modules.php?course_id=" + course_id)
    .then(res => res.json())
    .then(data => {

        let module = document.getElementById("module");
        module.innerHTML = '<option value="">-- Select Module --</option>';

        data.forEach(m => {
            module.innerHTML += `<option value="${m.id}">${m.module_name}</option>`;
        });

        document.getElementById("unit").innerHTML = '<option value="">-- Select Unit --</option>';
    });
});

// LOAD UNITS
document.getElementById("module").addEventListener("change", function(){

    let module_id = this.value;

    fetch("get_units.php?module_id=" + module_id)
    .then(res => res.json())
    .then(data => {

        let unit = document.getElementById("unit");
        unit.innerHTML = '<option value="">-- Select Unit --</option>';

        data.forEach(u => {
            unit.innerHTML += `<option value="${u.id}">${u.unit_name}</option>`;
        });
    });
});
</script>
<?php include(__DIR__ . '/../footer/footer.php'); ?>