<?php
$db = getDB();

// ---------- Determine action ----------
$action = $_GET['action'] ?? 'list';
if (!in_array($action, ['list', 'create', 'update', 'delete'])) {
    $action = 'list';
}

// ---------- Messages ----------
$errors = [];
$success = $_GET['success'] ?? '';

// ---------- Helper: fetch a single course by ID ----------
function getCourseById($db, $id): ?array {
    $stmt = $db->prepare("SELECT * FROM courses WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}

// ---------- Handle DELETE ----------
if ($action === 'delete' && isset($_GET['id'])) {
    $stmt = $db->prepare("DELETE FROM courses WHERE id = ?");
    $stmt->bind_param("i", $_GET['id']);
    $stmt->execute();
    header('Location: index.php?page=courses&success=deleted');
    exit;
}

// ---------- Handle CREATE / UPDATE form submission ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && in_array($action, ['create', 'update'])) {
    $title = trim($_POST['title'] ?? '');
    $description = $_POST['description'] ?? null;
    $category = $_POST['category'] ?? 'IBA';
    $is_premium = isset($_POST['is_premium']) ? 1 : 0;
    $price = floatval($_POST['price'] ?? 0);
    $sort_order = intval($_POST['sort_order'] ?? 0);

    // ---------- Thumbnail upload handling ----------
    $thumbnail_url = $_POST['existing_thumbnail'] ?? null;
    $uploadDir = __DIR__ . '/../uploads/courses/';
    // Build absolute URL using current scheme + host
    $scheme = (!empty($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'] : 'http');
    $host   = $_SERVER['HTTP_HOST'];
    $baseThumbURL = $scheme . '://' . $host . BASE_URL . 'uploads/courses/';

    if (isset($_FILES['thumbnail_file']) && $_FILES['thumbnail_file']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['thumbnail_file'];
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        $maxSize = 2 * 1024 * 1024; // 2 MB

        if (!in_array($file['type'], $allowedTypes)) {
            $errors[] = 'Invalid image type. Allowed: JPEG, PNG, GIF, WebP.';
        } elseif ($file['size'] > $maxSize) {
            $errors[] = 'Image size must be less than 2 MB.';
        } else {
            $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
            $newFilename = time() . '_' . bin2hex(random_bytes(8)) . '.' . $ext;
            $destination = $uploadDir . $newFilename;

            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }

            if (move_uploaded_file($file['tmp_name'], $destination)) {
                $thumbnail_url = $baseThumbURL . $newFilename;
            } else {
                $errors[] = 'Failed to upload thumbnail. Check folder permissions.';
            }
        }
    }

    // Validation
    if ($title === '') {
        $errors[] = 'Title is required.';
    }
    $allowedCategories = ['IBA', 'BCS', 'IELTS', 'Admission'];
    if (!in_array($category, $allowedCategories)) {
        $errors[] = 'Invalid category.';
    }
    if ($price < 0) {
        $errors[] = 'Price cannot be negative.';
    }

    if (empty($errors)) {
        if ($action === 'create') {
            $stmt = $db->prepare("INSERT INTO courses (title, description, category, is_premium, price, sort_order, thumbnail) 
                                  VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("sssidss", $title, $description, $category, $is_premium, $price, $sort_order, $thumbnail_url);
        } elseif ($action === 'update' && isset($_GET['id'])) {
            $stmt = $db->prepare("UPDATE courses SET title=?, description=?, category=?, is_premium=?, price=?, sort_order=?, thumbnail=? WHERE id=?");
            $stmt->bind_param("sssidssi", $title, $description, $category, $is_premium, $price, $sort_order, $thumbnail_url, $_GET['id']);
        }

        if (isset($stmt)) {
            $stmt->execute();
            $msg = ($action === 'create') ? 'created' : 'updated';
            header('Location: index.php?page=courses&success=' . $msg);
            exit;
        }
    }
}

// ---------- Load existing course for edit ----------
$course = null;
if ($action === 'update' && isset($_GET['id'])) {
    $course = getCourseById($db, $_GET['id']);
    if (!$course) {
        echo '<div class="alert alert-danger">Course not found.</div>';
        $action = 'list';
    }
}

// ---------- Success banners ----------
if ($success === 'created') {
    echo '<div class="alert alert-success">Course created successfully.</div>';
} elseif ($success === 'updated') {
    echo '<div class="alert alert-success">Course updated successfully.</div>';
} elseif ($success === 'deleted') {
    echo '<div class="alert alert-success">Course deleted.</div>';
}

// ---------- LIST view ----------
if ($action === 'list'):
?>
    <h3>Courses</h3>

    <div class="d-flex justify-content-between align-items-center mb-3">
        <form class="d-flex" method="get">
            <input type="hidden" name="page" value="courses">
            <input type="text" name="search" class="form-control me-2" placeholder="Search title..."
                   value="<?= htmlspecialchars($_GET['search'] ?? '') ?>">
            <select name="category" class="form-select me-2" style="width: 150px;">
                <option value="">All categories</option>
                <option value="IBA" <?= ($_GET['category'] ?? '') === 'IBA' ? 'selected' : '' ?>>IBA</option>
                <option value="BCS" <?= ($_GET['category'] ?? '') === 'BCS' ? 'selected' : '' ?>>BCS</option>
                <option value="IELTS" <?= ($_GET['category'] ?? '') === 'IELTS' ? 'selected' : '' ?>>IELTS</option>
                <option value="Admission" <?= ($_GET['category'] ?? '') === 'Admission' ? 'selected' : '' ?>>Admission</option>
            </select>
            <button type="submit" class="btn btn-outline-secondary"><i class="fa fa-search"></i></button>
        </form>
        <a href="?page=courses&action=create" class="btn btn-primary">
            <i class="fa fa-plus me-1"></i> New Course
        </a>
    </div>

    <?php
    // Pagination
    $pageNum = isset($_GET['p']) ? max(1, intval($_GET['p'])) : 1;
    $limit = 50;
    $offset = ($pageNum - 1) * $limit;

    $where = [];
    $params = [];
    $types = '';

    if (!empty($_GET['search'])) {
        $where[] = "title LIKE ?";
        $params[] = "%" . $_GET['search'] . "%";
        $types .= 's';
    }
    if (!empty($_GET['category'])) {
        $where[] = "category = ?";
        $params[] = $_GET['category'];
        $types .= 's';
    }

    $whereSQL = '';
    if (!empty($where)) {
        $whereSQL = 'WHERE ' . implode(' AND ', $where);
    }

    $countSQL = "SELECT COUNT(*) FROM courses $whereSQL";
    $stmt = $db->prepare($countSQL);
    if ($params) $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $total = $stmt->get_result()->fetch_row()[0];
    $totalPages = ceil($total / $limit);

    $sql = "SELECT * FROM courses $whereSQL ORDER BY sort_order, id LIMIT ? OFFSET ?";
    $types .= 'ii';
    $params[] = $limit;
    $params[] = $offset;
    $stmt = $db->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $courses = $stmt->get_result();
    ?>

    <div class="table-responsive">
        <table class="table table-striped table-hover">
            <thead class="table-dark">
                <tr>
                    <th>ID</th>
                    <th>Thumb</th>
                    <th>Title</th>
                    <th>Category</th>
                    <th>Lessons</th>
                    <th>Words</th>
                    <th>Premium</th>
                    <th>Price</th>
                    <th>Order</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if ($courses->num_rows > 0): ?>
                <?php while($row = $courses->fetch_assoc()): ?>
                <tr>
                    <td><?= $row['id'] ?></td>
                    <td>
                        <?php if (!empty($row['thumbnail'])): ?>
                            <img src="<?= htmlspecialchars($row['thumbnail']) ?>" style="height: 35px; width: 35px; object-fit: cover; border-radius: 4px;" alt="thumb">
                        <?php else: ?>
                            <span class="text-muted">–</span>
                        <?php endif; ?>
                    </td>
                    <td><?= htmlspecialchars($row['title']) ?></td>
                    <td><span class="badge bg-info"><?= $row['category'] ?></span></td>
                    <td><?= $row['total_lessons'] ?></td>
                    <td><?= $row['total_words'] ?></td>
                    <td><?= $row['is_premium'] ? '<span class="badge bg-warning text-dark">Yes</span>' : 'No' ?></td>
                    <td><?= number_format($row['price'], 2) ?> BDT</td>
                    <td><?= $row['sort_order'] ?></td>
                    <td>
                        <div class="btn-group btn-group-sm">
                            <a href="?page=lessons&course_id=<?= $row['id'] ?>" class="btn btn-outline-info" title="Lessons">
                                <i class="fa fa-list"></i>
                            </a>
                            <a href="?page=courses&action=update&id=<?= $row['id'] ?>" class="btn btn-outline-warning" title="Edit">
                                <i class="fa fa-edit"></i>
                            </a>
                            <a href="?page=courses&action=delete&id=<?= $row['id'] ?>"
                               class="btn btn-outline-danger" title="Delete"
                               onclick="return confirm('Delete this course? This will also remove all linked lessons, flashcards, and exam questions.')">
                                <i class="fa fa-trash"></i>
                            </a>
                        </div>
                    </td>
                </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="10" class="text-center">No courses found.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if ($totalPages > 1): ?>
    <nav>
        <ul class="pagination">
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <li class="page-item <?= $i == $pageNum ? 'active' : '' ?>">
                    <a class="page-link" href="?page=courses&p=<?= $i ?>&search=<?= urlencode($_GET['search'] ?? '') ?>&category=<?= urlencode($_GET['category'] ?? '') ?>">
                        <?= $i ?>
                    </a>
                </li>
            <?php endfor; ?>
        </ul>
    </nav>
    <?php endif; ?>

<?php
// ---------- CREATE / UPDATE form ----------
else:
?>
    <h3><?= $action === 'create' ? 'Create New Course' : 'Edit Course' ?></h3>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <ul class="mb-0">
                <?php foreach ($errors as $err): ?>
                    <li><?= htmlspecialchars($err) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <form method="post" enctype="multipart/form-data" class="card p-4" style="max-width: 600px;">
        <div class="mb-3">
            <label for="title" class="form-label">Title *</label>
            <input type="text" name="title" id="title" class="form-control"
                   value="<?= htmlspecialchars($course['title'] ?? ($_POST['title'] ?? '')) ?>" required>
        </div>

        <div class="mb-3">
            <label for="description" class="form-label">Description</label>
            <textarea name="description" id="description" class="form-control" rows="3"><?= htmlspecialchars($course['description'] ?? ($_POST['description'] ?? '')) ?></textarea>
        </div>

        <div class="mb-3">
            <label for="category" class="form-label">Category *</label>
            <select name="category" id="category" class="form-select">
                <option value="IBA" <?= ($course['category'] ?? $_POST['category'] ?? '') === 'IBA' ? 'selected' : '' ?>>IBA</option>
                <option value="BCS" <?= ($course['category'] ?? $_POST['category'] ?? '') === 'BCS' ? 'selected' : '' ?>>BCS</option>
                <option value="IELTS" <?= ($course['category'] ?? $_POST['category'] ?? '') === 'IELTS' ? 'selected' : '' ?>>IELTS</option>
                <option value="Admission" <?= ($course['category'] ?? $_POST['category'] ?? '') === 'Admission' ? 'selected' : '' ?>>Admission</option>
            </select>
        </div>

        <div class="mb-3 form-check">
            <input type="checkbox" name="is_premium" id="is_premium" class="form-check-input"
                   <?= ($course['is_premium'] ?? $_POST['is_premium'] ?? 0) ? 'checked' : '' ?>>
            <label for="is_premium" class="form-check-label">Premium course</label>
        </div>

        <div class="mb-3">
            <label for="price" class="form-label">Price (BDT)</label>
            <input type="number" step="0.01" min="0" name="price" id="price" class="form-control"
                   value="<?= $course['price'] ?? $_POST['price'] ?? '0.00' ?>">
        </div>

        <div class="mb-3">
            <label for="sort_order" class="form-label">Sort Order</label>
            <input type="number" min="0" name="sort_order" id="sort_order" class="form-control"
                   value="<?= $course['sort_order'] ?? $_POST['sort_order'] ?? '0' ?>">
        </div>

        <!-- Thumbnail upload field -->
        <div class="mb-3">
            <label for="thumbnail_file" class="form-label">Thumbnail Image</label>
            <?php if (!empty($course['thumbnail'])): ?>
                <div class="mb-2">
                    <img src="<?= htmlspecialchars($course['thumbnail']) ?>" style="max-height: 120px;" alt="Current thumbnail"><br>
                    <small class="text-muted">Current thumbnail</small>
                </div>
            <?php endif; ?>
            <input type="file" name="thumbnail_file" id="thumbnail_file" class="form-control" accept="image/*">
            <small class="text-muted">Upload a new thumbnail (JPEG, PNG, GIF, WebP, max 2MB). Leave empty to keep the current one.</small>
            <input type="hidden" name="existing_thumbnail" value="<?= htmlspecialchars($course['thumbnail'] ?? '') ?>">
        </div>

        <div class="d-flex gap-2">
            <button type="submit" class="btn btn-success">
                <i class="fa fa-save me-1"></i> Save
            </button>
            <a href="?page=courses" class="btn btn-secondary">Cancel</a>
        </div>
    </form>
<?php endif; ?>