<?php
require_once('../source/session.php');
require_once('../source/error.php');
//require_once('../source/dbconfig3.php');
require_once('../source/function.php');
require_once('../source/restrict_admin.php');

// Function to fetch subjects from tbl_subject table
function getSubjects()
{
    global $db;
    $stmt = $db->prepare("SELECT subject FROM tbl_subject ORDER BY subject ASC");
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result) {
        $subjects = array();
        while ($row = $result->fetch_assoc()) {
            $subjects[] = $row['subject'];
        }
        return $subjects;
    } else {
        return array();
    }
}

// Function to fetch classes from tbl_class table
function getClasses()
{
    global $db;
    $stmt = $db->prepare("SELECT class FROM tbl_class ORDER BY class ASC");
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result) {
        $classes = array();
        while ($row = $result->fetch_assoc()) {
            $classes[] = $row['class'];
        }
        return $classes;
    } else {
        return array();
    }
}

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

    if ($result) {
        $creators = array();
        while ($row = $result->fetch_assoc()) {
            $creators[] = $row['fullname'];
        }
        return $creators;
    } else {
        return array();
    }
}

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

    // Process the file upload - updated path to match the list page
    $uploadDir = "../teacher/lesson_plan/";
    
    // Create directory if it doesn't exist
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
    
    // Generate unique filename to prevent overwrites
    $fileExtension = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));
    $fileName = time() . '_' . preg_replace('/[^a-zA-Z0-9]/', '_', $title) . '.' . $fileExtension;
    $targetFilePath = $uploadDir . $fileName;

    // Validate file type
    $allowedExtensions = array("pdf", "doc", "docx");

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

    // Validate file size (max 10MB)
    if ($file["size"] > 10485760) {
        $_SESSION['error_message'] = "File size too large. Maximum size is 10MB.";
        return false;
    }

    // Move uploaded file
    if (move_uploaded_file($file["tmp_name"], $targetFilePath)) {
        // Store only the filename in database, not the full path
        $filePath = $fileName;
        
        // 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, $filePath);

        if ($stmt->execute()) {
            $_SESSION['success_message'] = "Lesson plan uploaded successfully.";
            return true;
        } else {
            $_SESSION['error_message'] = "Error uploading lesson plan. Please try again.";
            // Delete the file if database insert fails
            unlink($targetFilePath);
            return false;
        }
    } else {
        $_SESSION['error_message'] = "Error moving uploaded file. Please try again.";
        return false;
    }
}

// Form submission handling
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $class = $_POST['class'];
    $subject = $_POST['subject'];
    $lesson_date = $_POST['lesson_date'];
    $created_by = $_POST['lesson_creator'];
    $file = $_FILES['lesson_file'];

    if (uploadLessonPlan($title, $description, $created_by, $class, $subject, $lesson_date, $file)) {
        header("Location: lesson_plan_list.php");
        exit();
    } else {
        // Stay on the page to show error messages
    }
}

