<?php
include "include/db.php"; // Include database connection
include "include/header.php";

// Initialize variables
$errors = [];
$success = '';
$lesson_data = [];

// Check if ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $errors[] = "Invalid lesson ID.";
} else {
    $lesson_id = $_GET['id'];
    // Fetch lesson data
    $stmt = $conn->prepare("SELECT name, course_id FROM lessons WHERE id = ?");
    $stmt->bind_param("i", $lesson_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($lesson_data = $result->fetch_assoc()) {
        // Lesson data found
    } else {
        $errors[] = "Lesson not found.";
    }
    $stmt->close();
}

// Handle Delete Action
if (isset($_GET['delete_id']) && is_numeric($_GET['delete_id'])) {
    $delete_id = $_GET['delete_id'];
    $stmt = $conn->prepare("DELETE FROM lessons WHERE id = ?");
    $stmt->bind_param("i", $delete_id);
    if ($stmt->execute()) {
        $success = "Lesson deleted successfully!";
    } else {
        $errors[] = "Failed to delete lesson from database.";
    }
    $stmt->close();
}

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($errors)) {
    $lesson_name = trim($_POST['lesson_name'] ?? '');
    $course_id = trim($_POST['course_id'] ?? '');
    
    // Basic validation
    if (empty($lesson_name)) $errors[] = "Lesson Name is required.";
    if (empty($course_id) || !is_numeric($course_id)) $errors[] = "Please select a valid course.";
    
    // If no errors, update database
    if (empty($errors)) {
        $stmt = $conn->prepare("UPDATE lessons SET name = ?, course_id = ? WHERE id = ?");
        $stmt->bind_param("sii", $lesson_name, $course_id, $lesson_id);
        if ($stmt->execute()) {
            $success = "Lesson updated successfully!";
            // Refresh lesson data
            $stmt = $conn->prepare("SELECT name, course_id FROM lessons WHERE id = ?");
            $stmt->bind_param("i", $lesson_id);
            $stmt->execute();
            $result = $stmt->get_result();
            $lesson_data = $result->fetch_assoc();
            $_POST = []; // Reset form fields
        } else {
            $errors[] = "Failed to update lesson in database.";
        }
        $stmt->close();
    }
}

// Fetch all courses for the dropdown
$course_result = $conn->query("SELECT id, name FROM courses ORDER BY name");
$courses = $course_result->fetch_all(MYSQLI_ASSOC);

// Fetch all lessons for the table
$lesson_result = $conn->query("SELECT l.id, l.name AS lesson_name, c.name AS course_name FROM lessons l JOIN courses c ON l.course_id = c.id ORDER BY l.created_at DESC");
$lessons = $lesson_result->fetch_all(MYSQLI_ASSOC);
?>

