<?php
include_once __DIR__ . '/../baseInfo.php';
include_once __DIR__ . '/../config.php';
include_once __DIR__ . '/config_utils.php';
include_once __DIR__ . '/crm.php';
$time = time();

// بستن خودکار تیکت‌های باز قدیمی بعد از 3 روز
$threeDaysAgo = $time - (3 * 86400);
$connection->query("UPDATE `chats` SET `state` = 2 WHERE `state` != 2 AND `create_date` < $threeDaysAgo");

// --- دپارتمان همگام‌سازی خودکار دیتابیس با پنل سنایی ---
$serversSync = $connection->query("SELECT * FROM server_config");
if ($serversSync && $serversSync->num_rows > 0) {
    while($srv = $serversSync->fetch_assoc()) {
        $srv_id = $srv['id'];
        $srv_type = $srv['type'];
        if ($srv_type == 'marzban') {
            continue;
        }
        
        $xuiRes = getJson($srv_id);
        if($xuiRes && isset($xuiRes->success) && $xuiRes->success && isset($xuiRes->obj)) {
            $inbounds = $xuiRes->obj;
            foreach($inbounds as $inbound) {
                $inbound_id = $inbound->id;
                $settings = json_decode($inbound->settings);
                $clientStats = $inbound->clientStats ?? [];
                if(!isset($settings->clients)) continue;
                
                foreach($settings->clients as $client) {
                    $email = $client->email ?? '';
                    $uuid = isset($client->id) ? $client->id : ($client->password ?? '');
                    if (empty($email) || empty($uuid)) continue;
                    
                    // فرمت ایمیل کلاینت: Client|Gift|Proxy|User|agency-7206111157-2985@tg.com
                    if(preg_match('/^(Client|Gift|Proxy|User|agency)-(\d+)-/i', $email, $emailMatch)) {
                        $tg_userid = $emailMatch[2];
                        
                        $total = 0;
                        $up = 0;
                        $down = 0;
                        $expiryTime = 0;
                        $enable = true;
                        
                        foreach($clientStats as $stat) {
                            if($stat->email == $email) {
                                $total = $stat->total ?? 0;
                                $up = $stat->up ?? 0;
                                $down = $stat->down ?? 0;
                                $expiryTime = isset($stat->expiryTime) ? substr($stat->expiryTime, 0, -3) : 0;
                                $enable = $stat->enable ?? true;
                                break;
                            }
                        }
                        
                        if ($expiryTime > 0 && strlen((string)$expiryTime) > 10) {
                            $expiryTime = intval(substr((string)$expiryTime, 0, 10));
                        }
                        
                        $checkOrder = $connection->prepare("SELECT id, userid FROM `orders_list` WHERE `uuid` = ? OR `remark` = ?");
                        $checkOrder->bind_param("ss", $uuid, $email);
                        $checkOrder->execute();
                        $orderResult = $checkOrder->get_result();
                        $checkOrder->close();
                        
                        if($orderResult->num_rows > 0) {
                            $orderData = $orderResult->fetch_assoc();
                            if($orderData['userid'] != $tg_userid) {
                                $upd = $connection->prepare("UPDATE `orders_list` SET `userid` = ? WHERE `id` = ?");
                                $upd->bind_param("si", $tg_userid, $orderData['id']);
                                $upd->execute();
                                $upd->close();
                            }
                        } else {
                            $inst = $connection->prepare("INSERT INTO `orders_list` (`userid`, `token`, `transid`, `fileid`, `server_id`, `inbound_id`, `remark`, `uuid`, `protocol`, `expire_date`, `link`, `amount`, `status`, `date`, `notif`, `rahgozar`, `agent_bought`) VALUES (?, '', '', 0, ?, ?, ?, ?, 'vless/vmess/trojan', ?, '', 0, 1, ?, 0, 0, 0)");
                            $currDate = date("Y-m-d H:i:s");
                            $inst->bind_param("siiisis", $tg_userid, $srv_id, $inbound_id, $email, $uuid, $expiryTime, $currDate);
                            $inst->execute();
                            $inst->close();
                        }
                    }
                }
            }
        }
    }
}

// خواندن offset برای پیمایش دیتابیس
if(file_exists("warnOffset.txt")) $warnOffset = file_get_contents("warnOffset.txt");
else $warnOffset = 0;
$limit = 50;

