<?php
error_reporting(0);
header('Content-Type: application/json; charset=utf-8');

if (!isset($_GET['name']) || empty($_GET['name'])) {
    echo json_encode(['error' => 'نام غرفه وارد نشده است.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$name = $_GET["name"];
$limit = 20; // تعداد محصولات در هر درخواست
$page = 1;
$allProducts = [];

$headers = [
    'accept: application/json, text/plain, */*',
    'accept-language: fa-IR,fa;q=0.9,en-GB;q=0.8,en;q=0.7,en-US;q=0.6',
    'origin: https://basalam.com',
    'pragma: no-cache',
    'referer: https://basalam.com/',
    'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36',
    'x-client-info: {"version":"2.11.1","project":"charsou","name":"web.public","platform":"web"}'
];

do {
    $from = ($page - 1) * $limit;
    $url = "https://search.basalam.com/ai-engine/api/v2.0/product/search?from={$from}&size={$limit}&q=&dynamicFacets=true&f.vendorIdentifier={$name}&enableNavigations=true&filters.vendorIdentifier={$name}&adsImpressionDisable=false";

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_ENCODING => '',
    ]);

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        echo json_encode(['error' => curl_error($ch)], JSON_UNESCAPED_UNICODE);
        curl_close($ch);
        exit;
    }

    curl_close($ch);
    $json = json_decode($response, true);

    $products = $json['products'] ?? ($json['data']['products'] ?? []);

    foreach ($products as $product) {
        $allProducts[] = [
            'name' => $product['name'] ?? 'N/A',
            'id' => $product['id'] ?? 'N/A',
            'photo_medium' => $product['photo']['MEDIUM'] ?? 'N/A',
            'status' => $product['status']['title'] ?? 'N/A',
            'vendor_name' => $product['vendor']['name'] ?? 'N/A',
            'price' => $product['price'] ?? 'N/A',
            'vendor_city' => $product['vendor']['owner']['city'] ?? 'N/A'
        ];
    }

    $page++;
} while (count($products) == $limit); // ادامه تا زمانی که تعداد محصولات کمتر از limit نشه

echo json_encode([
    'vendor' => $name,
    'count' => count($allProducts),
    'products' => $allProducts
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);