<?php
require_once __DIR__ . '/../db.php';

$chk = $conn->query("SELECT telegram_enabled FROM notification_settings WHERE id=1")->fetch_assoc();
if (!$chk || !$chk['telegram_enabled']) exit;

date_default_timezone_set('Asia/Kolkata');
file_put_contents(__DIR__.'/cron_test.log', date('Y-m-d H:i:s')."\n", FILE_APPEND);

define('TG_BOT_TOKEN', '8523225338:AAGOzt1Wf6Hq6Gb8IYNAieNFYW_vdgHMrFQ');
define('TG_CHAT_ID', '895411165');

function tg_send($text) {
    file_get_contents(
        "https://api.telegram.org/bot" . TG_BOT_TOKEN . "/sendMessage?" .
        http_build_query([
            'chat_id' => TG_CHAT_ID,
            'text' => $text
        ])
    );
}

$now = date('Y-m-d H:i:s');
$chk = $conn->query("SELECT telegram_enabled FROM notification_settings WHERE id=1")->fetch_assoc();
if (!$chk || (int)$chk['telegram_enabled'] === 0) {
    exit;
}

$res = $conn->query("
SELECT 
    v.unit_id,
    v.current_ip,
    g.name AS group_name,
    r.name AS rdp_name
FROM vms v
JOIN rdps r ON r.id = v.rdp_id
JOIN groups g ON g.id = r.group_id
WHERE LOWER(v.status) = 'blocked'
");
while ($r = $res->fetch_assoc()) {
    tg_send(
        "IP BLOCKED\n" .
        "Group: {$r['group_name']}\n" .
        "RDP: {$r['rdp_name']}\n" .
        "VM: {$r['unit_id']}\n" .
        "IP: {$r['current_ip']}\n" .
        "Time: {$now}"
    );
}

$res = $conn->query("
SELECT 
    v.unit_id,
    v.current_ip,
    g.name AS group_name,
    r.name AS rdp_name
FROM vms v
JOIN rdps r ON r.id = v.rdp_id
JOIN groups g ON g.id = r.group_id
WHERE v.last_heartbeat IS NULL
   OR v.last_heartbeat < CONVERT_TZ(NOW(), @@session.time_zone, '+05:30') - INTERVAL 30 MINUTE
");
while ($r = $res->fetch_assoc()) {
    tg_send(
        "VM OFFLINE\n" .
        "Group: {$r['group_name']}\n" .
        "RDP: {$r['rdp_name']}\n" .
        "VM: {$r['unit_id']}\n" .
        "IP: {$r['current_ip']}\n" .
        "Time: {$now}"
    );
}

$res = $conn->query("
SELECT 
    v.unit_id,
    v.current_ip,
    g.name AS group_name,
    r.name AS rdp_name
FROM vms v
JOIN rdps r ON r.id = v.rdp_id
JOIN groups g ON g.id = r.group_id
LEFT JOIN (
    SELECT earnapp_token, MAX(redeem_balance) t
    FROM earnapp_history
    WHERE DATE(recorded_at) = CURDATE()
    GROUP BY earnapp_token
) td ON td.earnapp_token = v.earnapp_token
LEFT JOIN (
    SELECT earnapp_token, MAX(redeem_balance) y
    FROM earnapp_history
    WHERE DATE(recorded_at) = CURDATE() - INTERVAL 1 DAY
    GROUP BY earnapp_token
) yd ON yd.earnapp_token = v.earnapp_token
WHERE IFNULL(td.t,0) = 0
  AND IFNULL(yd.y,0) > 0
");
while ($r = $res->fetch_assoc()) {
    tg_send(
        "ZERO EARNING TODAY\n" .
        "Group: {$r['group_name']}\n" .
        "RDP: {$r['rdp_name']}\n" .
        "VM: {$r['unit_id']}\n" .
        "IP: {$r['current_ip']}\n" .
        "Time: {$now}"
    );
}