<?php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../classes/Course.php';

$allowedRegions = array_merge(['global'], is_string(SUPPORTED_REGIONS) ? unserialize(SUPPORTED_REGIONS) : ['usa','europe','africa']);

$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = max(1, min(100, (int)($_GET['per_page'] ?? 12)));
$offset = ($page - 1) * $perPage;

$filters = [];
// Region: prefer explicit param then session
if (!empty($_GET['region']) && in_array(strtolower($_GET['region']), $allowedRegions, true)) {
    $filters['region'] = strtolower($_GET['region']);
    $_SESSION['region'] = $filters['region'];
} elseif (!empty($_SESSION['region'])) {
    $filters['region'] = $_SESSION['region'];
}

if (!empty($_GET['search'])) $filters['search'] = trim($_GET['search']);
if (!empty($_GET['category_id'])) $filters['category_id'] = (int)$_GET['category_id'];
if (!empty($_GET['level'])) $filters['level'] = trim($_GET['level']);
if (!empty($_GET['sort'])) $filters['sort'] = trim($_GET['sort']);
if (isset($_GET['free_only']) && $_GET['free_only']) $filters['free_only'] = true;

$courseModel = new Course();
$total = $courseModel->countCourses($filters);
$courses = $courseModel->getCourses($filters, $perPage, $offset);

$itemsHtml = '';
foreach ($courses as $c) {
    // generate safe category slug (preserve letters and numbers)
    $categorySlug = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '', $c['category_name'] ?? ''));

    $priceLabel = ($c['price'] > 0) ? ('$' . number_format($c['price'], 2)) : 'Free';

    // Thumbnail resolution and file existence check
    $thumb = $c['thumbnail'] ?? '';
    $thumbLocal = $thumb ? __DIR__ . '/../../' . ltrim($thumb, '/') : '';
    $baseUrl = defined('APP_URL') ? rtrim(APP_URL, '/') : '';
    if ($thumb && file_exists($thumbLocal)) {
        $thumbSrc = (stripos($thumb, 'http') === 0) ? $thumb : $baseUrl . '/' . ltrim($thumb, '/');
    } else {
        $thumbSrc = $baseUrl . '/assets/images/course-placeholder.jpg';
    }

    $itemsHtml .= '<div class="col-lg-4 col-md-6">';
    $itemsHtml .= '<div class="course-card" data-category="' . htmlspecialchars($categorySlug) . '" data-level="' . htmlspecialchars($c['level'] ?? '') . '" data-duration="' . htmlspecialchars($c['duration'] ?? 'medium') . '" data-price="' . (($c['price'] > 0) ? 'paid' : 'free') . '">';
    $itemsHtml .= '<div class="course-image"><img src="' . htmlspecialchars($thumbSrc) . '" alt="' . htmlspecialchars($c['title']) . '" class="img-fluid"></div>';
    $itemsHtml .= '<div class="course-content">';
    $itemsHtml .= '<div class="course-meta"><span class="course-category">' . htmlspecialchars($c['category_name']) . '</span><span class="course-level">' . htmlspecialchars(ucfirst($c['level'] ?? '')) . '</span></div>';
    $itemsHtml .= '<h3 class="course-title">' . htmlspecialchars($c['title']) . '</h3>';
    $itemsHtml .= '<p class="course-description">' . htmlspecialchars($c['short_description'] ?? substr($c['description'] ?? '', 0, 120)) . '</p>';
    $itemsHtml .= '<div class="course-info"><div class="info-item"><i class="fas fa-clock"></i><span>' . htmlspecialchars($c['duration'] ?? '—') . '</span></div><div class="info-item"><i class="fas fa-users"></i><span>' . (int)($c['enrollment_count'] ?? 0) . ' students</span></div></div>';
    $itemsHtml .= '<div class="course-price"><span class="price-current">' . $priceLabel . '</span></div>';
    $itemsHtml .= '<a href="' . APP_URL . '/website/course.php?course_id=' . (int)$c['id'] . '" class="btn btn-primary w-100">View Course</a>';
    $itemsHtml .= '</div></div></div>';
}

$response = [
    'success' => true,
    'html' => $itemsHtml,
    'page' => $page,
    'per_page' => $perPage,
    'total' => $total,
    'total_pages' => (int)ceil($total / $perPage),
    'count_returned' => count($courses)
];

echo json_encode($response);
exit;
