<?php
// api.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *'); // Allow requests from Shopify theme

require __DIR__ . '/db.php';

// Inputs
$collection_handle = $_GET['collection'] ?? '';
$categories = $_GET['categories'] ?? [];
$brands = $_GET['brands'] ?? [];
$price_min = isset($_GET['price_min']) ? (float)$_GET['price_min'] : null;
$price_max = isset($_GET['price_max']) ? (float)$_GET['price_max'] : null;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$limit = 24;
$offset = ($page - 1) * $limit;

if (empty($collection_handle)) {
    echo json_encode(['error' => 'Missing collection handle']);
    exit;
}

try {
    // Start building query
    $query = "SELECT DISTINCT p.id, p.handle FROM products p ";
    $joins = [];
    $where = ["p.status = 'active'"];
    $params = [];

    // Base collection join
    $joins[] = "JOIN product_collections pc_base ON pc_base.product_id = p.id";
    $joins[] = "JOIN collections c_base ON c_base.id = pc_base.collection_id";
    $where[] = "c_base.handle = ?";
    $params[] = $collection_handle;

    // Categories (sub-collections)
    if (!empty($categories) && is_array($categories)) {
        $category_placeholders = implode(',', array_fill(0, count($categories), '?'));
        // Must belong to AT LEAST ONE of the selected categories
        $joins[] = "JOIN product_collections pc_cat ON pc_cat.product_id = p.id";
        $joins[] = "JOIN collections c_cat ON c_cat.id = pc_cat.collection_id";
        $where[] = "c_cat.handle IN ($category_placeholders)";
        $params = array_merge($params, $categories);
    }

    // Brands
    if (!empty($brands) && is_array($brands)) {
        $brand_placeholders = implode(',', array_fill(0, count($brands), '?'));
        $where[] = "p.vendor IN ($brand_placeholders)";
        $params = array_merge($params, $brands);
    }

    // Price
    if ($price_min !== null) {
        $where[] = "p.min_price >= ?";
        $params[] = $price_min;
    }
    if ($price_max !== null) {
        $where[] = "p.min_price <= ?";
        $params[] = $price_max;
    }

    $sql = $query . " " . implode(" ", $joins) . " WHERE " . implode(" AND ", $where);
    
    // Count total query
    $count_sql = "SELECT COUNT(DISTINCT p.id) as total FROM products p " . implode(" ", $joins) . " WHERE " . implode(" AND ", $where);
    $total_result = db_fetch_one($pdo, $count_sql, $params);
    $total_count = $total_result['total'] ?? 0;

    // Add pagination and sorting
    // Sort logic can be added here if needed (e.g., ORDER BY p.min_price ASC)
    $sql .= " ORDER BY p.id DESC LIMIT $limit OFFSET $offset";
    
    $results = db_fetch_all($pdo, $sql, $params);

    $product_ids = [];
    $product_handles = [];
    foreach ($results as $row) {
        $product_ids[] = $row['id'];
        $product_handles[] = $row['handle'];
    }

    // Get max price of active products in collection
    $max_price_sql = "SELECT MAX(p.min_price) as max_price FROM products p JOIN product_collections pc ON pc.product_id = p.id JOIN collections c ON c.id = pc.collection_id WHERE c.handle = ? AND p.status = 'active'";
    $max_price_result = db_fetch_one($pdo, $max_price_sql, [$collection_handle]);
    $collection_max_price = $max_price_result['max_price'] ? ceil($max_price_result['max_price']) : 9999;

    echo json_encode([
        'product_ids' => $product_ids,
        'product_handles' => $product_handles,
        'max_price' => $collection_max_price,
        'pagination' => [
            'page' => $page,
            'pages' => ceil($total_count / $limit),
            'total' => $total_count
        ]
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
