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

// Set PHP configuration for larger uploads
ini_set('upload_max_filesize', '2G');
ini_set('post_max_size', '2G');
ini_set('max_execution_time', '300');

// Initialize variables for form submission
$errors = [];
$success = '';

// Handle Delete Action
if (isset($_GET['delete_id']) && is_numeric($_GET['delete_id'])) {
    $delete_id = $_GET['delete_id'];
    // Fetch file paths to delete from server
    $stmt = $conn->prepare("SELECT image, video_path FROM videos WHERE id = ?");
    $stmt->bind_param("i", $delete_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($row = $result->fetch_assoc()) {
        // Delete files from server
        if (file_exists($row['image'])) unlink($row['image']);
        if (file_exists($row['video_path'])) unlink($row['video_path']);
        // Delete record from database
        $delete_stmt = $conn->prepare("DELETE FROM videos WHERE id = ?");
        $delete_stmt->bind_param("i", $delete_id);
        if ($delete_stmt->execute()) {
            $success = "Video deleted successfully!";
        } else {
            $errors[] = "Failed to delete video from database.";
        }
        $delete_stmt->close();
    } else {
        $errors[] = "Video not found.";
    }
    $stmt->close();
}

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $video_name = trim($_POST['video_name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $course_id = trim($_POST['course_id'] ?? '');
    $lesson_id = trim($_POST['lesson_id'] ?? '');
    
    // Basic validation
    if (empty($video_name)) $errors[] = "Video Name is required.";
    if (empty($description)) $errors[] = "Description is required.";
    if (empty($course_id) || !is_numeric($course_id)) $errors[] = "Please select a valid course.";
    if (empty($lesson_id) || !is_numeric($lesson_id)) $errors[] = "Please select a valid lesson.";
    
    // Image upload handling
    $image_path = '';
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $image_name = $_FILES['image']['name'];
        $image_tmp = $_FILES['image']['tmp_name'];
        $image_ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
        $allowed_image_exts = ['jpg', 'jpeg', 'png', 'gif'];
        if (!in_array($image_ext, $allowed_image_exts)) {
            $errors[] = "Only JPG, JPEG, PNG, or GIF files are allowed for image.";
        } else {
            $upload_dir = 'uploads/';
            $image_path = $upload_dir . uniqid() . '.' . $image_ext;
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
            if (!move_uploaded_file($image_tmp, $image_path)) {
                $errors[] = "Failed to upload image.";
            }
        }
    } else {
        $errors[] = "Image is required.";
    }

    // Video upload handling
    $video_path = '';
    if (isset($_FILES['video']) && $_FILES['video']['error'] === UPLOAD_ERR_OK) {
        $video_name = $_FILES['video']['name'];
        $video_tmp = $_FILES['video']['tmp_name'];
        $video_ext = strtolower(pathinfo($video_name, PATHINFO_EXTENSION));
        $allowed_video_exts = ['mp4', 'avi', 'mov'];
        if (!in_array($video_ext, $allowed_video_exts)) {
            $errors[] = "Only MP4, AVI, or MOV files are allowed for video.";
        } elseif ($_FILES['video']['size'] > 2000000000) { // Limit to 2GB
            $errors[] = "Video size must be less than 2GB.";
        } else {
            $upload_dir = 'uploads/videos/';
            $video_path = $upload_dir . uniqid() . '.' . $video_ext;
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
            if (!move_uploaded_file($video_tmp, $video_path)) {
                $errors[] = "Failed to upload video.";
            }
        }
    } else {
        $errors[] = "Video is required.";
    }

    // If no errors, save to database
    if (empty($errors)) {
        $stmt = $conn->prepare("INSERT INTO videos (name, description, course_id, lesson_id, image, video_path) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssiiss", $video_name, $description, $course_id, $lesson_id, $image_path, $video_path);
        if ($stmt->execute()) {
            $success = "Video saved to database successfully!";
            $_POST = []; // Reset form fields
        } else {
            $errors[] = "Failed to save video to 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 dropdown (initially all, will be filtered by JS)
$lesson_result = $conn->query("SELECT id, name, course_id FROM lessons ORDER BY name");
$lessons = $lesson_result->fetch_all(MYSQLI_ASSOC);

// Fetch all videos for the table
$video_result = $conn->query("SELECT v.id, v.name AS video_name, v.description, v.image, v.video_path, c.name AS course_name, l.name AS lesson_name FROM videos v JOIN courses c ON v.course_id = c.id JOIN lessons l ON v.lesson_id = l.id ORDER BY v.created_at DESC");
$videos = $video_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, textarea, select { transition: all 0.2s ease; }
        input:focus, textarea: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); }
        .video-image { transition: transform 0.2s ease; }
        .video-image:hover { transform: scale(1.1); }
        .progress-container, .upload-success { display: none; }
        .progress-container.active, .upload-success.active { display: block; }
        .progress-bar { transition: width 0.3s ease; }
        @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">
        <!-- Add Video 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">Add New Video</h2>
            
            <!-- Upload Success Message -->
            <p id="upload-success" class="upload-success success text-center font-semibold mb-4">Video uploaded successfully!</p>

            <!-- Database 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; ?>

            <!-- Progress Bar -->
            <div id="progress-container" class="progress-container mb-4">
                <p class="text-sm font-medium text-gray-700">Uploading...</p>
                <div class="w-full bg-gray-200 rounded-full h-4">
                    <div id="progress-bar" class="progress-bar bg-yellow-500 h-4 rounded-full" style="width: 0%"></div>
                </div>
                <p id="progress-text" class="text-sm text-gray-700 mt-1">0%</p>
            </div>

            <!-- Form -->
            <form id="video-form" method="POST" enctype="multipart/form-data" class="space-y-4">
                <div>
                    <label for="video_name" class="block text-sm font-medium text-gray-700">Video Name</label>
                    <input type="text" id="video_name" name="video_name" value="<?php echo isset($_POST['video_name']) ? htmlspecialchars($_POST['video_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="description" class="block text-sm font-medium text-gray-700">Description</label>
                    <textarea id="description" name="description" rows="4" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required><?php echo isset($_POST['description']) ? htmlspecialchars($_POST['description']) : ''; ?></textarea>
                </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 isset($_POST['course_id']) && $_POST['course_id'] == $course['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($course['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label for="lesson_id" class="block text-sm font-medium text-gray-700">Select Lesson</label>
                    <select id="lesson_id" name="lesson_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 lesson</option>
                        <?php foreach ($lessons as $lesson): ?>
                            <option value="<?php echo htmlspecialchars($lesson['id']); ?>" data-course-id="<?php echo htmlspecialchars($lesson['course_id']); ?>" <?php echo isset($_POST['lesson_id']) && $_POST['lesson_id'] == $lesson['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($lesson['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label for="image" class="block text-sm font-medium text-gray-700">Video Thumbnail</label>
                    <input type="file" id="image" name="image" accept="image/*" 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="video" class="block text-sm font-medium text-gray-700">Video Tutorial</label>
                    <input type="file" id="video" name="video" accept="video/mp4,video/avi,video/mov" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                </div>
                <div>
                    <button type="submit" class="w-full bg-yellow-500 text-white p-2 rounded-md hover:bg-yellow-600 transition-colors">Add Video</button>
                </div>
            </form>
        </div>

        <!-- Videos 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 Videos</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">Video Name</th>
                            <th class="p-3 text-left font-bold">Description</th>
                            <th class="p-3 text-left font-bold">Course</th>
                            <th class="p-3 text-left font-bold">Lesson</th>
                            <th class="p-3 text-left font-bold">Image</th>
                            <th class="p-3 text-left font-bold">Video</th>
                            <th class="p-3 text-left font-bold">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($videos)): ?>
                            <tr>
                                <td colspan="8" class="p-3 text-center text-gray-500">No videos found.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($videos as $video): ?>
                                <tr>
                                    <td class="p-3 border-b border-gray-200"><?php echo htmlspecialchars($video['id']); ?></td>
                                    <td class="p-3 border-b border-gray-200"><?php echo htmlspecialchars($video['video_name']); ?></td>
                                    <td class="p-3 border-b border-gray-200"><?php echo htmlspecialchars(substr($video['description'], 0, 50)) . (strlen($video['description']) > 50 ? '...' : ''); ?></td>
                                    <td class="p-3 border-b border-gray-200"><?php echo htmlspecialchars($video['course_name']); ?></td>
                                    <td class="p-3 border-b border-gray-200"><?php echo htmlspecialchars($video['lesson_name']); ?></td>
                                    <td class="p-3 border-b border-gray-200">
                                        <img src="<?php echo htmlspecialchars($video['image']); ?>" alt="Video Thumbnail" class="video-image w-16 h-16 object-cover rounded-md">
                                    </td>
                                    <td class="p-3 border-b border-gray-200">
                                        <a href="<?php echo htmlspecialchars($video['video_path']); ?>" target="_blank" class="text-blue-900 hover:text-yellow-500">View Video</a>
                                    </td>
                                    <td class="p-3 border-b border-gray-200">
                                        <a href="edit_video.php?id=<?php echo htmlspecialchars($video['id']); ?>" class="text-blue-900 hover:text-yellow-500 mr-2">Edit</a>
                                        <a href="add_video.php?delete_id=<?php echo htmlspecialchars($video['id']); ?>" class="text-red-600 hover:text-red-700" onclick="return confirm('Are you sure you want to delete this video?')">Delete</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- JavaScript for dynamic lesson dropdown and upload progress -->
    <script>
        // Dynamic lesson dropdown
        const courseSelect = document.getElementById('course_id');
        const lessonSelect = document.getElementById('lesson_id');
        const lessons = Array.from(lessonSelect.options).slice(1); // Skip the "Select a lesson" option

        courseSelect.addEventListener('change', function() {
            const selectedCourseId = this.value;
            lessonSelect.innerHTML = '<option value="">Select a lesson</option>';
            lessons.forEach(option => {
                if (!selectedCourseId || option.getAttribute('data-course-id') === selectedCourseId) {
                    lessonSelect.appendChild(option);
                }
            });
        });

        // Upload progress bar and success message
        const form = document.getElementById('video-form');
        const progressContainer = document.getElementById('progress-container');
        const progressBar = document.getElementById('progress-bar');
        const progressText = document.getElementById('progress-text');
        const uploadSuccess = document.getElementById('upload-success');

        form.addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const xhr = new XMLHttpRequest();

            xhr.upload.addEventListener('progress', function(event) {
                if (event.lengthComputable) {
                    const percentComplete = Math.round((event.loaded / event.total) * 100);
                    progressContainer.classList.add('active');
                    progressBar.style.width = percentComplete + '%';
                    progressText.textContent = percentComplete + '%';
                }
            });

            xhr.onreadystatechange = function() {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    progressContainer.classList.remove('active');
                    if (xhr.status === 200) {
                        uploadSuccess.classList.add('active');
                        setTimeout(() => {
                            uploadSuccess.classList.remove('active');
                            window.location.reload(); // Reload to show database success/errors
                        }, 2000); // Show success for 2 seconds
                    } else {
                        alert('An error occurred during upload.');
                    }
                }
            };

            xhr.open('POST', 'add_video.php', true);
            xhr.send(formData);
        });
    </script>
</div>

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