// دریافت لیست کاربرانی که هشدار دریافت نکرده‌اند
$stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `status`=1 AND (`notif`=0 OR `notif` = -1) ORDER BY `id` ASC LIMIT ? OFFSET ?");
$stmt->bind_param("ii", $limit, $warnOffset);
$stmt->execute();
$orders = $stmt->get_result();
$stmt->close();

if($orders){
    if($orders->num_rows>0){
        while ($order = $orders->fetch_assoc()){
            // --- مقداردهی اولیه متغیرها برای جلوگیری از ارور ---
            $send = false;
            $total = 0; 
            $up = 0; 
            $down = 0; 
            $totalLeft = 0;
            $expiryTime = 0;
            $found = false;
            $logedIn = false;
            // ----------------------------------------------------

            $from_id = $order['userid'];
            $remark = $order['remark'];
            $uuid = $order['uuid']??"0";
            $server_id = $order['server_id'];
            $inbound_id = $order['inbound_id'];
            $notif = $order['notif'];
            $amount = $order['amount'];

            // دریافت اطلاعات سرور
            $stmt = $connection->prepare("SELECT * FROM `server_config` WHERE `id` = ?");
            $stmt->bind_param('i', $server_id);
            $stmt->execute();
            $serverConfig = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            
            if (!$serverConfig) {
                continue;
            }
            
            $serverType = $serverConfig['type'];
            $panel_url = $serverConfig['panel_url'];

            // بررسی در پنل مرزبان
            if($serverType == "marzban"){
                $info = getMarzbanUser($server_id, $remark);
                if(isset($info->username)){
                    $found = true;
                    $logedIn = true;
                    $total = $info->data_limit;
                    $totalLeft = $total - $info->used_traffic;
                    $expiryTime = $info->expire;
                    $enable = $info->status == "active"?true:false;
                }elseif(isset($info->detail)){
                    if($info->detail == "User not found") $logedIn = true;
                }
            }else{
                // بررسی در پنل X-UI
                $response = getJson($server_id); 
                if($response && isset($response->success) && $response->success){
                    $logedIn = true;
                    $response = $response->obj;
                    foreach($response as $row){
                        if($inbound_id == 0) { 
                            $settings = json_decode($row->settings);
                            if(isset($settings->clients) && is_array($settings->clients)){
                                $clientId = isset($settings->clients[0]->id) ? $settings->clients[0]->id : ($settings->clients[0]->password ?? '');
                                $clientEmail = $settings->clients[0]->email ?? '';
                                if($clientId == $uuid || $clientEmail == $uuid || $clientEmail == $remark) {
                                    $found = true;
                                    $total = $row->total;
                                    $up = $row->up;
                                    $down = $row->down;
                                    $expiryTime = substr($row->expiryTime, 0, -3);
                                    $enable = $row->enable;
                                    break;
                                }
                            }
                        }else{
                            if($row->id == $inbound_id) {
                                $settings = json_decode($row->settings, true); 
                                $clients = $settings['clients'];
                                $clientsStates = $row->clientStats;
                                
                                foreach($clients as $key => $client){
                                    $clientId = isset($client['id']) ? $client['id'] : ($client['password'] ?? '');
                                    $clientEmail = $client['email'] ?? '';
                                    if($clientId == $uuid || $clientEmail == $uuid || $clientEmail == $remark){
                                        $found = true;
                                        $email = $client['email'];
                                        $emails = array_column($clientsStates,'email');
                                        $emailKey = array_search($email,$emails);
                                        
                                        if($emailKey !== false){
                                            $total = $client['totalGB'];
                                            $up = $clientsStates[$emailKey]->up;
                                            $enable = $clientsStates[$emailKey]->enable;
                                            $down = $clientsStates[$emailKey]->down; 
                                            $expiryTime = substr($clientsStates[$emailKey]->expiryTime, 0, -3);
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    } 
                    if($found){
                        $totalLeft = $total - $up - $down;
                    }
                }
            }
            
            // اگر یوزر پیدا نشد، برو بعدی
            if(!$found) continue;

            // Sync database expire_date with panel's expiryTime
            if ($found && $expiryTime > 0) {
                if (strlen((string)$expiryTime) > 10) {
                    $expiryTime = intval(substr((string)$expiryTime, 0, 10));
                }
                $syncStmt = $connection->prepare("UPDATE `orders_list` SET `expire_date` = ? WHERE `uuid` = ? AND `server_id` = ?");
                if ($syncStmt) {
                    $syncStmt->bind_param("isi", $expiryTime, $uuid, $server_id);
                    $syncStmt->execute();
                    $syncStmt->close();
                }
            }
            
            // محاسبه حجم و زمان
            $leftgb = round( ($totalLeft) / 1073741824, 2);
            $totalGbText = round( ($total) / 1073741824, 2);
            $daysRemaining = round(((int)$expiryTime - time()) / 86400);

            // --- بررسی انقضای قطعی جهت حذف سریع ---
            if (($expiryTime != null && $expiryTime > 0 && $expiryTime <= time()) || ($totalLeft != null && $total > 0 && $totalLeft <= 0)) {
                if ($serverType == "marzban") {
                    $res = deleteMarzban($server_id, $remark);
                } else {
                    if ($inbound_id > 0) {
                        $res = deleteClient($server_id, $inbound_id, $uuid, 1);
                    } else {
                        $res = deleteInbound($server_id, $uuid, 1);
                    }
                }

                $msg = "❌ *اتمام سرویس*
                    
مشترک گرامی: `$remark`
سرویس شما به دلیل اتمام زمان یا حجم منقضی و حذف گردید. 🗑";
                $keyboard = json_encode(['inline_keyboard' => [
                    [['text' => "🛒 خرید سرویس جدید", 'callback_data' => "buySubscription"]],
                    [['text' => "🏠 منوی اصلی", 'callback_data' => "mainMenu"]]
                ]]);
                sendMessage($msg, $keyboard, "MARKDOWN", $from_id);

                // حذف از دیتابیس
                $stmt = $connection->prepare("DELETE FROM `orders_list` WHERE `uuid` = ?");
                $stmt->bind_param("s", $uuid);
                $stmt->execute();
                $stmt->close();
                continue;
            }

            // --- فراخوانی سیستم هشدار CRM مجزا ---
            if($expiryTime != null && $total != null && $expiryTime >= 0){
                checkAndSendCrmWarning($order, $expiryTime, $total, $totalLeft);
            }elseif(!$enable){
                // اگر غیرفعال بود ولی هنوز وقت داشت، نوتیفیکیشن را جلو بینداز
                $newTIme = $time + 86400 * 2;
                $stmt = $connection->prepare("UPDATE `orders_list` SET `notif`= ? WHERE `uuid`=?");
                $stmt->bind_param("is", $newTIme, $uuid);
                $stmt->execute();
                $stmt->close();
            }
        }
        file_put_contents("warnOffset.txt", $warnOffset + $limit);
    }else unlink('warnOffset.txt');
}


// --- بخش دوم: حذف سرویس‌های منقضی ---
$stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `status`=1 AND `notif` = -1 LIMIT 50");
$stmt->execute();
$orders = $stmt->get_result();
$stmt->close();

if($orders){
    if($orders->num_rows>0){
        while ($order = $orders->fetch_assoc()){
            // --- مقداردهی اولیه متغیرها ---
            $send = false;
            $total = 0; $up = 0; $down = 0; $expiryTime = 0; $totalLeft = 0;
            $found = false; $logedIn = false;
            // -----------------------------
            
            $from_id = $order['userid'];
            $remark = $order['remark'];
            $uuid = $order['uuid']??"0";
            $server_id = $order['server_id'];
            $inbound_id = $order['inbound_id'];
            $notif = $order['notif'];
            
            $stmt = $connection->prepare("SELECT * FROM `server_config` WHERE `id` = ?");
            $stmt->bind_param('i', $server_id);
            $stmt->execute();
            $serverConfig = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            
            if (!$serverConfig) continue;

            $serverType = $serverConfig['type'];
            $panel_url = $serverConfig['panel_url'];

            // چک کردن وضعیت در پنل (مشابه بالا)
            if($serverType == "marzban"){
                $info = getMarzbanUser($server_id, $remark);
                if(isset($info->username)){
                    $found = true;
                    $logedIn = true;
                    $total = $info->data_limit;
                    $totalLeft = $total - $info->used_traffic;
                    $expiryTime = $info->expire;
                }elseif(isset($info->detail)){
                    if($info->detail == "User not found") $logedIn = true;
                }
            }else{
                $response = getJson($server_id); 
                if($response && isset($response->success) && $response->success){
                    $logedIn = true;
                    $response = $response->obj;
                    foreach($response as $row){
                        if($inbound_id == 0) { 
                            $settings = json_decode($row->settings);
                            if(isset($settings->clients) && is_array($settings->clients)){
                                $clientId = isset($settings->clients[0]->id) ? $settings->clients[0]->id : ($settings->clients[0]->password ?? '');
                                $clientEmail = $settings->clients[0]->email ?? '';
                                if($clientId == $uuid || $clientEmail == $uuid || $clientEmail == $remark) {
                                    $total = $row->total;
                                    $up = $row->up;
                                    $down = $row->down;
                                    $expiryTime = substr($row->expiryTime, 0, -3);
                                    $found = true;
                                    break;
                                }
                            }
                        }else{
                            if($row->id == $inbound_id) {
                                $settings = json_decode($row->settings, true); 
                                $clients = $settings['clients'];
                                $clientsStates = $row->clientStats;
                                foreach($clients as $key => $client){
                                     $clientId = isset($client['id']) ? $client['id'] : ($client['password'] ?? '');
                                     $clientEmail = $client['email'] ?? '';
                                     if($clientId == $uuid || $clientEmail == $uuid || $clientEmail == $remark){
                                         $found = true;
                                        $email = $client['email'];
                                        $emails = array_column($clientsStates,'email');
                                        $emailKey = array_search($email,$emails);
                                        if($emailKey !== false){
                                            $total = $client['totalGB'];
                                            $up = $clientsStates[$emailKey]->up;
                                            $down = $clientsStates[$emailKey]->down; 
                                            $expiryTime = substr($clientsStates[$emailKey]->expiryTime, 0, -3);
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    } 
                    if($found){
                        $totalLeft = $total - $up - $down;
                    }
                }
            }
            
            if(!$found && !$logedIn) continue;
            
            $leftgb = round( ($totalLeft) / 1073741824, 2);
            
            // شرط حذف: زمان تمام شده یا حجم تمام شده
            if(((int)$expiryTime > 0 && (int)$expiryTime <= time()) || ($totalLeft != 0 && $leftgb <= 0)) {
                $send = true;
            }

            if($send){
                if($serverType == "marzban") $res = deleteMarzban($server_id, $remark);
                else{
                    if($inbound_id > 0) $res = deleteClient($server_id, $inbound_id, $uuid, 1); 
                    else $res = deleteInbound($server_id, $uuid, 1); 
                }
                
                if(!is_null($res)){
                    $msg = "❌ *اتمام سرویس*
                    
مشترک گرامی: `$remark`
متاسفانه سرویس شما به دلیل اتمام حجم یا زمان منقضی و حذف گردید. 🗑

💡 *همین حالا دوباره وصل شو!*";
                    
                    // دکمه شیشه‌ای اتمام
                    $keyboard = json_encode(['inline_keyboard'=>[
                        [['text'=>"🛒 خرید سرویس جدید", 'callback_data'=>"buySubscription"]],
                        [['text'=>"🏠 منوی اصلی", 'callback_data'=>"mainMenu"]]
                    ]]);

                    sendMessage($msg, $keyboard, "MARKDOWN", $from_id);
                    
                    // حذف از دیتابیس
                    $stmt = $connection->prepare("DELETE FROM `orders_list` WHERE `uuid`=?");
                    $stmt->bind_param("s", $uuid);
                    $stmt->execute();
                    $stmt->close();
                }
            }                
            else{
                // اگر هنوز تمام نشده بود، نوتیفیکیشن را صفر کن تا دوباره در صف بررسی قرار گیرد
                $stmt = $connection->prepare("UPDATE `orders_list` SET `notif`= 0 WHERE `uuid`=?");
                $stmt->bind_param("s", $uuid);
                $stmt->execute();
                $stmt->close();
            }
        }
    }
}
echo "OK";
?>