<?php
// cron.php — gmail auto-delete + secure wipe
// RUN CRON: */5 * * * * php /var/www/html/cron/cron.php

require __DIR__ . '/../db.php';
require __DIR__ . '/../bot_functions.php';
$config = require __DIR__ . '/../config.php';

function tApi($method, $params = []) {
    global $config;
    $url = "https://api.telegram.org/bot{$config['bot_token']}/{$method}";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $r = curl_exec($ch);
    curl_close($ch);
    return $r;
}

/** ---------------- DELETE OTP + ALERTS ---------------- */

$now = date('Y-m-d H:i:s');

// fetch expired messages
$q = $pdo->prepare("SELECT * FROM gmail_notifications WHERE delete_at <= ?");
$q->execute([$now]);
$rows = $q->fetchAll();

foreach ($rows as $r) {
    $chat  = (int)$r['chat_id'];
    $mid   = (int)$r['message_id'];
    $type  = $r['type']; // otp or notice

    // delete telegram msg
    tApi('deleteMessage', [
        'chat_id'    => $chat,
        'message_id' => $mid
    ]);

    // delete row
    $pdo->prepare("DELETE FROM gmail_notifications WHERE id = ?")->execute([$r['id']]);
}


/** ---------------- HANDLE GMAIL DELETED WIPE ---------------- */
// when Gmail deleted: remove all old OTP/security alerts preventing inline delete usage

// this flag gets set in webhook upon: "Gmail Deleted"
$q2 = $pdo->prepare("
    SELECT a.gmail, u.telegram_id
    FROM accounts a
    JOIN users u ON a.owner_id = u.id
    WHERE gmail_status = 'none' AND gmail IS NOT NULL
");
$q2->execute();
$deleted = $q2->fetchAll();

foreach ($deleted as $d) {
    $gmail = $d['gmail'];
    $chat  = $d['telegram_id'];

    // wipe all linked OTP + notices
    $wipe = $pdo->prepare("
        SELECT message_id FROM gmail_notifications WHERE user_id = (
            SELECT id FROM users WHERE telegram_id = ? LIMIT 1
        )
    ");
    $wipe->execute([$chat]);
    $msgs = $wipe->fetchAll();

    foreach ($msgs as $m) {
        tApi('deleteMessage', [
            'chat_id'    => $chat,
            'message_id' => (int)$m['message_id']
        ]);
    }

    // clear rows
    $pdo->prepare("
        DELETE FROM gmail_notifications WHERE user_id = (
            SELECT id FROM users WHERE telegram_id = ? LIMIT 1
        )
    ")->execute([$chat]);

    // block tapping old inline deletes
    $pdo->prepare("UPDATE accounts SET gmail_status = 'none' WHERE gmail = ?")->execute([$gmail]);

    // instant remove "Password changed" older popup
    tApi('sendMessage', [
        'chat_id' => $chat,
        'text'    => "⚠️ This Gmail is deleted — old OTP / security messages are now invalid.",
        'parse_mode' => 'HTML'
    ]);
}

echo "Cron OK @ ".date('H:i:s');