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

// 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 image path to delete from server
    $stmt = $conn->prepare("SELECT image FROM courses WHERE id = ?");
    $stmt->bind_param("i", $delete_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($row = $result->fetch_assoc()) {
        // Delete image file from server
        if (file_exists($row['image'])) unlink($row['image']);
        // Delete course record from database (lessons and videos will be deleted via ON DELETE CASCADE)
        $delete_stmt = $conn->prepare("DELETE FROM courses WHERE id = ?");
        $delete_stmt->bind_param("i", $delete_id);
        if ($delete_stmt->execute()) {
            $success = "Course deleted successfully!";
        } else {
            $errors[] = "Failed to delete course from database.";
        }
        $delete_stmt->close();
    } else {
        $errors[] = "Course not found.";
    }
    $stmt->close();
}

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $course_name = trim($_POST['course_name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $price = trim($_POST['price'] ?? '');
    $discount = trim($_POST['discount'] ?? '');
    
    // Basic validation
    if (empty($course_name)) $errors[] = "Course Name is required.";
    if (empty($description)) $errors[] = "Description is required.";
    if (empty($price) || !is_numeric($price) || $price < 0) $errors[] = "Valid Price is required.";
    if (empty($discount) || !is_numeric($discount) || $discount < 0 || $discount > 100) $errors[] = "Discount must be between 0 and 100.";
    
    // 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_exts = ['jpg', 'jpeg', 'png', 'gif'];
        if (!in_array($image_ext, $allowed_exts)) {
            $errors[] = "Only JPG, JPEG, PNG, or GIF files are allowed.";
        } 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.";
    }

    // If no errors, save to database
    if (empty($errors)) {
        $stmt = $conn->prepare("INSERT INTO courses (name, description, price, discount, image) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("ssdss", $course_name, $description, $price, $discount, $image_path);
        if ($stmt->execute()) {
            $success = "Course added successfully!";
            $_POST = []; // Reset form fields
        } else {
            $errors[] = "Failed to save course to database.";
        }
        $stmt->close();
    }
}

// Fetch all courses for the table
$result = $conn->query("SELECT id, name, description, price, discount, image FROM courses ORDER BY created_at DESC");
$courses = $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 { transition: all 0.2s ease; }
        input:focus, textarea: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); }
        .course-image { transition: transform 0.2s ease; }
        .course-image:hover { transform: scale(1.1); }
        @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 Course 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 Course</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 -->
            <form method="POST" enctype="multipart/form-data" class="space-y-4">
                <div>
                    <label for="course_name" class="block text-sm font-medium text-gray-700">Course Name</label>
                    <input type="text" id="course_name" name="course_name" value="<?php echo isset($_POST['course_name']) ? htmlspecialchars($_POST['course_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="price" class="block text-sm font-medium text-gray-700">Price ($)</label>
                    <input type="number" id="price" name="price" value="<?php echo isset($_POST['price']) ? htmlspecialchars($_POST['price']) : ''; ?>" min="0" step="0.01" 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="discount" class="block text-sm font-medium text-gray-700">Discount (%)</label>
                    <input type="number" id="discount" name="discount" value="<?php echo isset($_POST['discount']) ? htmlspecialchars($_POST['discount']) : ''; ?>" min="0" max="100" 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="image" class="block text-sm font-medium text-gray-700">Course Image</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>
                    <button type="submit" class="w-full bg-yellow-500 text-white p-2 rounded-md hover:bg-yellow-600 transition-colors">Add Course</button>
                </div>
            </form>
        </div>

        <!-- Courses 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 Courses</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">Name</th>
                            <th class="p-3 text-left font-bold">Description</th>
                            <th class="p-3 text-left font-bold">Price ($)</th>
                            <th class="p-3 text-left font-bold">Discount (%)</th>
                            <th class="p-3 text-left font-bold">Image</th>
                            <th class="p-3 text-left font-bold">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($courses)): ?>
                            <tr>
                                <td colspan="7" class="p-3 text-center text-gray-500">No courses found.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($courses as $course): ?>
                                <tr>
                                    <td class="p-3 border-b border-gray-200"><?php echo htmlspecialchars($course['id']); ?></td>
                                    <td class="p-3 border-b border-gray-200"><?php echo htmlspecialchars($course['name']); ?></td>
                                    <td class="p-3 border-b border-gray-200"><?php echo htmlspecialchars(substr($course['description'], 0, 50)) . (strlen($course['description']) > 50 ? '...' : ''); ?></td>
                                    <td class="p-3 border-b border-gray-200"><?php echo htmlspecialchars(number_format($course['price'], 2)); ?></td>
                                    <td class="p-3 border-b border-gray-200"><?php echo htmlspecialchars($course['discount']); ?></td>
                                    <td class="p-3 border-b border-gray-200">
                                        <img src="<?php echo htmlspecialchars($course['image']); ?>" alt="Course Image" class="course-image w-16 h-16 object-cover rounded-md">
                                    </td>
                                    <td class="p-3 border-b border-gray-200">
                                        <a href="edit_course.php?id=<?php echo htmlspecialchars($course['id']); ?>" class="text-blue-900 hover:text-yellow-500 mr-2">Edit</a>
                                        <a href="course_add.php?delete_id=<?php echo htmlspecialchars($course['id']); ?>" class="text-red-600 hover:text-red-700" onclick="return confirm('Are you sure you want to delete this course? This will also delete associated lessons and 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
?>