<!-- Content -->
<div id="content" class="content ml-64 p-6 min-h-screen">
    <style>
        /* Tailwind CSS CDN (embedded for top-class design) */
        @import url('https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css');

        /* Custom styles for enhanced design */
        body { overflow-x: hidden; font-family: 'Inter', sans-serif; }
        .content { transition: margin-left 0.3s ease; }
        .form-section, .table-section { transition: transform 0.2s ease, box-shadow 0.2s ease; }
        .form-section:hover, .table-section:hover { transform: translateY(-5px); box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15); }
        .top-nav { background: linear-gradient(90deg, #1F2937, #374151); }
        input, select { transition: all 0.2s ease; }
        input:focus, select:focus { ring: 2px solid #F59E0B; }
        .error { color: #DC2626; }
        .success { color: #10B981; }
        .table-section { overflow-x: auto; }
        .table-section th { background: linear-gradient(90deg, #1F2937, #374151); }
        @media (max-width: 768px) {
            .content { margin-left: 0; }
            .content.open { margin-left: 0; }
            .search { display: none; }
            .form-table-container { flex-direction: column; }
        }
        @media (min-width: 769px) {
            .content { margin-left: 250px; }
        }
    </style>

    <!-- Top Nav -->
    <nav class="top-nav sticky top-0 text-white p-4 flex justify-between items-center shadow-lg z-40">
        <div class="logo text-2xl font-bold">CourseLMS Admin</div>
        <div class="search flex-1 max-w-xs mx-4">
            <input type="text" placeholder="Search courses or users..." class="w-full p-2 border border-gray-300 rounded-md bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-yellow-500">
        </div>
        <div class="right-nav flex items-center gap-4">
            <i class="fas fa-bell text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer" title="Notifications"></i>
            <i class="fas fa-envelope text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer" title="Messages"></i>
            <div class="profile flex items-center gap-2">
                <img src="https://via.placeholder.com/40" alt="Profile" class="w-10 h-10 rounded-full">
                <span class="text-white">Admin</span>
            </div>
            <i id="toggle" class="fas fa-bars text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer" title="Toggle Menu"></i>
        </div>
    </nav>

    <!-- Form and Table Container -->
    <div class="form-table-container flex flex-col lg:flex-row gap-6 my-6">
        <!-- Edit Lesson Form -->
        <div class="form-section bg-white p-6 rounded-lg shadow-md w-full lg:w-1/2">
            <h2 class="text-xl font-semibold text-gray-900 mb-4">Edit Lesson</h2>
            
            <!-- Success/Error Messages -->
            <?php if ($success): ?>
                <p class="success text-center font-semibold mb-4"><?php echo htmlspecialchars($success); ?></p>
            <?php endif; ?>
            <?php if (!empty($errors)): ?>
                <ul class="error mb-4">
                    <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>

            <!-- Form -->
            <?php if (!empty($lesson_data)): ?>
                <form method="POST" class="space-y-4">
                    <div>
                        <label for="lesson_name" class="block text-sm font-medium text-gray-700">Lesson Name</label>
                        <input type="text" id="lesson_name" name="lesson_name" value="<?php echo htmlspecialchars($lesson_data['name']); ?>" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                    </div>
                    <div>
                        <label for="course_id" class="block text-sm font-medium text-gray-700">Select Course</label>
                        <select id="course_id" name="course_id" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                            <option value="">Select a course</option>
                            <?php foreach ($courses as $course): ?>
                                <option value="<?php echo htmlspecialchars($course['id']); ?>" <?php echo $lesson_data['course_id'] == $course['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($course['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <button type="submit" class="w-full bg-yellow-500 text-white p-2 rounded-md hover:bg-yellow-600 transition-colors">Update Lesson</button>
                    </div>
                </form>
            <?php else: ?>
                <p class="text-center text-gray-500">No lesson selected for editing.</p>
            <?php endif; ?>
        </div>

        <!-- Lessons Table -->
        <div class="table-section bg-white p-6 rounded-lg shadow-md w-full lg:w-1/2">
            <h2 class="text-xl font-semibold text-gray-900 mb-4">All Lessons</h2>
            <div class="overflow-x-auto">
                <table class="w-full border-collapse">
                    <thead>
                        <tr class="text-white">
                            <th class="p-3 text-left font-bold">ID</th>
                            <th class="p-3 text-left font-bold">Lesson Name</th>
                            <th class="p-3 text-left font-bold">Course</th>
                            <th class="p-3 text-left font-bold">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($lessons)): ?>
                            <tr>
                                <td colspan="4" class="p-3 text-center text-gray-500">No lessons found.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($lessons as $lesson): ?>
                                <tr>
                                    <td class="p-3 border-b border-gray-200"><?php echo htmlspecialchars($lesson['id']); ?></td>
                                    <td class="p-3 border-b border-gray-200"><?php echo htmlspecialchars($lesson['lesson_name']); ?></td>
                                    <td class="p-3 border-b border-gray-200"><?php echo htmlspecialchars($lesson['course_name']); ?></td>
                                    <td class="p-3 border-b border-gray-200">
                                        <a href="edit_lesson.php?id=<?php echo htmlspecialchars($lesson['id']); ?>" class="text-blue-900 hover:text-yellow-500 mr-2">Edit</a>
                                        <a href="edit_lesson.php?delete_id=<?php echo htmlspecialchars($lesson['id']); ?>" class="text-red-600 hover:text-red-700" onclick="return confirm('Are you sure you want to delete this lesson? This will also delete associated videos.')">Delete</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php
include "include/footer.php";
$conn->close(); // Close database connection
?>