<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../classes/Course.php';

requireLogin();
requireAnyRole(['instructor']);

$user = getCurrentUser();
$db = Database::getInstance();
$courseModel = new Course();

$id = (int)($_GET['id'] ?? 0);
$course = null;
if ($id) {
    $course = $courseModel->getById($id);
    if (!$course || (int)$course['instructor_id'] !== (int)$user['id']) {
        setFlashMessage('error', 'Course not found or you do not have permission to edit it.');
        redirect('courses.php?mine=1');
    }
}

$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $short_description = trim($_POST['short_description'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $category_id = (int)($_POST['category_id'] ?? 0);
    $price = (float)($_POST['price'] ?? 0);
    $currency = trim($_POST['currency'] ?? 'USD');
    $is_published = isset($_POST['is_published']) ? 1 : 0;
    $visibility = trim($_POST['visibility'] ?? 'public');
    $allowedRegions = ['global','usa','europe','africa'];
    $region = trim($_POST['region'] ?? ($_SESSION['region'] ?? 'global'));
    if (!in_array($region, $allowedRegions, true)) {
        $region = 'global';
    }

    if (empty($title) || empty($description) || empty($category_id)) {
        $errors[] = 'Title, description and category are required.';
    }

    if (empty($errors)) {
        // Status reflects Published checkbox for instructor convenience
        $status = $is_published ? 'published' : 'draft';

        $data = [
            'title' => $title,
            'short_description' => $short_description,
            'description' => $description,
            'category_id' => $category_id,
            'price' => $price,
            'currency' => $currency,
            'is_published' => $is_published,
            'status' => $status,
            'visibility' => $visibility,
            'region' => $region,
            'instructor_id' => $user['id']
        ];

        try {
            if ($id) {
                $courseModel->update($id, $data);
                $courseId = $id;
            } else {
                $courseId = $courseModel->create($data);
            }

            // Handle thumbnail upload
            if (!empty($_FILES['thumbnail']['name'])) {
                $uploadDir = __DIR__ . '/../uploads/courses/' . $courseId;
                if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
                $ext = pathinfo($_FILES['thumbnail']['name'], PATHINFO_EXTENSION);
                $filename = 'thumbnail_' . time() . '.' . $ext;
                $target = $uploadDir . '/' . $filename;
                if (move_uploaded_file($_FILES['thumbnail']['tmp_name'], $target)) {
                    $relPath = 'uploads/courses/' . $courseId . '/' . $filename;
                    $courseModel->update($courseId, ['thumbnail' => $relPath]);
                }
            }

            setFlashMessage('success', 'Course saved successfully.');
            header('Location: ' . APP_URL . '/lms/courses.php?course_id=' . $courseId);
            exit;
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
    }
}

$categories = $db->getAll("SELECT id, name FROM categories WHERE is_active = 1 ORDER BY name");
$pageTitle = $id ? 'Edit Course' : 'New Course';
include __DIR__ . '/includes/header.php';
?>

<div class="container-xxl">
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="m-0"><?php echo htmlspecialchars($pageTitle); ?></h5>
            <a href="<?php echo APP_URL; ?>/lms/courses.php?mine=1" class="btn btn-outline-secondary btn-sm">Back</a>
        </div>
        <div class="card-body">
            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger"><ul class="mb-0"><?php foreach ($errors as $err): ?><li><?php echo htmlspecialchars($err); ?></li><?php endforeach; ?></ul></div>
            <?php endif; ?>

            <form method="post" enctype="multipart/form-data">
                <div class="mb-3">
                    <label class="form-label">Title</label>
                    <input type="text" name="title" class="form-control" value="<?php echo htmlspecialchars($course['title'] ?? ''); ?>" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">Short Description</label>
                    <input type="text" name="short_description" class="form-control" value="<?php echo htmlspecialchars($course['short_description'] ?? ''); ?>">
                </div>
                <div class="mb-3">
                    <label class="form-label">Description</label>
                    <textarea name="description" class="form-control" rows="6"><?php echo htmlspecialchars($course['description'] ?? ''); ?></textarea>
                </div>
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Category</label>
                        <select name="category_id" class="form-select" required>
                            <option value="">Select</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo (int)$cat['id']; ?>" <?php echo (int)($course['category_id'] ?? 0) === (int)$cat['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($cat['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2 mb-3">
                        <label class="form-label">Price</label>
                        <input type="number" step="0.01" name="price" class="form-control" value="<?php echo htmlspecialchars($course['price'] ?? 0); ?>">
                    </div>
                    <div class="col-md-2 mb-3">
                        <label class="form-label">Currency</label>
                        <input type="text" name="currency" class="form-control" value="<?php echo htmlspecialchars($course['currency'] ?? 'USD'); ?>">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Thumbnail</label>
                        <input type="file" name="thumbnail" class="form-control">
                        <?php if (!empty($course['thumbnail'])):
                            // Ensure we provide an absolute URL for the thumbnail and only show it when the file exists
                            $thumb = $course['thumbnail'];
                            $thumbPath = __DIR__ . '/../' . ltrim($thumb, '/');
                            $baseUrl = defined('APP_URL') ? rtrim(APP_URL, '/') : '';
                            $thumbSrc = (stripos($thumb, 'http') === 0 || strpos($thumb, '/') === 0) ? $thumb : $baseUrl . '/' . ltrim($thumb, '/');
                            if (file_exists($thumbPath)): ?>
                                <img src="<?php echo htmlspecialchars($thumbSrc); ?>" class="img-fluid mt-2" style="max-width:120px;">
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Visibility</label>
                        <select name="visibility" id="visibilitySelect" class="form-select">
                            <option value="public" <?php echo (($course['visibility'] ?? 'public') === 'public') ? 'selected' : ''; ?>>Public</option>
                            <option value="private" <?php echo (($course['visibility'] ?? 'public') === 'private') ? 'selected' : ''; ?>>Private</option>
                            <option value="region" <?php echo (($course['visibility'] ?? 'public') === 'region') ? 'selected' : ''; ?>>Region</option>
                        </select>
                    </div>

                    <div class="col-md-4 mb-3" id="regionSelectWrapper" style="display: <?php echo (($course['visibility'] ?? '') === 'region') ? 'block' : 'none'; ?>;">
                        <label class="form-label">Region</label>
                        <select name="region" class="form-select">
                            <?php $currentRegion = $course['region'] ?? ($_SESSION['region'] ?? 'global'); $regions = ['global','usa','europe','africa']; foreach ($regions as $r): ?>
                                <option value="<?php echo $r; ?>" <?php echo ($currentRegion === $r) ? 'selected' : ''; ?>><?php echo ucfirst($r); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php if (!empty($id)): ?>
                    <div class="col-md-8 mb-3 d-flex align-items-end justify-content-end">
                        <a href="<?php echo APP_URL; ?>/lms/course_modules.php?course_id=<?php echo (int)$id; ?>" class="btn btn-outline-secondary ms-2">Manage Modules</a>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="form-check mb-3">
                    <input type="checkbox" name="is_published" value="1" class="form-check-input" id="is_published" <?php echo (!empty($course['is_published']) ? 'checked' : ''); ?>>
                    <label for="is_published" class="form-check-label">Published</label>
                </div>

                <button class="btn btn-primary">Save</button>
            </form>

            <script>
                // Toggle region selector when visibility == 'region'
                (function(){
                    const vis = document.getElementById('visibilitySelect');
                    const regionWrap = document.getElementById('regionSelectWrapper');
                    function toggleRegion(){
                        if (!vis || !regionWrap) return;
                        regionWrap.style.display = vis.value === 'region' ? 'block' : 'none';
                    }
                    if (vis){ vis.addEventListener('change', toggleRegion); toggleRegion(); }
                })();
            </script>
        </div>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php';
