<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/currency.php';
require_once '../../includes/functions.php';

// Set JSON response header
header('Content-Type: application/json');

$db = getDB();
$method = $_SERVER['REQUEST_METHOD'];

try {
    // Only allow GET requests
    if ($method !== 'GET') {
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        exit;
    }

    // Get filter parameters
    $category = $_GET['category'] ?? '';
    $exam_type = $_GET['exam_type'] ?? '';
    $search = $_GET['search'] ?? '';
    $sort = $_GET['sort'] ?? 'newest';
    $page = max(1, intval($_GET['page'] ?? 1));
    $perPage = intval($_GET['per_page'] ?? 12);

    // Build query
    $query = "SELECT DISTINCT e.id, e.title, e.slug, e.description, e.price, e.currency, e.is_free,
                     e.exam_type, e.total_points, e.passing_score, e.time_limit, e.max_attempts,
                     e.status, e.created_at, e.updated_at,
                     e.instructor_id, e.course_id,
                     c.title as course_title,
                     u.username as instructor_name, up.first_name, up.last_name,
                     COALESCE(stats.attempt_count, 0) as attempt_count,
                     AVG(er.rating) as average_rating,
                     COUNT(DISTINCT er.id) as review_count
              FROM exams e
              LEFT JOIN courses c ON e.course_id = c.id
              LEFT JOIN users u ON e.instructor_id = u.id
              LEFT JOIN user_profiles up ON u.id = up.user_id
              LEFT JOIN (
                  SELECT e2.id as exam_id,
                         COUNT(DISTINCT ea.student_id) as attempt_count
                  FROM exams e2
                  LEFT JOIN exam_attempts ea ON e2.id = ea.exam_id
                  GROUP BY e2.id
              ) stats ON e.id = stats.exam_id
              LEFT JOIN exam_reviews er ON e.id = er.exam_id AND er.status = 'approved'
              WHERE e.status = 'published'
              AND (e.start_date IS NULL OR e.start_date <= NOW())
              AND (e.end_date IS NULL OR e.end_date >= NOW())
              GROUP BY e.id";

    $params = [];

    // Get total count for pagination
    $countQuery = "SELECT COUNT(DISTINCT e.id) as total
                   FROM exams e
                   LEFT JOIN courses c ON e.course_id = c.id
                   WHERE e.status = 'published'
                   AND (e.start_date IS NULL OR e.start_date <= NOW())
                   AND (e.end_date IS NULL OR e.end_date >= NOW())";

    // Add filters
    if (!empty($exam_type)) {
        $query .= " AND e.exam_type = ?";
        $countQuery .= " AND e.exam_type = ?";
        $params[] = $exam_type;
    }

    if (!empty($search)) {
        $query .= " AND (e.title LIKE ? OR e.description LIKE ? OR c.title LIKE ?)";
        $countQuery .= " AND (e.title LIKE ? OR e.description LIKE ? OR c.title LIKE ?)";
        $searchTerm = "%$search%";
        $params[] = $searchTerm;
        $params[] = $searchTerm;
        $params[] = $searchTerm;
    }

    // Add sorting
    switch ($sort) {
        case 'oldest':
            $query .= " ORDER BY e.created_at ASC";
            break;
        case 'popular':
            $query .= " ORDER BY attempt_count DESC";
            break;
        case 'price_low':
            $query .= " ORDER BY e.price ASC";
            break;
        case 'price_high':
            $query .= " ORDER BY e.price DESC";
            break;
        default: // newest
            $query .= " ORDER BY e.created_at DESC";
            break;
    }

    // Add the same filters to count query
    $countParams = $params;

    $stmt = $db->prepare($countQuery);
    $stmt->execute($countParams);
    $totalExams = $stmt->fetch()['total'];
    $totalPages = ceil($totalExams / $perPage);

    // Add pagination
    $offset = ($page - 1) * $perPage;
    $query .= " LIMIT $perPage OFFSET $offset";

    // Execute main query
    $stmt = $db->prepare($query);
    $stmt->execute($params);
    $exams = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Get user exam attempts for logged-in users
    $userAttempts = [];
    $userExamAccess = [];
    if (isLoggedIn()) {
        $userId = $_SESSION['user_id'];
        
        // Get user's exam attempts
        $stmt = $db->prepare("SELECT exam_id, status, score FROM exam_attempts WHERE student_id = ?");
        $stmt->execute([$userId]);
        $attempts = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($attempts as $attempt) {
            $userAttempts[$attempt['exam_id']] = $attempt;
        }
        
        // Get user's exam access (purchased or enrolled)
        $stmt = $db->prepare("SELECT exam_id FROM exam_access WHERE student_id = ?");
        $stmt->execute([$userId]);
        $accessRecords = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($accessRecords as $record) {
            $userExamAccess[$record['exam_id']] = true;
        }
        
        // Also check course enrollments for exams linked to courses
        $stmt = $db->prepare("
            SELECT DISTINCT e.id 
            FROM exams e
            JOIN courses c ON e.course_id = c.id
            JOIN course_enrollments ce ON c.id = ce.course_id
            WHERE ce.student_id = ?
        ");
        $stmt->execute([$userId]);
        $enrolledExams = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($enrolledExams as $exam) {
            $userExamAccess[$exam['id']] = true;
        }
    }

    // Process exams to add user-specific data
    foreach ($exams as &$exam) {
        $examId = $exam['id'];
        $exam['user_has_access'] = isset($userExamAccess[$examId]);
        $exam['user_attempt'] = isset($userAttempts[$examId]) ? $userAttempts[$examId] : null;
        
        // Format price
        if ($exam['is_free']) {
            $exam['formatted_price'] = 'Free';
        } else {
            $exam['formatted_price'] = formatCurrency($exam['price'], $exam['currency']);
        }
        
        // Truncate description
        if ($exam['description']) {
            $exam['description_short'] = substr($exam['description'], 0, 120) . '...';
        } else {
            $exam['description_short'] = 'Test your knowledge with this exam';
        }
    }

    echo json_encode([
        'success' => true,
        'data' => $exams,
        'meta' => [
            'total' => intval($totalExams),
            'per_page' => $perPage,
            'current_page' => $page,
            'total_pages' => $totalPages,
            'has_more' => $page < $totalPages
        ]
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
