<?php

define("IN_SITE", true);

$hash_d1e8a4 = '18c2d09000a8bb37d2958a746eaddc7cb0faafd567922223cac62da72f62b8b2';
if (!function_exists('verify_license_integrity_d1e8a4')) {
    function verify_license_integrity_d1e8a4($expectedHash)
    {
        static $verified = false;
        if ($verified) {
            return;
        }
        $licenseFile = __DIR__ . '/../models/is_license.php';
        if (!is_file($licenseFile) || hash_file('sha256', $licenseFile) !== $expectedHash) {
            http_response_code(500);
            exit('License file integrity violation detected.');
        }
        $verified = true;
    }
}
verify_license_integrity_d1e8a4($hash_d1e8a4);
unset($hash_d1e8a4);

require_once(__DIR__.'/../libs/db.php');
require_once(__DIR__.'/../config.php');
require_once(__DIR__.'/../libs/helper.php');
$CMSNT = new DB();

if($CMSNT->site('pin_cron') != ''){
    if(empty($_GET['pin'])){
        die('Vui lòng nhập mã PIN');
    }
    if($_GET['pin'] != $CMSNT->site('pin_cron')){
        die('Mã PIN không chính xác');
    }
}

/* START CHỐNG SPAM */
if (time() > $CMSNT->site('check_time_cron_checklivefb')) {
    if (time() - $CMSNT->site('check_time_cron_checklivefb') < 3) {
        die('Thao tác quá nhanh, vui lòng đợi');
    }
}

/* Cập nhật thời gian chạy cron */
$CMSNT->update("settings", [
    'value' => time()
], " `name` = 'check_time_cron_checklivefb' ");

// Khởi tạo
$uids = [];
$products_info = [];
$where_is_checklive = "";

$products_list = $CMSNT->get_list_safe("SELECT * FROM `products` WHERE `checklive` = 1");
if (empty($products_list)) {
    die('Không có sản phẩm nào bật check live');
}

$product_ids = array_column($products_list, 'id');
$product_ids_str = implode(',', array_map('intval', $product_ids));
$where_is_checklive = " AND `product_id` IN ($product_ids_str)";

$products = $CMSNT->get_list_safe("SELECT * FROM `accounts` WHERE `buyer` IS NULL AND `status` = 'LIVE' $where_is_checklive ORDER BY `time_live` ASC LIMIT 200 ");

foreach ($products as $product) {
    // Làm sạch UID: chỉ giữ chữ số để tránh ký tự ẩn gây lỗi
    $raw_uid = explode("|", (string)$product['account'])[0];
    $uid = preg_replace('/[^0-9]/', '', $raw_uid);

    if ($uid === '') {
        continue; // Bỏ qua UID không hợp lệ
    }

    if (!isset($products_info[$uid])) {
        $uids[] = $uid;
        $products_info[$uid] = $product;
    }
}

if (empty($uids)) {
    die('Không có UID để kiểm tra.');
}

$mh = curl_multi_init();
$curl_handles = [];

foreach ($uids as $uid) {
    $ch = curl_init();
    $url = "https://graph.facebook.com/v18.0/{$uid}/picture?redirect=0";
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_NOSIGNAL => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4
    ]);
    curl_multi_add_handle($mh, $ch);
    $curl_handles[$uid] = $ch;
}

$running = 0;
do {
    do {
        $mrc = curl_multi_exec($mh, $running);
    } while ($mrc === CURLM_CALL_MULTI_PERFORM);

    if ($running) {
        $sel = curl_multi_select($mh, 1.0);
        if ($sel === -1) usleep(10000);
    }
} while ($running && $mrc === CURLM_OK);

foreach ($curl_handles as $uid => $ch) {
    $result = curl_multi_getcontent($ch);
    $info = curl_getinfo($ch);
    $error = curl_error($ch);

    echo "<hr>";
    echo "👉 UID: <strong>" . substr($uid, 0, 10) . "..." . "</strong><br>";
    echo "📦 HTTP CODE: " . $info['http_code'] . "<br>";
    echo "🐞 CURL ERROR: " . ($error ?: 'Không có') . "<br>";
    echo "📄 RESPONSE: <pre>" . htmlspecialchars($result) . "</pre>";

    if ($info['http_code'] == 200) {
        $result_array = json_decode($result, true);
        if (isset($result_array['data']) && (!empty($result_array['data']['height']) || !empty($result_array['data']['width']))) {
            $CMSNT->update("accounts", [
                'status'    => 'LIVE',
                'time_live' => time()
            ], " `id` = '".$products_info[$uid]['id']."' ");
            echo "<span style='color:green;'>✅ LIVE</span><br>";
        } else {
            $CMSNT->update("accounts", [
                'status'    => 'DIE',
                'time_live' => time()
            ], " `id` = '".$products_info[$uid]['id']."' ");
            echo "<span style='color:red;'>❌ DIE</span><br>";
        }
    } else {
        echo "<span style='color:orange;'>⚠️ Không thể kiểm tra</span><br>";
    }

    curl_multi_remove_handle($mh, $ch);
    curl_close($ch);
}

curl_multi_close($mh);
