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

$lockFile = __DIR__ . '/cron.lock';
$logFile  = __DIR__ . '/log.txt';

// جلوگیری از اجرای هم‌زمان
if (file_exists($lockFile) && time() - filemtime($lockFile) < 110) {
    exit;
}
file_put_contents($lockFile, time());

// پاک کردن لاگ هر ۳ روز
if (file_exists($logFile) && time() - filemtime($logFile) > 259200) {
    file_put_contents($logFile, '');
}

// اتصال به دیتابیس
try {
    $conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8", DB_USER, DB_PASS);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    logToFile("❌ DB Error: " . $e->getMessage());
    unlink($lockFile);
    exit;
}

// زمان فعلی
$time = time();
$limit = 300;

$stmt = $conn->prepare("SELECT * FROM del WHERE timeDel < :time LIMIT $limit");
$stmt->execute(['time' => $time]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($rows as $row) {
    $chat_id    = $row['from_id'];
    $message_id = $row['message_id'];
    $row_id     = $row['id'];

    $success = false;
    $errorMsg = '';

    for ($attempt = 1; $attempt <= 3; $attempt++) {
        $response = sendDeleteRequest($chat_id, $message_id);
        $httpCode = $response['code'];
        $body     = $response['body'];

        if ($httpCode == 200 && strpos($body, '"ok":true') !== false) {
            $success = true;
            break;
        } else {
            $errorJson = json_decode($body, true);
            $errorMsg = $errorJson['description'] ?? 'Unknown error';
            sleep(1); // صبر برای تلاش بعدی
        }
    }

    $logTime = date("Y-m-d H:i:s");

    if ($success) {
        $delStmt = $conn->prepare("DELETE FROM del WHERE id = :id");
        $delStmt->execute(['id' => $row_id]);
        logToFile("✅ [$logTime] Deleted message_id $message_id from chat_id $chat_id after $attempt attempt(s)");
    } else {
        logToFile("❌ [$logTime] Failed to delete message_id $message_id from chat_id $chat_id after 3 attempts | Error: $errorMsg");
    }
}

unlink($lockFile);
echo "Done.\n";

// تابع ثبت لاگ
function logToFile($msg) {
    global $logFile;
    file_put_contents($logFile, $msg . "\n", FILE_APPEND);
}

// تابع حذف پیام با curl
function sendDeleteRequest($chat_id, $message_id) {
    $token = API_TOKEN;
    $url = "https://api.telegram.org/bot$token/deleteMessage";
    $postData = ['chat_id' => $chat_id, 'message_id' => $message_id];

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $postData,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_TIMEOUT        => 10
    ]);
    $responseBody = curl_exec($ch);
    $httpCode     = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return ['code' => $httpCode, 'body' => $responseBody];
}