// 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 - School Management System</title>
    <link rel="stylesheet" href="../css/styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Arial', sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 20px auto;
            background-color: #fff;
            padding: 30px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
        }

        h2 {
            color: #333;
            font-size: 2em;
            margin-bottom: 30px;
            text-align: center;
            border-bottom: 2px solid #007bff;
            padding-bottom: 15px;
        }

        .links {
            margin-bottom: 30px;
            text-align: center;
        }

        .links a {
            display: inline-block;
            margin: 0 10px;
            text-decoration: none;
            color: #007bff;
            padding: 10px 20px;
            background: #f8f9fa;
            border-radius: 5px;
            transition: all 0.3s ease;
        }

        .links a:hover {
            background: #007bff;
            color: white;
            text-decoration: none;
        }

        .links i {
            margin-right: 8px;
        }

        .success-message {
            background-color: #d4edda;
            color: #155724;
            padding: 15px;
            margin-bottom: 20px;
            border: 1px solid #c3e6cb;
            border-radius: 4px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .success-message i {
            color: #28a745;
            font-size: 1.2em;
        }

        .error-message {
            background-color: #f8d7da;
            color: #721c24;
            padding: 15px;
            margin-bottom: 20px;
            border: 1px solid #f5c6cb;
            border-radius: 4px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .error-message i {
            color: #dc3545;
            font-size: 1.2em;
        }

        form {
            background: #f9f9f9;
            padding: 25px;
            border-radius: 8px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: bold;
            font-size: 0.95em;
        }

        label i {
            color: #007bff;
            margin-right: 8px;
            width: 20px;
        }

        input[type="text"],
        input[type="date"],
        select,
        textarea {
            width: 100%;
            padding: 12px;
            margin-bottom: 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 1em;
            transition: border-color 0.3s ease;
        }

        input[type="text"]:focus,
        input[type="date"]:focus,
        select:focus,
        textarea:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 5px rgba(0, 123, 255, 0.3);
        }

        input[type="file"] {
            width: 100%;
            padding: 10px;
            margin-bottom: 20px;
            border: 1px dashed #007bff;
            border-radius: 4px;
            background: #f8f9fa;
            cursor: pointer;
        }

        input[type="file"]:hover {
            background: #e9ecef;
        }

        textarea {
            resize: vertical;
            min-height: 100px;
        }

        button[type="submit"] {
            background-color: #007bff;
            color: white;
            padding: 14px 30px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 1.1em;
            font-weight: bold;
            width: 100%;
            transition: background-color 0.3s ease;
        }

        button[type="submit"]:hover {
            background-color: #0056b3;
        }

        button[type="submit"] i {
            margin-right: 10px;
        }

        .file-info {
            font-size: 0.85em;
            color: #666;
            margin-top: -15px;
            margin-bottom: 20px;
        }

        .required-field::after {
            content: " *";
            color: red;
        }

        @media (max-width: 768px) {
            .container {
                padding: 20px;
                margin: 10px;
            }
            
            h2 {
                font-size: 1.6em;
            }
            
            .links a {
                display: block;
                margin: 10px 0;
            }
            
            form {
                padding: 15px;
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <h2><i class="fas fa-upload" style="margin-right: 10px; color: #007bff;"></i>Upload Lesson Plan</h2>

        <!-- Navigation Links -->
        <div class="links">
            <a href="lesson_plan_list.php"><i class="fas fa-list"></i> View Lesson Plans</a>
            <a href="../admin_dashboard.php"><i class="fas fa-arrow-left"></i> Back to Dashboard</a>
            <a href="https://smt.lahs.com.ng"><i class="fas fa-school"></i> Go to School Management</a>
        </div>

        <!-- Display Messages -->
        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="success-message">
                <i class="fas fa-check-circle"></i>
                <?php 
                echo $_SESSION['success_message'];
                unset($_SESSION['success_message']);
                ?>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="error-message">
                <i class="fas fa-exclamation-circle"></i>
                <?php 
                echo $_SESSION['error_message'];
                unset($_SESSION['error_message']);
                ?>
            </div>
        <?php endif; ?>

        <form action="" method="post" enctype="multipart/form-data">
            <label for="lesson_creator">
                <i class="fas fa-user"></i>Lesson Plan Creator <span class="required-field">*</span>
            </label>
            <select name="lesson_creator" required>
                <option value="">Select Creator</option>
                <?php foreach ($lessonPlanCreators as $creator) : ?>
                    <option value="<?php echo htmlspecialchars($creator); ?>"><?php echo htmlspecialchars($creator); ?></option>
                <?php endforeach; ?>
            </select>

            <label for="title">
                <i class="fas fa-heading"></i>Title <span class="required-field">*</span>
            </label>
            <input type="text" name="title" placeholder="Enter lesson plan title" required>

            <label for="description">
                <i class="fas fa-align-left"></i>Description <span class="required-field">*</span>
            </label>
            <textarea name="description" placeholder="Enter detailed description of the lesson plan" required></textarea>

            <label for="class">
                <i class="fas fa-users"></i>Class <span class="required-field">*</span>
            </label>
            <select name="class" required>
                <option value="">Select Class</option>
                <?php foreach ($classes as $class) : ?>
                    <option value="<?php echo htmlspecialchars($class); ?>"><?php echo htmlspecialchars($class); ?></option>
                <?php endforeach; ?>
            </select>

            <label for="subject">
                <i class="fas fa-book"></i>Subject <span class="required-field">*</span>
            </label>
            <select name="subject" required>
                <option value="">Select Subject</option>
                <?php foreach ($subjects as $subject) : ?>
                    <option value="<?php echo htmlspecialchars($subject); ?>"><?php echo htmlspecialchars($subject); ?></option>
                <?php endforeach; ?>
            </select>

            <label for="lesson_date">
                <i class="fas fa-calendar"></i>Lesson Date <span class="required-field">*</span>
            </label>
            <input type="date" name="lesson_date" required value="<?php echo date('Y-m-d'); ?>">

            <label for="lesson_file">
                <i class="fas fa-file"></i>Upload Lesson Plan <span class="required-field">*</span>
            </label>
            <input type="file" name="lesson_file" accept=".pdf,.doc,.docx" required>
            <div class="file-info">
                <i class="fas fa-info-circle"></i> Accepted formats: PDF, DOC, DOCX (Max size: 10MB)
            </div>

            <button type="submit">
                <i class="fas fa-cloud-upload-alt"></i> Upload Lesson Plan
            </button>
        </form>
    </div>
</body>

</html>