<?php
require_once '../../includes/functions.php';
setCORSHeaders();

// Verify API Hash
verifyAPIHash();

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    sendError('Method not allowed', 405);
}

// Get query parameters
$category = $_GET['category'] ?? '';
$limit = (int)($_GET['limit'] ?? 20);
$offset = (int)($_GET['offset'] ?? 0);

// Build query
$query = "SELECT id, name, description, price_coins, min_order, image_url, category, coin_type, created_at FROM products WHERE is_active = 1";
$params = [];

if (!empty($category)) {
    $query .= " AND category = ?";
    $params[] = $category;
}

$query .= " ORDER BY created_at DESC LIMIT " . (int)$limit . " OFFSET " . (int)$offset;

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Test: Check if we can get any products at all (without is_active filter)
$testQuery = "SELECT COUNT(*) FROM products";
$testStmt = $pdo->prepare($testQuery);
$testStmt->execute();
$totalProducts = $testStmt->fetchColumn();
error_log("Total products in database (including inactive): " . $totalProducts);

// Debug: Log the query and results
error_log("Products Query: " . $query);
error_log("Products Count: " . count($products));
error_log("Products Data: " . json_encode($products));

// Get total count
$countQuery = "SELECT COUNT(*) FROM products WHERE is_active = 1";
if (!empty($category)) {
    $countQuery .= " AND category = ?";
    $countStmt = $pdo->prepare($countQuery);
    $countStmt->execute([$category]);
} else {
    $countStmt = $pdo->prepare($countQuery);
    $countStmt->execute();
}
$totalCount = $countStmt->fetchColumn();
error_log("Total Count: " . $totalCount);

// Create the response data
$responseData = [
    'products' => $products,
    'pagination' => [
        'total' => $totalCount,
        'limit' => $limit,
        'offset' => $offset,
        'has_more' => ($offset + $limit) < $totalCount
    ]
];

// Send response with proper format
$response = [
    'success' => true,
    'message' => 'Products retrieved successfully',
    'data' => $responseData
];

error_log("Final Response: " . json_encode($response));
sendResponse($response);
?>
