<?php
/*
dev: https://factweb.ir
channel telegram : @factwebir
*/
// باید هر 1 دقیقه کرون جاب شود

include "../config.php";
set_time_limit(300);
error_reporting(0);
date_default_timezone_set('Asia/Tehran');
define('API_KEY',$API_KC);

function factweb($method,$datas=[]){
    global $API_KC;
    $url = "https://api.telegram.org/bot".API_KEY."/".$method;
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$datas);
    $res = curl_exec($ch);
    if(curl_error($ch)){
        // var_dump(curl_error($ch));
    }else{
        return json_decode($res);
    }
}

function Takhmin($fil){
    if($fil <= 40 ){
        return "2";
    }else{
        $besanie = $fil/40;
        return ceil($besanie)+1;
    }
}

function get_target_lang_cron($connect, $target_user_id) {
    global $botid;
    $set_res = mysqli_query($connect, "SELECT lang_fa_status, lang_en_status FROM settings WHERE botid = '$botid' LIMIT 1");
    $settings = mysqli_fetch_assoc($set_res);

    if ($settings['lang_fa_status'] == 1 && $settings['lang_en_status'] == 0) return 'fa';
    if ($settings['lang_fa_status'] == 0 && $settings['lang_en_status'] == 1) return 'en';

    $u_res = mysqli_query($connect, "SELECT lng FROM user WHERE id = '$target_user_id' LIMIT 1");
    if ($u_res && mysqli_num_rows($u_res) > 0) {
        $u_data = mysqli_fetch_assoc($u_res);
        return !empty($u_data['lng']) ? $u_data['lng'] : 'fa';
    }
    return 'fa';
}

function call_callinoo_api($endpoint, $method = 'GET', $data_array = null, $auth_type = 'url') {
    global $callinoo_api_key, $callinoo_base_url;
    $url = $callinoo_base_url;
    $headers = [
        'Content-Type: application/json',
        'Accept: application/json'
    ];
    if ($auth_type === 'bearer') {
        $url .= $endpoint;
        $headers[] = 'Authorization: Bearer ' . $callinoo_api_key;
    } else {
        $endpoint_with_token = str_replace('{token}', $callinoo_api_key, $endpoint);
        $url .= $endpoint_with_token;
    }
    $ch = curl_init();
    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        if ($data_array) {
            $payload = json_encode($data_array);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
            $headers[] = 'Content-Length: ' . strlen($payload);
        }
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $response_raw = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);

    if ($curl_error) {
        return ['_http_code' => 503, 'success' => false, 'error' => 'Curl Error: ' . $curl_error];
    }

    $response_json = json_decode($response_raw, true);
    if ($response_json === null) {
        return ['_http_code' => $http_code, 'success' => false, 'error' => 'Invalid JSON response', 'raw' => $response_raw];
    }
    $response_json['_http_code'] = $http_code;
    return $response_json;
}

function getReportKeyboard($status, $user_id) {
    $status_text = "▫️ وضعیت: ⏳ در حال بررسی";
    switch ($status) {
        case 'completed': $status_text = "✅ تکمیل شده"; break;
        case 'cancelled':
        case 'failed':
        case 'expired': $status_text = "❌ لغو/ناموفق"; break;
        case 'code_waiting': $status_text = "⏳ در انتظار کد"; break;
    }

    return json_encode(['inline_keyboard' => [
        [
            ['text' => $status_text, 'callback_data' => "none"]
        ],
        [
            ['text' => "📨 پیوی کاربر", 'url' => "tg://openmessage?user_id=$user_id"]
        ]
    ]]);
}

echo "Cron Job Started: Checking Order Statuses...\n";

