<?php
require_once 'config.php';

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

try {
    $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
    $perPage = isset($_GET['per_page']) ? max(1, (int)$_GET['per_page']) : 5;
    $offset = ($page - 1) * $perPage;
    
    // Get reviews
    $stmt = $pdo->prepare("SELECT * FROM reviews WHERE status = 'approved' ORDER BY created_at DESC LIMIT :limit OFFSET :offset");
    $stmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $reviews = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Check if there are more reviews
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM reviews WHERE status = 'approved'");
    $stmt->execute();
    $totalReviews = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    $hasMore = ($page * $perPage) < $totalReviews;
    
    echo json_encode([
        'success' => true,
        'reviews' => $reviews,
        'has_more' => $hasMore,
        'total' => $totalReviews
    ]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>