<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.php';
$lms_config = require '../../config/lms.php';
require_once '../../includes/functions.php';
require_once '../../includes/middleware.php';

// Check if user is instructor or admin
anyRoleMiddleware(['instructor', 'admin']);

$user = getUserContext();
$db = getDB();
$userId = $_SESSION['user_id'];

$courseId = $_GET['id'] ?? null;
if (!$courseId || !is_numeric($courseId)) {
    $_SESSION['error_message'] = 'Invalid course ID';
    header('Location: index.php');
    exit;
}

// Get course details - verify ownership
$stmt = $db->prepare("
    SELECT c.*, cc.name as category_name 
    FROM courses c 
    LEFT JOIN course_categories cc ON c.category_id = cc.id 
    WHERE c.id = ? AND c.instructor_id = ?
");
$stmt->execute([$courseId, $userId]);
$course = $stmt->fetch();

if (!$course) {
    $_SESSION['error_message'] = 'Course not found or access denied';
    header('Location: index.php');
    exit;
}

// Get categories dropdown
$stmt = $db->query("SELECT id, name FROM course_categories WHERE is_active = 1 ORDER BY name");
$categories = $stmt->fetchAll();

// Get enrollment stats
$stmt = $db->prepare("SELECT COUNT(*) as enrollments, AVG(progress_percentage) as avg_progress FROM course_enrollments WHERE course_id = ?");
$stmt->execute([$courseId]);
$stats = $stmt->fetch();

// Handle form submission
$message = '';
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title']);
    $slug = trim($_POST['slug'] ?? '');
    $description = trim($_POST['description']);
    $short_description = trim($_POST['short_description']);
    $category_id = !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null;
    $level = $_POST['level'];
    $language = trim($_POST['language']);
    $duration_hours = (float)$_POST['duration_hours'];
    $price = (float)$_POST['price'];
    $currency = trim($_POST['currency']);
    $max_students = !empty($_POST['max_students']) ? (int)$_POST['max_students'] : null;
    $prerequisites = trim($_POST['prerequisites']);
    $status = $_POST['status'];
    $is_featured = isset($_POST['is_featured']);
    $is_free = isset($_POST['is_free']);

    // Auto-generate slug if empty
    if (empty($slug)) {
        $baseSlug = strtolower(preg_replace('/[^a-zA-Z0-9\s-]/', '', str_replace(' ', '-', $title)));
        $slug = $baseSlug;
        // Check uniqueness (simplified)
        $counter = 1;
        while (true) {
            $checkStmt = $db->prepare("SELECT id FROM courses WHERE slug = ? AND id != ?");
            $checkStmt->execute([$slug, $courseId]);
            if (!$checkStmt->fetch()) break;
            $slug = $baseSlug . '-' . $counter++;
        }
    }

    if (empty($title) || empty($description)) {
        $error = 'Title and description are required.';
    } else {
        try {
            // Handle thumbnail upload
            $thumbnail = $course['thumbnail'];
            if (isset($_FILES['thumbnail']) && $_FILES['thumbnail']['error'] === UPLOAD_ERR_OK) {
                $uploadDir = '../../uploads/course-thumbnails/';
                if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
                $fileName = time() . '_' . basename($_FILES['thumbnail']['name']);
                $targetPath = $uploadDir . $fileName;
                if (move_uploaded_file($_FILES['thumbnail']['tmp_name'], $targetPath)) {
                    $thumbnail = 'uploads/course-thumbnails/' . $fileName;
                    // Delete old thumbnail if exists
                    if ($course['thumbnail'] && file_exists('../../' . $course['thumbnail'])) {
                        unlink('../../' . $course['thumbnail']);
                    }
                }
            }

            // Handle banner upload
            $banner_image = $course['banner_image'];
            if (isset($_FILES['banner_image']) && $_FILES['banner_image']['error'] === UPLOAD_ERR_OK) {
                $uploadDir = '../../uploads/course-banners/';
                if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
                $fileName = time() . '_' . basename($_FILES['banner_image']['name']);
                $targetPath = $uploadDir . $fileName;
                if (move_uploaded_file($_FILES['banner_image']['tmp_name'], $targetPath)) {
                    $banner_image = 'uploads/course-banners/' . $fileName;
                    // Delete old banner if exists
                    if ($course['banner_image'] && file_exists('../../' . $course['banner_image'])) {
                        unlink('../../' . $course['banner_image']);
                    }
                }
            }

            // Parse JSON fields
            $learning_objectives = isset($_POST['learning_objectives']) ? array_filter(array_map('trim', $_POST['learning_objectives'])) : json_decode($course['learning_objectives'], true) ?: [];
            $tags = isset($_POST['tags']) ? array_filter(array_map('trim', explode(',', $_POST['tags']))) : json_decode($course['tags'], true) ?: [];

            // Update course
            $stmt = $db->prepare("
                UPDATE courses SET 
                    title=?, slug=?, description=?, short_description=?, category_id=?,
                    thumbnail=?, banner_image=?, price=?, currency=?, level=?,
                    duration_hours=?, language=?, max_students=?, prerequisites=?,
                    learning_objectives=?, tags=?, status=?, is_featured=?, is_free=?,
                    updated_at=NOW()
                WHERE id=?
            ");
            $stmt->execute([
                $title, $slug, $description, $short_description, $category_id,
                $thumbnail, $banner_image, $price, $currency, $level,
                $duration_hours, $language, $max_students, $prerequisites,
                json_encode($learning_objectives), json_encode($tags), $status, $is_featured, $is_free,
                $courseId
            ]);

            $message = 'Course updated successfully! <a href="course_builder.php?id=' . $courseId . '" class="font-semibold hover:underline">→ Continue editing curriculum</a>';

            // Refresh course data
            $stmt->execute([$courseId, $userId]);
            $course = $stmt->fetch();
            $stats = ['enrollments' => $db->prepare("SELECT COUNT(*) FROM course_enrollments WHERE course_id = ?")->execute([$courseId])->fetchColumn()];

        } catch (PDOException $e) {
            $error = 'Database error: ' . $e->getMessage();
        }
    }
}

$page_title = 'Edit Course: ' . htmlspecialchars($course['title']) . ' - ' . $lms_config['lms']['site_name'];
$active_link = 'courses';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: { extend: {
                colors: {
                    'primary-blue': '#1E3A8A',
                    'background-light': '#F8FAFC',
                    'text-dark': '#1F2937',
                    'accent-subtle': '#E5E7EB'
                },
                fontFamily: { sans: ['Inter', 'sans-serif'] }
            }}
        }
    </script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        html, body { height: 100%; }
        ::-webkit-scrollbar { width: 8px; }
        ::-webkit-scrollbar-thumb { background-color: #D1D5DB; border-radius: 4px; }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">
    <!-- Toast Container -->
    <div id="toast-container"></div>
    <!-- Sidebar Overlay -->
    <div id="sidebar-overlay" class="sidebar-overlay lg:hidden"></div>

    <div class="flex">
        <?php include '../includes/sidebar.php'; ?>

        <!-- Header -->
        <header class="bg-white shadow-sm fixed top-0 left-0 right-0 z-10 border-b border-accent-subtle">
            <div class="px-4 sm:px-6 lg:px-8 py-4 flex justify-between items-center">
                <div class="flex items-center space-x-3">
                    <img src="../../assets/images/logo_1757657555.jpg" alt="LMS Logo" class="h-10 w-10">
                    <div>
                        <h1 class="text-xl font-bold text-primary-blue"><?php echo htmlspecialchars($lms_config['lms']['site_name']); ?></h1>
                        <p class="text-sm text-gray-600">Edit Course: <?php echo htmlspecialchars(substr($course['title'], 0, 30)) . (strlen($course['title']) > 30 ? '...' : ''); ?></p>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <span class="text-sm font-medium hidden sm:inline"><?php echo htmlspecialchars($user['username']); ?></span>
                    <img class="h-10 w-10 rounded-full border-2 border-primary-blue" src="https://placehold.co/100x100/1E3A8A/ffffff?text=<?php echo strtoupper(substr($user['username'] ?? 'U', 0, 1)); ?>">
                    <button class="lg:hidden p-2 rounded-lg hover:bg-accent-subtle" id="mobileMenuButton">☰</button>
                </div>
            </div>
        </header>

        <!-- Main Content -->
        <main class="flex-1 overflow-y-auto pt-16 lg:ml-0">
            <!-- Mobile Menu -->
            <div id="mobileMenu" class="fixed inset-0 bg-white z-20 p-6 transform -translate-x-full lg:hidden transition-transform">
                <div class="flex justify-between items-center mb-10">
                    <div class="text-xl font-bold text-primary-blue"><?php echo htmlspecialchars($lms_config['lms']['site_name']); ?></div>
                    <button id="closeMobileMenu" class="text-3xl">&times;</button>
                </div>
                <nav class="space-y-4">
                    <a href="../dashboard.php" class="block p-3 rounded-lg hover:bg-accent-subtle">🏠 Dashboard</a>
                    <a href="index.php" class="block p-3 bg-primary-blue text-white rounded-lg font-semibold">📚 My Courses</a>
                    <a href="../exams/index.php" class="block p-3 rounded-lg hover:bg-accent-subtle">📝 Exams</a>
                    <a href="../../logout.php" class="block p-3 rounded-lg hover:bg-accent-subtle">🚪 Logout</a>
                </nav>
            </div>

            <div class="p-6">
                <!-- Course Stats Cards -->
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                    <div class="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle text-center">
                        <i class="fas fa-users text-3xl text-blue-500 mb-2"></i>
                        <div class="text-3xl font-bold text-gray-900"><?php echo $stats['enrollments'] ?? 0; ?></div>
                        <div class="text-sm text-gray-500">Enrollments</div>
                    </div>
                    <div class="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle text-center">
                        <i class="fas fa-chart-line text-3xl text-green-500 mb-2"></i>
                        <div class="text-3xl font-bold text-gray-900"><?php echo round(($stats['avg_progress'] ?? 0), 1); ?>%</div>
                        <div class="text-sm text-gray-500">Avg. Progress</div>
                    </div>
                    <div class="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle text-center">
                        <span class="text-xl font-bold px-3 py-1 rounded-full bg-<?php echo $course['status'] == 'published' ? 'green' : 'yellow'; ?>-100 text-<?php echo $course['status'] == 'published' ? 'green' : 'yellow'; ?>-800">
                            <?php echo ucfirst($course['status']); ?>
                        </span>
                        <div class="text-sm text-gray-500 mt-2">Status</div>
                    </div>
                </div>

                <!-- Messages -->
                <?php if ($message): ?>
                    <div class="bg-green-50 border border-green-200 text-green-800 p-4 rounded-xl mb-6"><?php echo $message; ?></div>
                <?php endif; ?>
                <?php if ($error): ?>
                    <div class="bg-red-50 border border-red-200 text-red-800 p-4 rounded-xl mb-6"><?php echo htmlspecialchars($error); ?></div>
                <?php endif; ?>

                <!-- Main Form -->
                <div class="bg-white rounded-xl shadow-lg border border-accent-subtle overflow-hidden">
                    <div class="p-6 border-b border-gray-100">
                        <h2 class="text-2xl font-bold text-gray-900 flex items-center gap-3">
                            <i class="fas fa-edit text-blue-500"></i>
                            Edit Course Details
                        </h2>
                        <p class="text-gray-600 mt-1">Update course metadata, pricing, and status. <a href="course_builder.php?id=<?php echo $courseId; ?>" class="text-blue-600 hover:underline font-semibold">→ Advanced curriculum editor</a></p>
                    </div>

                    <form method="POST" enctype="multipart/form-data" class="p-6 space-y-6">
                        <!-- Basic Info -->
                        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                            <div>
                                <label class="block text-sm font-semibold text-gray-700 mb-2">Course Title <span class="text-red-500">*</span></label>
                                <input type="text" name="title" required value="<?php echo htmlspecialchars($course['title']); ?>" 
                                       class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition">
                            </div>
                            <div>
                                <label class="block text-sm font-semibold text-gray-700 mb-2">Status</label>
                                <select name="status" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                                    <option value="draft" <?php echo $course['status']=='draft'?'selected':''; ?>>Draft</option>
                                    <option value="published" <?php echo $course['status']=='published'?'selected':''; ?>>Published</option>
                                    <option value="archived" <?php echo $course['status']=='archived'?'selected':''; ?>>Archived</option>
                                </select>
                            </div>
                        </div>

                        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                            <div>
                                <label class="block text-sm font-semibold text-gray-700 mb-2">URL Slug</label>
                                <input type="text" name="slug" value="<?php echo htmlspecialchars($course['slug']); ?>" 
                                       class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                                <p class="text-xs text-gray-500 mt-1">Leave empty to auto-generate from title</p>
                            </div>
                            <div>
                                <label class="block text-sm font-semibold text-gray-700 mb-2">Category</label>
                                <select name="category_id" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                                    <option value="">No category</option>
                                    <?php foreach ($categories as $cat): ?>
                                        <option value="<?php echo $cat['id']; ?>" <?php echo $course['category_id']==$cat['id']?'selected':''; ?>>
                                            <?php echo htmlspecialchars($cat['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <!-- Descriptions -->
                        <div class="lg:col-span-2">
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Short Description</label>
                            <textarea name="short_description" rows="3" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"><?php echo htmlspecialchars($course['short_description']); ?></textarea>
                        </div>
                        <div class="lg:col-span-2">
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Full Description <span class="text-red-500">*</span></label>
                            <textarea name="description" rows="6" required class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"><?php echo htmlspecialchars($course['description']); ?></textarea>
                        </div>

                        <!-- Pricing & Details -->
                        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                            <div>
                                <label class="block text-sm font-semibold text-gray-700 mb-2">Price ($)</label>
                                <input type="number" name="price" step="0.01" min="0" value="<?php echo $course['price']; ?>" 
                                       class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div class="flex items-center space-x-4">
                                <label class="flex items-center">
                                    <input type="checkbox" name="is_free" <?php echo $course['is_free'] ? 'checked' : ''; ?> class="mr-2 rounded">
                                    <span class="text-sm font-semibold text-gray-700">Free Course</span>
                                </label>
                            </div>
                        </div>

                        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                            <div>
                                <label class="block text-sm font-semibold text-gray-700 mb-2">Level</label>
                                <select name="level" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                                    <option value="beginner" <?php echo $course['level']=='beginner'?'selected':''; ?>>Beginner</option>
                                    <option value="intermediate" <?php echo $course['level']=='intermediate'?'selected':''; ?>>Intermediate</option>
                                    <option value="advanced" <?php echo $course['level']=='advanced'?'selected':''; ?>>Advanced</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-sm font-semibold text-gray-700 mb-2">Duration (hours)</label>
                                <input type="number" name="duration_hours" step="0.5" min="0" value="<?php echo $course['duration_hours']; ?>" 
                                       class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                            </div>
                        </div>

                        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                            <div>
                                <label class="block text-sm font-semibold text-gray-700 mb-2">Language</label>
                                <input type="text" name="language" value="<?php echo htmlspecialchars($course['language'] ?? 'English'); ?>" 
                                       class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div>
                                <label class="block text-sm font-semibold text-gray-700 mb-2">Max Students</label>
                                <input type="number" name="max_students" min="1" value="<?php echo $course['max_students']; ?>" 
                                       class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                            </div>
                        </div>

                        <!-- Media Uploads -->
                        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                            <div>
                                <label class="block text-sm font-semibold text-gray-700 mb-2">Thumbnail (Recommended 1280x720)</label>
                                <div class="flex items-center gap-4">
                                    <?php if ($course['thumbnail']): ?>
                                        <img src="../../<?php echo htmlspecialchars($course['thumbnail']); ?>" alt="Current thumbnail" class="w-24 h-16 object-cover rounded-lg border">
                                    <?php endif; ?>
                                    <input type="file" name="thumbnail" accept="image/*" class="flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                                </div>
                            </div>
                            <div>
                                <label class="block text-sm font-semibold text-gray-700 mb-2">Banner Image</label>
                                <div class="flex items-center gap-4">
                                    <?php if ($course['banner_image']): ?>
                                        <img src="../../<?php echo htmlspecialchars($course['banner_image']); ?>" alt="Current banner" class="w-48 h-16 object-cover rounded-lg border">
                                    <?php endif; ?>
                                    <input type="file" name="banner_image" accept="image/*" class="flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                                </div>
                            </div>
                        </div>

                        <!-- Additional Fields -->
                        <div class="lg:col-span-2">
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Prerequisites</label>
                            <textarea name="prerequisites" rows="3" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"><?php echo htmlspecialchars($course['prerequisites']); ?></textarea>
                        </div>

                        <!-- Actions -->
                        <div class="flex flex-col sm:flex-row gap-4 pt-4 border-t border-gray-100">
                            <button type="submit" class="flex-1 bg-blue-600 hover:bg-blue-700 text-white font-semibold py-3 px-6 rounded-lg transition duration-200 flex items-center justify-center gap-2">
                                <i class="fas fa-save"></i> Save Changes
                            </button>
                            <a href="course_builder.php?id=<?php echo $courseId; ?>" class="flex-1 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold py-3 px-6 rounded-lg transition duration-200 flex items-center justify-center gap-2 text-center">
                                <i class="fas fa-layer-group"></i> Edit Curriculum
                            </a>
                            <a href="../../courses/detail.php?id=<?php echo $courseId; ?>" target="_blank" class="flex-1 bg-green-600 hover:bg-green-700 text-white font-semibold py-3 px-6 rounded-lg transition duration-200 flex items-center justify-center gap-2">
                                <i class="fas fa-eye"></i> Preview
                            </a>
                            <a href="index.php" class="flex-1 bg-gray-500 hover:bg-gray-600 text-white font-semibold py-3 px-6 rounded-lg transition duration-200 flex items-center justify-center gap-2">
                                <i class="fas fa-list"></i> All Courses
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>

    <script>
        // Mobile menu
        document.getElementById('mobileMenuButton')?.addEventListener('click', () => {
            document.getElementById('mobileMenu').classList.remove('-translate-x-full');
        });
        document.getElementById('closeMobileMenu')?.addEventListener('click', () => {
            document.getElementById('mobileMenu').classList.add('-translate-x-full');
        });
        document.getElementById('sidebar-overlay')?.addEventListener('click', () => {
            document.getElementById('mobileMenu').classList.add('-translate-x-full');
        });

        // Auto-slug generation
        document.querySelector('input[name="title"]')?.addEventListener('input', function() {
            const slugInput = document.querySelector('input[name="slug"]');
            if (!slugInput.value) {
                let slug = this.value.toLowerCase().trim()
                    .replace(/[^\w\s-]/g, '')
                    .replace(/[\s_-]+/g, '-')
                    .replace(/^-+|-+$/g, '');
                slugInput.value = slug;
            }
        });

        // Toast notifications
        <?php if ($message): ?>
            setTimeout(() => {
                const toast = document.createElement('div');
                toast.className = 'fixed top-4 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-xl animate-pulse z-50';
                toast.textContent = '<?php echo addslashes($message); ?>';
                document.body.appendChild(toast);
                setTimeout(() => toast.remove(), 5000);
            }, 500);
        <?php endif; ?>
    </script>
</body>
</html>

