<?php
if (isset($_POST['id'])) {
    $id = (int)$_POST['id'];
    $stmt = $connection->prepare("SELECT file_path FROM lesson_plans 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/lesson_plans/');
        $full_path = realpath($base_dir . '/' . basename($file));

        // Validate 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'] = "Lesson plan not found.";
        $_SESSION['type'] = "danger";
    }

    // Redirect to lesson plans page on error
    header("Location: upload_lesson_plans");
    exit;
}
// Handle file upload
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_FILES['file']['name'] ?? '';
    $tmp_name = $_FILES['file']['tmp_name'] ?? '';
    $upload_dir = 'uploads/lesson_plans/';

    $subject = $_POST['result_upload_subject'] ?? '';
    $class = $_POST['show_publish_result_class'] ?? '';
    $term = $_POST['show_publish_result_term'] ?? '';
    $session = $_POST['show_publish_result_session'] ?? '';

    if (!empty($name)) {
        $file_ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
        $allowed_exts = ['pdf'];

        if (in_array($file_ext, $allowed_exts)) {
            $new_filename = time() . '_' . $name;
            $file_path = $upload_dir . $new_filename;

            if (move_uploaded_file($tmp_name, $file_path)) {
                // Check for duplicates
                $check = $connection->prepare("SELECT id FROM lesson_plans WHERE file_name = ? AND subject = ? AND class = ? AND term = ? AND session = ?");
                $check->bind_param("sssss", $name, $subject, $class, $term, $session);
                $check->execute();
                $check->store_result();

                if ($check->num_rows > 0) {
                    $_SESSION['msg'] = "⚠️ A lesson plan with the same file name already exists.";
                    $_SESSION['type'] = "warning";
                    unlink($file_path); // Remove the newly uploaded file
                } else {
                    $query = "INSERT INTO lesson_plans (file_name, file_path, subject, class, term, session, upload_date) 
                              VALUES (?, ?, ?, ?, ?, ?, NOW())";
                    $stmt = $connection->prepare($query);
                    $stmt->bind_param("ssssss", $name, $file_path, $subject, $class, $term, $session);

                    if ($stmt->execute()) {
                        $_SESSION['msg'] = "✅ Lesson plan uploaded successfully!";
                        $_SESSION['type'] = "success";
                    } else {
                        $_SESSION['msg'] = "❌ Database error: " . $stmt->error;
                        $_SESSION['type'] = "danger";
                    }
                    $stmt->close();
                }
                $check->close();
            } else {
                $_SESSION['msg'] = "❌ File upload failed! Try again.";
                $_SESSION['type'] = "danger";
            }
        } else {
            $_SESSION['msg'] = "❌ Only PDF files are allowed.";
            $_SESSION['type'] = "danger";
        }
    }
}

// Handle delete request
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);

    $stmt = $connection->prepare("SELECT file_path FROM lesson_plans WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->bind_result($file_path);
    $stmt->fetch();
    $stmt->close();

    if (!empty($file_path)) {
        if (file_exists($file_path)) {
            unlink($file_path);
        }

        $stmt = $connection->prepare("DELETE FROM lesson_plans WHERE id = ?");
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            $_SESSION['msg'] = "✅ Lesson plan deleted successfully!";
            $_SESSION['type'] = "success";
        } else {
            $_SESSION['msg'] = "❌ Error deleting lesson plan!";
            $_SESSION['type'] = "danger";
        }
        $stmt->close();
    } else {
        $_SESSION['msg'] = "❌ File not found in the database.";
        $_SESSION['type'] = "warning";
    }
}
?>


<div class='page-title'>
  <div>
    <h1><i class='fa fa-laptop'></i> Lesson Plan</h1>
    <p>Class Lesson Plans</p>
  </div>  
</div>

