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

if (!isset($_GET['url']) || !filter_var($_GET['url'], FILTER_VALIDATE_URL)) {
    echo json_encode(['error' => 'آدرس صفحه معتبر نیست یا وارد نشده است.']);
    exit;
}

$url = $_GET['url'];

$headers = [
    'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
    'accept-language: fa-IR,fa;q=0.9,en-GB;q=0.8,en;q=0.7,en-US;q=0.6',
    'cache-control: no-cache',
    'pragma: no-cache',
    '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'
];

$cookieFile = __DIR__ . '/cookies.txt';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$html = curl_exec($ch);

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

if (!$html) {
    echo json_encode(['error' => 'دریافت صفحه ناموفق بود']);
    exit;
}

// استخراج JSON اصلی
$productData = null;
if (preg_match('#<script id="__NEXT_DATA__" type="application/json">\s*(\{.*?\})\s*</script>#s', $html, $matches)) {
    $jsonText = $matches[1];
    $data = json_decode($jsonText, true);
    if ($data && isset($data['props']['pageProps']['product'])) {
        $productData = $data['props']['pageProps']['product'];
    }
}

// عنوان
$title = $productData['title'] ?? '';
// قیمت
$price = $productData['price'] ?? '';
// توضیحات
$description = $productData['description'] ?? '';

// breadcrumb
$breadcrumbText = null;
if (preg_match('#<div class="bs-breadcrumbs">(.*?)</div>#s', $html, $breadcrumbMatch)) {
    $breadcrumbHtml = $breadcrumbMatch[1];
    if (preg_match_all('#<a class="bs-breadcrumbs__item"[^>]*>(.*?)</a>#s', $breadcrumbHtml, $links)) {
        $breadcrumbItems = array_map('strip_tags', $links[1]);
        $breadcrumbText = implode(' > ', array_map('trim', $breadcrumbItems));
    }
}

// تصاویر از JSON و preload
$images = [];
if (!empty($productData['gallery'])) {
    foreach ($productData['gallery'] as $img) {
        if (isset($img['url'])) $images[] = $img['url'];
    }
}
if (empty($images) && !empty($productData['photos'])) {
    foreach ($productData['photos'] as $img) {
        if (isset($img['url'])) $images[] = $img['url'];
    }
}
if (empty($images) && !empty($productData['image']['url'])) {
    $images[] = $productData['image']['url'];
}
if (empty($images) && preg_match_all('/<link[^>]+rel=["\']preload["\'][^>]+as=["\']image["\'][^>]+href=["\']([^"\']+)["\']/', $html, $matches)) {
    $images = $matches[1];
}

$output = [
    'title' => $title,
    'description' => $description,
    'price' => $price,
    'breadcrumb' => $breadcrumbText,
    'images' => $images
];

echo json_encode($output, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);