$pending_premiums = $connect->query("
SELECT po.id, po.user_id, po.target_username, po.api_order_id, po.order_code, po.report_message_id,
  po.payment_method, po.cost_irt, po.cost_ton,
  IFNULL(pp.display_name, pp.name) as package_name
FROM premium_orders po
LEFT JOIN premium_packages pp ON po.package_id = pp.id
WHERE po.status = 'pending'
AND po.api_order_id IS NOT NULL
AND po.api_order_id != 'N/A'
AND po.api_order_id != 'MANUAL'
");

if ($pending_premiums && $pending_premiums->num_rows > 0) {
    echo "Found " . $pending_premiums->num_rows . " pending premium orders.\n";
    while ($order = $pending_premiums->fetch_assoc()) {
        $api_code = $order['api_order_id'];
        $user_id = $order['user_id'];

        $api_response = call_callinoo_api("/telegram-services/status/", 'GET', ['service' => 'premium', 'code' => $api_code], 'bearer');

        if (isset($api_response['status']) && $api_response['status'] === true && isset($api_response['data']['status']) && $api_response['data']['status'] === true) {

            $connect->query("UPDATE premium_orders SET status = 'completed' WHERE id = {$order['id']}");

            if (!empty($order['report_message_id']) && !empty($channelreports)) {
                $new_keyboard = getReportKeyboard('completed', $user_id);
                factweb('editMessageReplyMarkup', [
                    'chat_id' => $channelreports,
                    'message_id' => $order['report_message_id'],
                    'reply_markup' => $new_keyboard
                ]);
            }

            $package_name = $order['package_name'] ?? 'پریمیوم';
            $t_lang = get_target_lang_cron($connect, $user_id);

            if ($t_lang == 'en') {
                $message_text = "✅ Your Premium order is completed.\n\n" .
                    "▫️ Plan: <b>" . htmlspecialchars($package_name) . "</b>\n" .
                    "▫️ Recipient: @" . htmlspecialchars($order['target_username']) . "\n\n" .
                    "Thank you for your purchase!";
            } else {
                $message_text = "✅ سفارش پریمیوم شما تکمیل شد.\n\n" .
                    "▫️ پلن: <b>" . htmlspecialchars($package_name) . "</b>\n" .
                    "▫️ برای: @" . htmlspecialchars($order['target_username']) . "\n\n" .
                    "از خرید شما متشکریم!";
            }

            factweb('sendMessage', [
                'chat_id' => $user_id,
                'text' => $message_text,
                'parse_mode' => 'HTML'
            ]);

            if(function_exists('sendProofToChannel')){
                $currency_proof = ($order['payment_method'] == 'IRT') ? 'تومان' : 'TON';
                $amount_proof = ($order['payment_method'] == 'IRT') ? $order['cost_irt'] : $order['cost_ton'];


                $plan_name = $order['package_name'] ?? 'نامشخص';

                $item_name_fa = "پریمیوم تلگرام\n📋 <b>پلن:</b> $plan_name";
                $item_name_en = "Telegram Premium\n📋 <b>Plan:</b> $plan_name";

                sendProofToChannel($user_id, $item_name_fa, $item_name_en, $amount_proof, $currency_proof, time());
            }

            echo "Order ID {$order['id']} (Premium) completed. Notifying user $user_id.\n";
        }
    }
} else {
    echo "No pending premium orders (API) found.\n";
}


$pending_stars = $connect->query("
SELECT id, user_id, target_username, quantity, api_order_id, order_code, report_message_id,
  payment_method, cost_irt_final, cost_ton_final
FROM star_orders
WHERE status = 'pending'
AND api_order_id IS NOT NULL
AND api_order_id != 'N/A'
AND api_order_id != 'MANUAL'
");

if ($pending_stars && $pending_stars->num_rows > 0) {
    echo "Found " . $pending_stars->num_rows . " pending star orders.\n";
    while ($order = $pending_stars->fetch_assoc()) {
        $api_code = $order['api_order_id'];
        $user_id = $order['user_id'];

        $api_response = call_callinoo_api("/telegram-services/status/", 'GET', ['service' => 'stars', 'code' => $api_code], 'bearer');

        if (isset($api_response['status']) && $api_response['status'] === true && isset($api_response['data']['status']) && $api_response['data']['status'] === true) {

            $connect->query("UPDATE star_orders SET status = 'completed' WHERE id = {$order['id']}");

            if (!empty($order['report_message_id']) && !empty($channelreports)) {
                $new_keyboard = getReportKeyboard('completed', $user_id);
                factweb('editMessageReplyMarkup', [
                    'chat_id' => $channelreports,
                    'message_id' => $order['report_message_id'],
                    'reply_markup' => $new_keyboard
                ]);
            }

            $t_lang = get_target_lang_cron($connect, $user_id);

            if ($t_lang == 'en') {
                $message_text = "✅ Your Stars order is completed.\n\n" .
                    "▫️ Quantity: <b>" . number_format($order['quantity']) . "</b> Stars ✨\n" .
                    "▫️ Recipient: @" . htmlspecialchars($order['target_username']) . "\n\n" .
                    "Thank you for your purchase!";
            } else {
                $message_text = "✅ سفارش استارز شما تکمیل شد.\n\n" .
                    "▫️ تعداد: <b>" . number_format($order['quantity']) . "</b> استارز ✨\n" .
                    "▫️ برای: @" . htmlspecialchars($order['target_username']) . "\n\n" .
                    "از خرید شما متشکریم!";
            }

            factweb('sendMessage', [
                'chat_id' => $user_id,
                'text' => $message_text,
                'parse_mode' => 'HTML'
            ]);

            if(function_exists('sendProofToChannel')){
                $currency_proof = ($order['payment_method'] == 'IRT') ? 'تومان' : 'TON';
                $amount_proof = ($order['payment_method'] == 'IRT') ? $order['cost_irt_final'] : $order['cost_ton_final'];
                $qty_formatted = number_format($order['quantity']);
                sendProofToChannel($user_id, "$qty_formatted استارز", "$qty_formatted Stars", $amount_proof, $currency_proof, time());
            }

            echo "Order ID {$order['id']} (Stars) completed. Notifying user $user_id.\n";
        }
    }
} else {
    echo "No pending star orders (API) found.\n";
}


echo "Checking for expired virtual number orders...\n";
$expired_vnums_res = $connect->query("
SELECT id, user_id, request_id, order_code, report_message_id, payment_method, price_irt, price_ton
FROM virtual_number_orders
WHERE status = 'code_waiting' AND created_at < NOW() - INTERVAL 1 HOUR
");

if ($expired_vnums_res && $expired_vnums_res->num_rows > 0) {
    echo "Found " . $expired_vnums_res->num_rows . " expired virtual number orders to cancel.\n";

    while ($order = $expired_vnums_res->fetch_assoc()) {
        $order_id_db = (int)$order['id'];

        $check_status = $connect->query("SELECT status FROM virtual_number_orders WHERE id = $order_id_db LIMIT 1")->fetch_assoc();
        if (!$check_status || $check_status['status'] != 'code_waiting') {
            echo "Order ID $order_id_db status changed (to {$check_status['status']}), skipping refund.\n";
            continue;
        }
        $user_id = $order['user_id'];
        $request_id = $order['request_id'];

        if (empty($request_id) || $request_id == 0) {
            continue;
        }

        $api_endpoint = "/web/{token}/logout/$request_id";
        call_callinoo_api($api_endpoint, 'POST', null, 'url');

        $connect->begin_transaction();
        try {
            $stmt_cancel = $connect->prepare("UPDATE virtual_number_orders SET status = 'expired' WHERE id = ? AND status = 'code_waiting'");
            $stmt_cancel->bind_param("i", $order_id_db);
            $stmt_cancel->execute();

            if ($stmt_cancel->affected_rows > 0) {
                $refund_message_part = "";
                if ($order['payment_method'] == 'IRT') {
                    $stmt_refund = $connect->prepare("UPDATE user SET balancerial = balancerial + ? WHERE id = ?");
                    $stmt_refund->bind_param("is", $order['price_irt'], $user_id);
                } else { // TON
                    $stmt_refund = $connect->prepare("UPDATE user SET balanceton = balanceton + ? WHERE id = ?");
                    $stmt_refund->bind_param("ds", $order['price_ton'], $user_id);
                }
                $stmt_refund->execute();

                $connect->commit();
                echo "Order ID {$order['id']} (VNumber) expired. Refunded to user $user_id.\n";

                if (!empty($order['report_message_id']) && !empty($channelreports)) {
                    $new_keyboard = getReportKeyboard('expired', $user_id);
                    factweb('editMessageReplyMarkup', [
                        'chat_id' => $channelreports,
                        'message_id' => $order['report_message_id'],
                        'reply_markup' => $new_keyboard
                    ]);
                }

                $t_lang = get_target_lang_cron($connect, $user_id);

                if ($t_lang == 'en') {
                    $refund_txt = ($order['payment_method'] == 'IRT') ? number_format($order['price_irt']) . " IRT" : number_format((float)$order['price_ton'], 3) . " TON";
                    $message_text = "⚠️ Your virtual number order (Code: <code>{$order['order_code']}</code>) has expired due to not receiving the code.\n\nRefunded: $refund_txt";
                } else {
                    $refund_message_part = ($order['payment_method'] == 'IRT') ? "مبلغ " . number_format($order['price_irt']) . " تومان به حساب شما بازگردانده شد." : "مبلغ " . number_format((float)$order['price_ton'], 3) . " تون به حساب شما بازگردانده شد.";
                    $message_text = "⚠️ سفارش شماره مجازی شما (کد: <code>{$order['order_code']}</code>) به دلیل عدم دریافت کد در زمان مقرر منقضی شد.\n\n$refund_message_part";
                }

                factweb('sendMessage', [
                    'chat_id' => $user_id,
                    'text' => $message_text,
                    'parse_mode' => 'HTML'
                ]);

            } else {
                $connect->rollback();
            }

        } catch (Exception $e) {
            $connect->rollback();
            echo "Error processing VNumber Order ID {$order['id']}: " . $e->getMessage() . "\n";
        }
    }
} else {
    echo "No expired virtual number orders found.\n";
}
echo "Cron Job Continuing: Processing Queues...\n";

$settings = mysqli_fetch_assoc(mysqli_query($connect,"SELECT * FROM settings WHERE botid = '$botid' LIMIT 1"));
$foall = $settings["forall"];
$sendall = $settings["sendall"];
$tedad = $settings["tedad"];
$text = $settings["text"];
$chat_id = $settings["chat_id"];
$msg_id = $settings["msg_id"];
$pin_message = $settings["pin_message"];
$is_all = $settings["is_all"];
$factwebir = $settings["factwebir"];
$charge_ton_all = $settings["charge_ton_all"];
$charge_amount_ton = $settings["charge_amount_ton"];
$charge_rial_all = $settings["charge_rial_all"];
$charge_amount_rial = $settings["charge_amount_rial"];

$users_query = mysqli_query($connect,"select id from user");
$ex = [];
while($row = mysqli_fetch_assoc($users_query)){
    $ex[] = $row["id"];
}
$fil = count($ex);

if($tedad >= $fil && ($foall == "true" || $sendall == "true" || $charge_ton_all == "true" || $charge_rial_all == "true")) {

    if ($foall == "true" || $sendall == "true") {
        $end_message_text = "✅ همگانی پایان یافت .";
    }
    if ($charge_ton_all == "true" || $charge_rial_all == "true") {
        $end_message_text = "✅ شارژ همگانی پایان یافت.";
    }

    $connect->query("UPDATE settings SET 
  forall = 'false', 
  sendall = 'false', 
  charge_ton_all = 'false',
  charge_rial_all = 'false',
  tedad = '0', 
  msg_id = '0', 
  pin_message = 'false', 
  is_all = 'no', 
  factwebir = '0',
  charge_amount_ton = '0',
  charge_amount_rial = '0'
  WHERE botid = '$botid' LIMIT 1");

    if(!empty($is_all) && $is_all != 'no' && !empty($factwebir) && !empty($end_message_text)){
        factweb('editMessageReplyMarkup',[
            'chat_id'=>$is_all,
            'message_id'=>$factwebir,
            'reply_markup'=> json_encode([
                'inline_keyboard'=>[
                    [['text'=> $end_message_text,'callback_data'=>"none"]],
                ]
            ])
        ]);
    }
}
elseif($foall == "true"){
    $kobs2 = $tedad + 40;
    for($z = $tedad; $z < $kobs2; $z++){
        if(isset($ex[$z])){
            $sent_message = factweb('ForwardMessage',[
                'chat_id'=>$ex[$z],
                'from_chat_id'=>$chat_id,
                'message_id'=>$msg_id,
            ]);

            if($pin_message == "true" && isset($sent_message->result->message_id)){
                factweb('pinChatMessage', [
                    'chat_id' => $ex[$z],
                    'message_id' => $sent_message->result->message_id,
                    'disable_notification' => false
                ]);
            }
        }
    }
    $new_tedad = $z;
    if($new_tedad > $fil) $new_tedad = $fil;

    $connect->query("UPDATE settings SET tedad = '$new_tedad' WHERE botid = '$botid' LIMIT 1");
    $tfrigh = $fil - $new_tedad;
    $min = Takhmin($tfrigh);

    if(!empty($is_all) && $is_all != 'no' && !empty($factwebir)){
        factweb('editMessageReplyMarkup',[
            'chat_id'=>$is_all,
            'message_id'=>$factwebir,
            'reply_markup'=> json_encode([
                'inline_keyboard'=>[
                    [['text'=>"🔹 تعداد افراد ارسال شده : $new_tedad",'callback_data'=>"none"]],
                    [['text'=>"🚀 زمان تخمینی ارسال : $min دقیقه (باقیمانده)",'callback_data'=>"none"]],
                ]
            ])
        ]);
    }
}

elseif($sendall == "true"){
    $kobs2 = $tedad + 40;
    for($z = $tedad; $z < $kobs2; $z++){
        if(isset($ex[$z])){
            $sent_message = factweb('sendMessage',[
                'chat_id'=>$ex[$z],
                'text'=>$text,
                'parse_mode'=>"HTML",
                'disable_web_page_preview'=>true,
            ]);

            if($pin_message == "true" && isset($sent_message->result->message_id)){
                factweb('pinChatMessage', [
                    'chat_id' => $ex[$z],
                    'message_id' => $sent_message->result->message_id,
                    'disable_notification' => false
                ]);
            }
        }
    }
    $new_tedad = $z;
    if($new_tedad > $fil) $new_tedad = $fil;

    $connect->query("UPDATE settings SET tedad = '$new_tedad' WHERE botid = '$botid' LIMIT 1");
    $tfrigh = $fil - $new_tedad;
    $min = Takhmin($tfrigh);

    if(!empty($is_all) && $is_all != 'no' && !empty($factwebir)){
        factweb('editMessageReplyMarkup',[
            'chat_id'=>$is_all,
            'message_id'=>$factwebir,
            'reply_markup'=> json_encode([
                'inline_keyboard'=>[
                    [['text'=>"🔹 تعداد افراد ارسال شده : $new_tedad",'callback_data'=>"none"]],
                    [['text'=>"🚀 زمان تخمینی ارسال : $min دقیقه (باقیمانده)",'callback_data'=>"none"]],
                ]
            ])
        ]);
    }
}

elseif($charge_ton_all == "true"){
    $kobs2 = $tedad + 40;

    for($z = $tedad; $z < $kobs2; $z++){
        if(isset($ex[$z])){
            $user_id = $ex[$z];
            $user_info = mysqli_fetch_assoc(mysqli_query($connect,"SELECT lng FROM user WHERE id = '$user_id' LIMIT 1"));
            $user_lang = $user_info['lng'];

            $connect->query("UPDATE user SET balanceton = balanceton + $charge_amount_ton WHERE id = '$user_id' LIMIT 1");

            if($user_lang == 'en'){
                $message = "🎉 <b>Gift Charge!</b>\n\n💎 Amount of <code>$charge_amount_ton</code> TON has been added to your balance!\n\n✨ Enjoy your gift!";
            } else {
                $message = "🎉 <b>شارژ هدیه!</b>\n\n💎 مبلغ <code>$charge_amount_ton</code> تون به موجودی شما اضافه شد!\n\n✨ از این هدیه لذت ببرید!";
            }

            factweb('sendMessage',[
                'chat_id' => $user_id,
                'text' => $message,
                'parse_mode' => 'HTML'
            ]);
        }
    }

    $new_tedad = $z;
    if($new_tedad > $fil) $new_tedad = $fil;

    $connect->query("UPDATE settings SET tedad = '$new_tedad' WHERE botid = '$botid' LIMIT 1");

    $tfrigh = $fil - $new_tedad;
    $min = Takhmin($tfrigh);

    if(!empty($is_all) && $is_all != 'no' && !empty($factwebir)){
        factweb('editMessageReplyMarkup',[
            'chat_id'=>$is_all,
            'message_id'=>$factwebir,
            'reply_markup'=> json_encode([
                'inline_keyboard'=>[
                    [['text'=>"🔹 تعداد شارژ شده : $new_tedad",'callback_data'=>"none"]],
                    [['text'=>"🚀 زمان تخمینی : $min دقیقه",'callback_data'=>"none"]],
                ]
            ])
        ]);
    }
}

elseif($charge_rial_all == "true"){
    $kobs2 = $tedad + 40;

    for($z = $tedad; $z < $kobs2; $z++){
        if(isset($ex[$z])){
            $user_id = $ex[$z];
            $user_info = mysqli_fetch_assoc(mysqli_query($connect,"SELECT lng FROM user WHERE id = '$user_id' LIMIT 1"));
            $user_lang = $user_info['lng'];

            $connect->query("UPDATE user SET balancerial = balancerial + $charge_amount_rial WHERE id = '$user_id' LIMIT 1");

            $formatted_amount = number_format($charge_amount_rial);

            if($user_lang == 'en'){
                $message = "🎉 <b>Gift Charge!</b>\n\n💵 Amount of <code>$formatted_amount</code> Toman has been added to your balance!\n\n✨ Enjoy your gift!";
            } else {
                $message = "🎉 <b>شارژ هدیه!</b>\n\n💵 مبلغ <code>$formatted_amount</code> تومان به موجودی شما اضافه شد!\n\n✨ از این هدیه لذت ببرید!";
            }

            factweb('sendMessage',[
                'chat_id' => $user_id,
                'text' => $message,
                'parse_mode' => 'HTML'
            ]);
        }
    }

    $new_tedad = $z;
    if($new_tedad > $fil) $new_tedad = $fil;

    $connect->query("UPDATE settings SET tedad = '$new_tedad' WHERE botid = '$botid' LIMIT 1");

    $tfrigh = $fil - $new_tedad;
    $min = Takhmin($tfrigh);

    if(!empty($is_all) && $is_all != 'no' && !empty($factwebir)){
        factweb('editMessageReplyMarkup',[
            'chat_id'=>$is_all,
            'message_id'=>$factwebir,
            'reply_markup'=> json_encode([
                'inline_keyboard'=>[
                    [['text'=>"🔹 تعداد شارژ شده : $new_tedad",'callback_data'=>"none"]],
                    [['text'=>"🚀 زمان تخمینی : $min دقیقه",'callback_data'=>"none"]],
                ]
            ])
        ]);
    }
}

$current_time = time();
$connect->query("DELETE FROM ton_charges WHERE status = 'pending' AND timeexpire < '$current_time'");
echo "Expired TON invoices cleaned up.\n";

echo "Cron Job Finished.\n";
?>