<?php

$bot_token = "8187059436:AAEPwFTEUzRNHTzZKrwVuIwqE3iadhPcZi8";
$support_username = "sajad_ghazi";
$admin_id = 586924831;

$update = json_decode(file_get_contents("php://input"), true);

if (isset($update["channel_post"]) || isset($update["edited_channel_post"])) {
    $post_data = $update["channel_post"] ?? $update["edited_channel_post"];

    $from_id = $post_data["from"]["id"] ?? null;
    $chat_id = $post_data["chat"]["id"];
    $message_id = $post_data["message_id"];
    $text = $post_data["text"] ?? $post_data["caption"] ?? "";

if (strpos($text, "xxx") !== false) {
    $new_text = str_replace("xxx", "", $text);
    $new_text = trim($new_text); // برای حذف فاصله‌های اضافه بعد از حذف

    if (isset($update["channel_post"]["caption"])) {
        // اگر پیام عکس یا ویدیو با کپشن بود
        file_get_contents("https://api.telegram.org/bot$bot_token/editMessageCaption?chat_id=$chat_id&message_id=$message_id&caption=" . urlencode($new_text));
    } else {
    file_get_contents("https://api.telegram.org/bot$bot_token/editMessageText?chat_id=$chat_id&message_id=$message_id&text=" . urlencode($new_text));
    }
    exit;
}

function convertToLatinNumbers($text) {
    $persianNumbers = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
    $latinNumbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

    return str_replace($persianNumbers, $latinNumbers, $text);
}

$text = convertToLatinNumbers(trim($text));
$lines = explode("\n", $text);
$lastLine = trim(end($lines));
if (preg_match('/^\d+$/', $lastLine)) {
    $newAmount = number_format((int)$lastLine);

array_pop($lines);
    $text = implode("\n", $lines);

    if (strpos($text, '🔥قیمت:') !== false) {
    $text = preg_replace('/🔥قیمت:\s*[\d,\.]+\s*تومان\s*🔥/', "🔥قیمت: {$newAmount} تومان 🔥", $text);
    } else {
    $text .= "\n\n🔥قیمت: {$newAmount} تومان 🔥\n\n📎وارد کننده مستقیم🇨🇳 و پخش لوازم جانبی";
    }
}
if (preg_match('/(\d[\d,\.]*)\s*تومان/u', $text, $matches)) {
    $raw_price = str_replace([',', '٫'], '', $matches[1]);
    $price = number_format((int)$raw_price);

    $new_text = preg_replace('/(\d[\d,\.]*)\s*تومان/u', "$price تومان", $text);

  // خواندن وضعیت فعلی دکمه اول (اگر موجود است)
$current_status_text = "✅ موجود"; // مقدار پیش‌فرض
$current_status_callback = "status:available";

if (isset($post_data["reply_markup"]["inline_keyboard"][0][0])) {
    $button = $post_data["reply_markup"]["inline_keyboard"][0][0];
    if (isset($button["text"]) && isset($button["callback_data"]) && strpos($button["callback_data"], "status:") === 0) {
        $current_status_text = $button["text"];
        $current_status_callback = $button["callback_data"];
    }
}

$inline_keyboard = [
    "inline_keyboard" => [
        [
            ["text" => $current_status_text, "callback_data" => $current_status_callback],
            ["text" => "🛒 سفارش", "callback_data" => "order_menu"]
        ],
        [
            ["text" => "💰 قیمت: $price تومان", "callback_data" => "noop"]
        ]
    ]
];

} else {
    $new_text = $text;

    // خواندن وضعیت فعلی دکمه اول (اگر موجود است)
    $current_status_text = "✅ موجود"; // مقدار پیش‌فرض
    $current_status_callback = "status:available";

    if (isset($post_data["reply_markup"]["inline_keyboard"][0][0])) {
        $button = $post_data["reply_markup"]["inline_keyboard"][0][0];
        if (isset($button["text"]) && isset($button["callback_data"]) && strpos($button["callback_data"], "status:") === 0) {
            $current_status_text = $button["text"];
            $current_status_callback = $button["callback_data"];
        }
    }

    $inline_keyboard = [
        "inline_keyboard" => [
            [
                ["text" => $current_status_text, "callback_data" => $current_status_callback],
                ["text" => "🛒 سفارش", "callback_data" => "order_menu"]
            ]
        ]
    ];
}


$reply_markup = json_encode($inline_keyboard);
if (isset($post_data["caption"])) {
    file_get_contents("https://api.telegram.org/bot$bot_token/editMessageCaption?chat_id=$chat_id&message_id=$message_id&caption=" . urlencode($new_text) . "&reply_markup=" . urlencode($reply_markup));
} else {
    file_get_contents("https://api.telegram.org/bot$bot_token/editMessageText?chat_id=$chat_id&message_id=$message_id&text=" . urlencode($new_text) . "&reply_markup=" . urlencode($reply_markup));
}

exit;

    if (isset($update["channel_post"]["media_group_id"])) {
        $media_group_id = $update["channel_post"]["media_group_id"];
        file_put_contents("last_media_group.txt", $media_group_id . "|" . $message_id);
        exit;
    }

    $last_media_group = @file_get_contents("last_media_group.txt");
    $last_media_data = explode("|", $last_media_group);
    
    if ((isset($update["channel_post"]["caption"]) || isset($update["channel_post"]["text"])) || ($last_media_data[0] == $media_group_id && $last_media_data[1] == $message_id)) {
        $inline_keyboard = [
            "inline_keyboard" => [
                [
                    ["text" => "✅ موجود", "callback_data" => "status:available"],
               ["text" => "🛒 سفارش", "callback_data" => "order_menu"]
               
                ]
            ]
        ];

        $reply_markup = json_encode($inline_keyboard);

        file_get_contents("https://api.telegram.org/bot$bot_token/editMessageReplyMarkup?chat_id=$chat_id&message_id=$message_id&reply_markup=$reply_markup");

        @unlink("last_media_group.txt");
    }
}
if (isset($update["callback_query"])) {
    $callback_id = $update["callback_query"]["id"];
    $chat_id = $update["callback_query"]["message"]["chat"]["id"];
    $message_id = $update["callback_query"]["message"]["message_id"];
    $callback_data = $update["callback_query"]["data"];
    
    if ($callback_data == "order_menu") {
    $inline_keyboard = [
     "inline_keyboard" => [
    [ // ردیف اول - دو دکمه کنار هم
        ["text" => "📦 شعبه مشهد", "url" => "http://t.me/mirkala_en"],
        ["text" => "📦 شعبه گرگان", "url" => "http://t.me/mirkalagorgan"]
    ],
    [ // ردیف دوم - دو دکمه کنار هم
        ["text" => "📸 پیج اینستاگرام", "url" => "http://instagram.com/mirshojaan.janebi"],
        ["text" => "🔗 زیلینک", "url" => "https://zil.ink/mirkala"]
    ],
    [ // ردیف سوم - دکمه بازگشت
        ["text" => "🔙 بازگشت", "callback_data" => "back_to_main"]
    ]
]


    ];

    $reply_markup = json_encode($inline_keyboard);

    file_get_contents("https://api.telegram.org/bot$bot_token/editMessageReplyMarkup?chat_id=$chat_id&message_id=$message_id&reply_markup=$reply_markup");

    file_get_contents("https://api.telegram.org/bot$bot_token/answerCallbackQuery?callback_query_id=$callback_id");
    exit;
}
    if ($callback_data == "back_to_main") {
    $text = $update["callback_query"]["message"]["text"] ?? "";
    if (preg_match('/(\d[\d,\.]*)\s*تومان/u', $text, $matches)) {
        $raw_price = str_replace([',', '٫'], '', $matches[1]);
        $price = number_format((int)$raw_price);

   // خواندن وضعیت فعلی دکمه اول (اگر موجود است)
$current_status_text = "✅ موجود"; // مقدار پیش‌فرض
$current_status_callback = "status:available";

if (isset($post_data["reply_markup"]["inline_keyboard"][0][0])) {
    $button = $post_data["reply_markup"]["inline_keyboard"][0][0];
    if (isset($button["text"]) && isset($button["callback_data"]) && strpos($button["callback_data"], "status:") === 0) {
        $current_status_text = $button["text"];
        $current_status_callback = $button["callback_data"];
    }
}

$inline_keyboard = [
    "inline_keyboard" => [
        [
            ["text" => $current_status_text, "callback_data" => $current_status_callback],
            ["text" => "🛒 سفارش", "callback_data" => "order_menu"]
        ],
        [
            
            ["text" => "💰 قیمت: $price تومان", "callback_data" => "noop"]
        ]
    ]
];

    } else {
    $inline_keyboard = [
            "inline_keyboard" => [
                [
                    ["text" => "✅ موجود", "callback_data" => "status:available"],
                    ["text" => "🛒 سفارش", "callback_data" => "order_menu"]
                ]
            ]
        ];
    }

    $reply_markup = json_encode($inline_keyboard);
    file_get_contents("https://api.telegram.org/bot$bot_token/editMessageReplyMarkup?chat_id=$chat_id&message_id=$message_id&reply_markup=$reply_markup");

    file_get_contents("https://api.telegram.org/bot$bot_token/answerCallbackQuery?callback_query_id=$callback_id");
    exit;
}
    
    $user_id = $update["callback_query"]["from"]["id"];

   if (strpos($callback_data, "status:") !== false) {
    if ($user_id != $admin_id) {
        file_get_contents("https://api.telegram.org/bot$bot_token/answerCallbackQuery?callback_query_id=$callback_id");
        exit;
    }

    $current_status = str_replace("status:", "", $callback_data);

    switch ($current_status) {
        case "available":
            $new_status = "not_available";
            $new_text = "⚠️ تعداد محدود";
            break;
        case "not_available":
            $new_status = "limited";
            $new_text = "❌ اتمام موجودی";
            break;
        case "limited":
            $new_status = "coming_soon";
            $new_text = "🕒 موجود به زودی...";
            break;
        case "coming_soon":
        default:
            $new_status = "available";
            $new_text = "✅ موجود";
            break;
    }

    $inline_keyboard = $update["callback_query"]["message"]["reply_markup"]["inline_keyboard"];
    $inline_keyboard[0][0]["text"] = $new_text;
    $inline_keyboard[0][0]["callback_data"] = "status:$new_status";

    $reply_markup = json_encode(["inline_keyboard" => $inline_keyboard]);

    file_get_contents("https://api.telegram.org/bot$bot_token/editMessageReplyMarkup?chat_id=$chat_id&message_id=$message_id&reply_markup=$reply_markup");

    file_get_contents("https://api.telegram.org/bot$bot_token/answerCallbackQuery?callback_query_id=$callback_id");
    exit;
}

}

?>


