<?php
require_once('source/session.php');
require_once('source/error.php');
require_once('source/dbconfig3.php'); // Include your new database connect
require_once('source/function.php');
require_once('source/restrict_admin.php');

// Function to fetch subjects from tbl_subject table
function getSubjects()
{
    global $db; // Use the existing database connection variable
    $stmt = $db->prepare("SELECT subject FROM tbl_subject");
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result) {
        $subjects = array();
        while ($row = $result->fetch_assoc()) {
            $subjects[] = $row['subject'];
        }
        return $subjects;
    } else {
        return array(); // Return an empty array or handle the error accordingly
    }
}

// Function to fetch classes from tbl_class table
function getClasses()
{
    global $db; // Use the existing database connection variable
    $stmt = $db->prepare("SELECT class FROM tbl_class");
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result) {
        $classes = array();
        while ($row = $result->fetch_assoc()) {
            $classes[] = $row['class'];
        }
        return $classes;
    } else {
        return array(); // Return an empty array or handle the error accordingly
    }
}

// Function to fetch lesson plan creators (admins only)
function getLessonPlanCreators()
{
    global $db;
    $stmt = $db->prepare("SELECT fullname FROM tbl_admin");
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result) {
        $creators = array();
        while ($row = $result->fetch_assoc()) {
            $creators[] = $row['fullname'];
        }
        return $creators;
    } else {
        return array(); // Return an empty array or handle the error accordingly
    }
}


function uploadLessonPlan($title, $description, $created_by, $class, $subject, $lesson_date, $file)
{
    global $db;

    // Process the file upload
    $uploadDir = "uploads/";
    $fileName = basename($file["name"]);
    $targetFilePath = $uploadDir . $fileName;

    // Validate file type
    $allowedExtensions = array("pdf", "doc", "docx");
    $fileExtension = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));

    if (!in_array($fileExtension, $allowedExtensions)) {
        $_SESSION['error_msg'] = "Invalid file type. Only PDF, DOC, and DOCX files are allowed.";
        return false;
    }

    // Move uploaded file
    if (move_uploaded_file($file["tmp_name"], $targetFilePath)) {
        // Insert lesson plan details into the database
        $sql = "INSERT INTO tbl_lessonplan (title, description, created_by, class, subject, lesson_date, file_path) 
                VALUES (?, ?, ?, ?, ?, ?, ?)";
        $stmt = $db->prepare($sql);

        if ($stmt === false) {
            die('Error in SQL query: ' . $db->error);
        }

        $stmt->bind_param('sssssss', $title, $description, $created_by, $class, $subject, $lesson_date, $targetFilePath);

        if ($stmt->execute()) {
            $_SESSION['success_msg'] = "Lesson plan uploaded successfully.";
            return true;
        } else {
            $_SESSION['error_msg'] = "Error uploading lesson plan. Please try again. SQL Error: " . $stmt->error;
            return false;
        }
    } else {
        $_SESSION['error_msg'] = "Error moving uploaded file. Please try again.";
        return false;
    }
}



// Form submission handling
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $title = $_POST['title'];
    $description = $_POST['description'];
    $class = $_POST['class'];
    $subject = $_POST['subject'];
    $lesson_date = $_POST['lesson_date'];
    $created_by = $_POST['lesson_creator']; // Use the selected name instead of ID
    $file = $_FILES['lesson_file'];

    if (uploadLessonPlan($title, $description, $created_by, $class, $subject, $lesson_date, $file)) {
        header("Location: lesson_plan_list.php");
        exit();
    }
}

// Fetch dynamic data for form elements
$subjects = getSubjects();
$classes = getClasses();
$lessonPlanCreators = getLessonPlanCreators();
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Lesson Plan</title>
    <link rel="stylesheet" href="styles.css">
</head>

<body>
    <div class="container">
        <h2>Upload Lesson Plan</h2>

        <?php include('source/error_success_messages.php'); ?>

<form action="" method="post" enctype="multipart/form-data">
    <label for="lesson_creator">Lesson Plan Creator:</label>
    <select name="lesson_creator" required>
        <?php foreach ($lessonPlanCreators as $creator) : ?>
            <option value="<?php echo $creator; ?>"><?php echo $creator; ?></option>
        <?php endforeach; ?>
    </select>

    <label for="title">Title:</label>
    <input type="text" name="title" required>

    <label for="description">Description:</label>
    <textarea name="description" rows="4" required></textarea>

    <label for="class">Class:</label>
    <select name="class" required>
        <?php foreach ($classes as $class) : ?>
            <option value="<?php echo $class; ?>"><?php echo $class; ?></option>
        <?php endforeach; ?>
    </select>

    <label for="subject">Subject:</label>
    <select name="subject" required>
        <?php foreach ($subjects as $subject) : ?>
            <option value="<?php echo $subject; ?>"><?php echo $subject; ?></option>
        <?php endforeach; ?>
    </select>

    <label for="lesson_date">Lesson Date:</label>
    <input type="date" name="lesson_date" required>

    <label for="lesson_file">Upload Lesson Plan (PDF, DOC, DOCX):</label>
    <input type="file" name="lesson_file" accept=".pdf, .doc, .docx" required>

    <button type="submit">Upload</button>
</form>
    </div>
</body>

</html>