<div class='card'>   
    <div class='panel panel-primary'>
        <div class='panel-heading'>
            <h4 class='text-center'>Upload Lesson Plans by Class</h4>
        </div>
        <div class='panel-body'>
            <form method='POST' enctype='multipart/form-data'>
                <div class='row'>
                    <!-- Select Subject -->
                    <div class='col-md-3'>
                        <div class='input-group'>
                            <span class='input-group-addon'>Subject:</span>
                            <select class='form-control' name='result_upload_subject' required>
                                <option selected disabled>Select Subject</option>
                                <?php
                                    $query = "SELECT * FROM `school_subjects`";
                                    $run_query = mysqli_query($connection, $query);
                                    while ($result = mysqli_fetch_assoc($run_query)) {
                                        echo "<option>{$result['subjects']}</option>";
                                    }
                                ?>
                            </select>
                        </div>
                    </div>

                    <!-- Select Class -->
                    <div class='col-md-3'>
                        <div class='input-group'>
                            <span class='input-group-addon'>Class:</span>
                            <select class='form-control' name='show_publish_result_class' required>
                                <option selected disabled>Select Class</option>
                                <?php
                                    $query = "SELECT classes FROM `classes`";
                                    $run_query = mysqli_query($connection, $query);
                                    while ($result = mysqli_fetch_assoc($run_query)) {
                                        echo "<option>{$result['classes']}</option>";
                                    }
                                ?>
                            </select>
                        </div>
                    </div>

                    <!-- Select Term -->
                    <div class='col-md-3'>
                        <div class='input-group'>
                            <span class='input-group-addon'>Term:</span>
                            <select class='form-control' name='show_publish_result_term' required>
                                <option selected disabled>Select Term</option>
                                <?php
                                    $term_array = ["First Term", "Second Term", "Third Term"];
                                    foreach ($term_array as $term_option) {
                                        echo "<option>{$term_option}</option>";
                                    }
                                ?>
                            </select>
                        </div>
                    </div>

                    <!-- Select Session -->
                    <div class='col-md-3'>
                        <div class='input-group'>
                            <span class='input-group-addon'>Session:</span>
                            <select class='form-control' name='show_publish_result_session' required>
                                <option selected disabled>Select Session</option>
                                <?php
                                    $query = "SELECT current_session FROM `current_season`";
                                    $run_query = mysqli_query($connection, $query);
                                    while ($result = mysqli_fetch_assoc($run_query)) {
                                        echo "<option>{$result['current_session']}</option>";
                                    }
                                ?>
                            </select>
                        </div>
                    </div>                  
                </div>
                <br />

                <!-- Upload File -->
                <div class='row'>
                    <div class='col-md-6'>
                        <input type='file' name='file' class='form-control' required />
                    </div>
                    <div class='col-md-2'>
                        <button type='submit' class='btn btn-primary'>Upload</button>
                    </div>
                </div>
            </form>           
        </div>
    </div>
</div>

<!-- Display Uploaded Lesson Plans -->
<div class='card'>
    <div class='panel panel-primary'>
        <div class='panel-heading'>
            <h4 class='text-center'>Uploaded Lesson Plans</h4>
        </div>
        <div class='panel-body'>
            <table class='table table-bordered' id='myTable'>
                <thead>
                    <tr>
                        <th>File Name</th>
                        <th>Subject</th>
                        <th>Class</th>
                        <th>Term</th>
                        <th>Session</th>
                        <th>Upload Date</th>
                        <th>Download</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
$query = "SELECT * FROM lesson_plans ORDER BY upload_date DESC";
$result = mysqli_query($connection, $query);

while ($row = mysqli_fetch_assoc($result)) {
    $file_name = $row['file_name'];
    $word_count = str_word_count($file_name);

    if ($word_count > 4) {
        $words = explode(' ', $file_name);
        $short_name = implode(' ', array_slice($words, 0, 4)) . '...';
        $display_name = "<span title='" . htmlspecialchars($file_name, ENT_QUOTES) . "'>$short_name</span>";
    } else {
        $display_name = htmlspecialchars($file_name);
    }

    echo "<tr>
    <td>$display_name</td>
    <td>{$row['subject']}</td>
    <td>{$row['class']}</td>
    <td>{$row['term']}</td>
    <td>{$row['session']}</td>
    <td>{$row['upload_date']}</td>
    <td>";

if (!empty($row['file_path'])) {
    echo "<form method='POST' action=''>
            <input type='hidden' name='id' value='" . htmlspecialchars($row['id']) . "'>
            <button type='submit' class='btn btn-success btn-sm'>Download</button>
          </form>";
} else {
    echo "N/A";
}

echo "</td>
    <td>
        <a href='?delete={$row['id']}' onclick=\"return confirm('Are you sure you want to delete this file?')\" class='btn btn-danger btn-sm'>Delete</a>
    </td>
</tr>";

}
?>

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

