<?php
/**
 * Auto Delete Messages Cron Job
 * Run every 1 minute
 */

declare(strict_types=1);

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../Database.php';
require_once __DIR__ . '/../Telegram.php';

set_time_limit(60);

$db = Database::getInstance();
$telegram = Telegram::getInstance();

// Get groups with pending deletions
$groups = $db->fetchAll(
    "SELECT id, del FROM `groups` WHERE del IS NOT NULL"
);

foreach ($groups as $group) {
    $deletions = json_decode($group['del'], true);
    
    if (!is_array($deletions) || empty($deletions)) {
        continue;
    }
    
    $changed = false;
    $now = time();
    
    foreach ($deletions as $messageId => $deleteTime) {
        if ($deleteTime <= $now) {
            // Delete message
            $telegram->deleteMessage($group['id'], (int)$messageId);
            unset($deletions[$messageId]);
            $changed = true;
            
            // Sleep to avoid rate limit
            usleep(100000); // 0.1 second
        }
    }
    
    if ($changed) {
        if (empty($deletions)) {
            $db->update('groups', ['del' => null], 'id = ?', [$group['id']]);
        } else {
            $db->update('groups', [
                'del' => json_encode($deletions)
            ], 'id = ?', [$group['id']]);
        }
    }
}

echo "Delete messages cron completed at " . date('Y-m-d H:i:s') . "\n";
