<?php
error_reporting(0);
ini_set('display_errors', 0);
set_time_limit(0);

// ================= تنظیمات اولیه =================
$telegram_token = "8785401295:AAFpZ_e0EkJULMv9BmMcJD3bBSvv1tZ4vKE"; 
$chat_id = "812870519"; 
$admin_email = "weborsy@gmail.com"; 

$categories = [
    ['name' => 'سازهای بادی (عمومی)', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/', 'file' => __DIR__ . '/data_wind_instruments.json'],
    ['name' => 'ابوا', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/oboe/', 'file' => __DIR__ . '/data_oboe.json'],
    ['name' => 'افکت بادی', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/wind-effect/', 'file' => __DIR__ . '/data_wind_effect.json'],
    ['name' => 'ترومپت', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/trumpet/', 'file' => __DIR__ . '/data_trumpet.json'],
    ['name' => 'ترومبون', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/trombone/', 'file' => __DIR__ . '/data_trombone.json'],
    ['name' => 'دیجریدو', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/didgeridoo/', 'file' => __DIR__ . '/data_didgeridoo.json'],
    ['name' => 'سوزافون', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/sousaphone/', 'file' => __DIR__ . '/data_sousaphone.json'],
    ['name' => 'ترومپت بادی', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/trumpet-wind-instruments/', 'file' => __DIR__ . '/data_trumpet_wind.json'],
    ['name' => 'فلوت', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/flute/', 'file' => __DIR__ . '/data_flute.json'],
    ['name' => 'فلوگل هورن', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/flugelhorns/', 'file' => __DIR__ . '/data_flugelhorns.json'],
    ['name' => 'کرنت', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/cornet/', 'file' => __DIR__ . '/data_cornet.json'],
    ['name' => 'کلارینت', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/clarinet/', 'file' => __DIR__ . '/data_clarinet.json'],
    ['name' => 'کیف و هاردکیس', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/wind-casebag/', 'file' => __DIR__ . '/data_wind_casebag.json'],
    ['name' => 'لوازم نگهداری و نظافت', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/cleaningcare/', 'file' => __DIR__ . '/data_cleaningcare.json'],
    ['name' => 'متعلقات سازهای بادی', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/wind-accessories/', 'file' => __DIR__ . '/data_wind_accessories.json'],
    ['name' => 'ساکسوفون آلتو', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/saxophones/saxophones-alto/', 'file' => __DIR__ . '/data_saxophones_alto.json'],
    ['name' => 'آلتو هورن', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/horn/alto-horn/', 'file' => __DIR__ . '/data_alto_horn.json'],
    ['name' => 'فلوت ریکوردر', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/flute/flute-recorder/', 'file' => __DIR__ . '/data_flute_recorder.json'],
    ['name' => 'فلوت کلیددار', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/flute/flute-ring-keys/', 'file' => __DIR__ . '/data_flute_ring_keys.json'],
    ['name' => 'سازدهنی ترمولو', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/harmonica/harmonica-tremolo/', 'file' => __DIR__ . '/data_harmonica_tremolo.json'],
    ['name' => 'سازدهنی دیاتونیک', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/harmonica/harmonica-diatonic/', 'file' => __DIR__ . '/data_harmonica_diatonic.json'],
    ['name' => 'باریتون هورن', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/horn/horn-baritone/', 'file' => __DIR__ . '/data_horn_baritone.json'],
    ['name' => 'فرنچ هورن', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/horn/french-horn/', 'file' => __DIR__ . '/data_french_horn.json'],
    ['name' => 'ساکسوفون باریتون', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/saxophones/saxophones-baritone/', 'file' => __DIR__ . '/data_saxophones_baritone.json'],
    ['name' => 'ساکسوفون تنور', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/saxophones/saxophones-tenor/', 'file' => __DIR__ . '/data_saxophones_tenor.json'],
    ['name' => 'ساکسوفون سوپرانو', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/saxophones/saxophones-soprano/', 'file' => __DIR__ . '/data_saxophones_soprano.json'],
    ['name' => 'سوردین ساکسوفون', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/saxophones/saxophone-mute/', 'file' => __DIR__ . '/data_saxophone_mute.json'],
    ['name' => 'سوردین پرکاشن/بادی', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/wind-accessories/percussion-surdine/', 'file' => __DIR__ . '/data_percussion_surdine.json'],
    ['name' => 'اکارینا', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/wind-effect/ocarina/', 'file' => __DIR__ . '/data_ocarina.json'],
    ['name' => 'سازدهنی ارکسترال', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/harmonica/orchestral-harmonica/', 'file' => __DIR__ . '/data_orchestral_harmonica.json'],
    ['name' => 'سازدهنی کروماتیک', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/harmonica/harmonica-chromatic/', 'file' => __DIR__ . '/data_harmonica_chromatic.json'],
    ['name' => 'توبا', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/tuba/', 'file' => __DIR__ . '/data_tuba.json'],
    ['name' => 'یوفونیوم', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/euphonium/', 'file' => __DIR__ . '/data_euphonium.json'],
    ['name' => 'لوازم جانبی ساکسوفون', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/saxophones/saxophone-accessories/', 'file' => __DIR__ . '/data_saxophone_accessories.json'],
    ['name' => 'ترمبون', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/%d8%aa%d8%b1%d9%85%d8%a8%d9%88%d9%86/', 'file' => __DIR__ . '/data_trombone_fa.json'],
    ['name' => 'سازدهنی تزئینی', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/harmonica/%d8%b3%d8%a7%d8%b2%d8%af%d9%87%d9%86%db%8c-%d8%aa%d8%b2%d8%a6%db%8c%d9%86%db%8c/', 'file' => __DIR__ . '/data_harmonica_mini_fa.json'],
    ['name' => 'ساکسوفون دیجیتال', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/saxophones/%d8%b3%d8%a7%da%a9%d8%b3%d9%88%d9%81%d9%88%d9%86-%d8%af%db%8c%d8%ac%db%8c%d8%aa%d8%a7%d9%84/', 'file' => __DIR__ . '/data_sax_digital.json'],
    ['name' => 'قمیش بر', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/wind-accessories/%d9%82%d9%85%db%8c%d8%b4-%d8%a8%d8%b1-wind-accessories/', 'file' => __DIR__ . '/data_reed_trimmer.json'],
    ['name' => 'متعلقات سازدهنی', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/wind-accessories/%d9%85%d8%aa%d8%b9%d9%84%d9%82%d8%a7%d8%aa-%d8%b3%d8%a7%d8%b2%d8%af%d9%87%d9%86%db%8c-wind-accessories/', 'file' => __DIR__ . '/data_harmonica_acc_fa.json'],
    ['name' => 'لوازم جانبی سازدهنی', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/wind-accessories/%d9%84%d9%88%d8%a7%d8%b2%d9%85-%d8%ac%d8%a7%d9%86%d8%a8%db%8c-%d8%b3%d8%a7%d8%b2%d8%af%d9%87%d9%86%db%8c-wind-accessories/', 'file' => __DIR__ . '/data_harmonica_acc2_fa.json'],
    ['name' => 'قمیش', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/wind-accessories/%d9%82%d9%85%db%8c%d8%b4/', 'file' => __DIR__ . '/data_reed.json'],
    ['name' => 'لوازم جانبی سازدهنی (اصلی)', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/wind-instruments/harmonica/harmonica-accessories/', 'file' => __DIR__ . '/data_harmonica_accessories.json'],
    ['name' => 'ملودیکا', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/clavier-instruments/melodica/', 'file' => __DIR__ . '/data_melodica.json'],
    ['name' => 'پایه سازهای بادی', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/stand/?filters=instrument%5B%25d9%25be%25d8%25a7%25db%258c%25d9%2587-%25d8%25b3%25d8%25a7%25d8%25b2%25d9%2587%25d8%25a7%25db%258c-%25d8%25a8%25d8%25a7%25d8%25af%25db%258c%5D', 'file' => __DIR__ . '/data_stand_wind.json'],
    ['name' => 'پایه نت (پوپیتر)', 'url' => 'https://www.sornashop.com/product-category/musical-instruments/stand/?filters=instrument%5B%25d9%25be%25d9%2588%25d9%25be%25db%258c%25d8%25aa%25d8%25b1%5D', 'file' => __DIR__ . '/data_pupitre.json']
];

// ================= توابع اصلی =================
function send_to_telegram($token, $chat_id, $text, $image_url = null, $product_url = null) {
    $tg_api = "https://telegramproxy.pooyamhmd.workers.dev/bot{$token}/";
    
    if ($image_url && $product_url) {
        $url = $tg_api . "sendPhoto";
        $keyboard = ['inline_keyboard' => [[['text' => '🛒 مشاهده در سایت', 'url' => $product_url]]]] ;
        $post_fields = [
            'chat_id' => $chat_id,
            'photo' => $image_url,
            'caption' => $text,
            'parse_mode' => 'HTML',
            'reply_markup' => json_encode($keyboard)
        ];
    } else {
        $url = $tg_api . "sendMessage";
        $post_fields = ['chat_id' => $chat_id, 'text' => $text, 'parse_mode' => 'HTML'];
    }

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_exec($ch);
    curl_close($ch);
}

function get_html($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $html = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if($http_code == 404) return false;
    return $html;
}

// ================= فایل‌های ذخیره وضعیت و حافظه =================
$state_file = __DIR__ . '/bot_state.txt';
$email_log_file = __DIR__ . '/bot_email_log.txt';
$changes_flag_file = __DIR__ . '/bot_changes_flag.txt';

$current_index = file_exists($state_file) ? (int)file_get_contents($state_file) : 0;

if ($current_index >= count($categories)) {
    $any_changes = file_exists($changes_flag_file) ? (int)file_get_contents($changes_flag_file) : 0;
    
    if ($any_changes === 1) {
        $email_subject = "گزارش تغییرات محصولات فروشگاه (" . date('Y-m-d H:i') . ")";
        $email_body = "گزارش جامع تغییرات قیمت و موجودی در این دور از بررسی:\n\n";
        $email_body .= file_exists($email_log_file) ? file_get_contents($email_log_file) : "";
        
        $headers = "From: monitor@mo.demoz.ir\r\n";
        $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
        @mail($admin_email, $email_subject, $email_body, $headers);
    }
    
    @unlink($email_log_file);
    @unlink($changes_flag_file);
    file_put_contents($state_file, "0");
    
    echo "<div style='font-family:tahoma; direction:rtl; margin:40px; text-align:center;'>";
    echo "<h2 style='color:green;'>🎉 بررسی تمام ۴۵ دسته با موفقیت به پایان رسید!</h2>";
    echo "<h3>سیستم برای شروع دور بعدی آماده است.</h3></div>";
    exit;
}

// ================= بررسی دسته فعلی با اصلاح لینک‌های فیلتردار =================
$cat = $categories[$current_index];
$base_url = $cat['url'];
$category_name = $cat['name'];
$data_file = $cat['file'];

$current_data = [];
$total_count = 0;
$in_stock_count = 0;
$out_of_stock_count = 0;

// استخراج بخش‌های لینک برای مدیریت درست صفحه‌بندی
$url_parts = parse_url($base_url);
$clean_url = $url_parts['scheme'] . "://" . $url_parts['host'] . $url_parts['path'];
$query_string = isset($url_parts['query']) ? "?" . $url_parts['query'] : "";

for ($page = 1; $page <= 100; $page++) {
    // ساخت اصولی لینک صفحات
    if ($page == 1) {
        $url = $base_url;
    } else {
        $url = rtrim($clean_url, '/') . "/page/{$page}/" . $query_string;
    }
    
    $html = get_html($url);
    if(!$html || strpos($html, 'هیچ محصولی یافت نشد') !== false) {
        break; 
    }

    $dom = new DOMDocument();
    @$dom->loadHTML('<?xml encoding="UTF-8">' . $html);
    $xpath = new DOMXPath($dom);
    $products = $xpath->query("//div[contains(@class, 'product-grid-item')]");
    
    if ($products->length == 0) break;

    foreach ($products as $product) {
        $total_count++;
        $title_node = $xpath->query(".//h3[contains(@class, 'wd-entities-title')]/a", $product)->item(0);
        $title = $title_node ? trim($title_node->nodeValue) : "محصول ناشناس";
        $product_link = $title_node ? $title_node->getAttribute('href') : "";
        
        $img_node = $xpath->query(".//div[contains(@class, 'product-element-top')]//img", $product)->item(0);
        $image_src = $img_node ? $img_node->getAttribute('src') : "";
        
        $sku_node = $xpath->query(".//*[contains(@class, 'product-meta')]", $product)->item(0);
        $sku = $sku_node ? trim(str_replace('Code :', '', strip_tags($sku_node->nodeValue))) : "نامشخص";
        
        $price_node = $xpath->query(".//span[contains(@class, 'price')]", $product)->item(0);
        $price = $price_node ? preg_replace('/\s+/', ' ', trim(strip_tags($price_node->nodeValue))) : "نامشخص";
        
        $class_attribute = $product->getAttribute('class');
        if (strpos($class_attribute, 'outofstock') !== false) {
            $stock_status = "ناموجود";
            $out_of_stock_count++;
        } else {
            $stock_status = "موجود";
            $in_stock_count++;
        }
        
        $current_data[$title] = [
            'sku' => $sku, 'price' => $price, 'stock' => $stock_status, 'link' => $product_link, 'image' => $image_src
        ];
    }
    sleep(rand(1, 2)); 
}

$changes_found_in_cat = false;
$category_email_log = "";
$old_data = file_exists($data_file) ? json_decode(file_get_contents($data_file), true) : [];

if (!empty($old_data) && !empty($current_data)) {
    foreach ($current_data as $title => $data) {
        $change_text = "";
        if (isset($old_data[$title])) {
            $old_price = $old_data[$title]['price'];
            $old_stock = $old_data[$title]['stock'];
            if ($old_price !== $data['price']) {
                $change_text .= "💰 <b>تغییر قیمت:</b>\nقدیم: <code>{$old_price}</code>\n⬅️ جدید: <code>{$data['price']}</code>\n";
            }
            if ($old_stock !== $data['stock']) {
                $change_text .= "📦 <b>تغییر موجودی:</b> از {$old_stock} به ⬅️ {$data['stock']}\n";
            }
        } else {
            $change_text .= "🆕 <b>محصول جدید اضافه شد</b>\n💰 قیمت: <code>{$data['price']}</code>\n";
        }
        
        if ($change_text !== "") {
            $changes_found_in_cat = true;
            $caption = "📂 <b>دسته: {$category_name}</b>\n<b>{$title}</b>\n🔖 کد کالا (SKU): {$data['sku']}\n\n{$change_text}";
            send_to_telegram($telegram_token, $chat_id, $caption, $data['image'], $data['link']);
            $category_email_log .= "   - محصول: {$title}\n     " . strip_tags(str_replace(['<b>', '</b>'], '', $change_text)) . "\n";
            usleep(300000); 
        }
    }

    foreach ($old_data as $title => $old_item) {
        if (!isset($current_data[$title])) {
            $change_text = "🗑 <b>محصول از سایت حذف شد!</b>\nآخرین قیمت ثبت شده: <code>{$old_item['price']}</code>\n";
            $changes_found_in_cat = true;
            $caption = "📂 <b>دسته: {$category_name}</b>\n<b>{$title}</b>\n🔖 کد کالا (SKU): {$old_item['sku']}\n\n{$change_text}";
            send_to_telegram($telegram_token, $chat_id, $caption);
            $category_email_log .= "   - محصول: {$title}\n     حذف شد!\n";
            usleep(300000);
        }
    }
} elseif (empty($old_data) && !empty($current_data)) {
    $welcome_msg = "✅ ربات برای دسته <b>{$category_name}</b> متصل شد و دیتابیس اولیه ساخته شد.";
    send_to_telegram($telegram_token, $chat_id, $welcome_msg);
    $category_email_log .= "   - دیتابیس اولیه ساخته شد.\n";
}

if (!empty($current_data)) {
    file_put_contents($data_file, json_encode($current_data, JSON_UNESCAPED_UNICODE));
}

// در اینجا مشکل آلارم‌های اضافی دسته‌های خالی حل شد
if ($changes_found_in_cat || (empty($old_data) && !empty($current_data))) {
    $stats = "📊 <b>آمار دسته «{$category_name}»</b>\n🔹 کل محصولات: {$total_count}\n✅ موجود: {$in_stock_count}\n❌ ناموجود: {$out_of_stock_count}\n";
    send_to_telegram($telegram_token, $chat_id, $stats);

    $cat_log_for_email = "📁 دسته‌بندی: {$category_name}\n{$category_email_log}";
    $cat_log_for_email .= "مجموع محصولات: {$total_count} (موجود: {$in_stock_count} | ناموجود: {$out_of_stock_count})\n";
    $cat_log_for_email .= "----------------------------------------\n\n";
    
    file_put_contents($email_log_file, $cat_log_for_email, FILE_APPEND);
    file_put_contents($changes_flag_file, "1");
}

$next_index = $current_index + 1;
file_put_contents($state_file, (string)$next_index);

echo "<div style='font-family:tahoma; direction:rtl; margin:40px; text-align:right;'>";
echo "<h2>⏳ در حال ایجاد دیتابیس‌ها و بررسی...</h2>";
echo "<h3>✅ دسته <b>{$category_name}</b> بررسی شد.</h3>";
echo "<p style='font-size:18px;'>پیشرفت: <b>دسته {$next_index} از " . count($categories) . "</b></p>";
echo "<p style='color:red;'>⚠️ لطفاً این صفحه را نبندید! تا ۲ ثانیه دیگر به صورت خودکار سراغ دسته بعدی می‌رود...</p>";
echo "</div>";

echo "<meta http-equiv='refresh' content='2'>";
?>