<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/scheduled_db_backup.php';

$bk = scheduled_db_backup_run($pdo, 50);
if (!empty($bk['ok'])) {
    echo date('c') . ' Database backup OK: ' . basename((string) $bk['local_file']) . "\n";
    if ($bk['ftp_ok'] !== null) {
        echo date('c') . ' FTP: ' . ($bk['ftp_ok'] ? 'OK' : 'FAIL') . ' — ' . ($bk['ftp_message'] ?? '') . "\n";
    }
} else {
    echo date('c') . ' Database backup FAILED: ' . ($bk['local_error'] ?? 'unknown') . "\n";
}

require_once __DIR__ . '/../includes/scheduled_files_backup.php';
$f = scheduled_files_backup_run($pdo, false);
if (empty($f['skipped'])) {
    $ts = date('c');
    echo $ts . ' FILES_FTP: ' . ($f['ok'] ? 'OK' : 'FAIL') . ' — ' . ($f['message'] ?? '') . "\n";
}

require_once __DIR__ . '/../includes/smm_api.php';

$stmt = $pdo->query("SELECT setting_value FROM app_settings WHERE setting_key = 'smm_api_key'");
$smmApiKey = $stmt->fetchColumn();

if (empty($smmApiKey)) {
    exit("SMM API Key not configured\n");
}

$stmt = $pdo->query("SELECT setting_value FROM app_settings WHERE setting_key = 'smm_orders'");
$smmOrdersData = $stmt->fetchColumn();
$smmOrders = [];
if ($smmOrdersData) {
    $smmOrders = json_decode($smmOrdersData, true) ?: [];
}

if (empty($smmOrders)) {
    exit("No SMM orders to check\n");
}

$api = new SMMApi($smmApiKey);
$orderIds = [];
foreach ($smmOrders as $orderId => $smmOrderData) {
    if (isset($smmOrderData['smm_order_id'])) {
        $orderIds[] = $smmOrderData['smm_order_id'];
    }
}

if (empty($orderIds)) {
    exit("No valid SMM order IDs found\n");
}

$statuses = $api->multiStatus($orderIds);

if (!$statuses) {
    exit("Failed to fetch order statuses\n");
}

$updated = false;
foreach ($smmOrders as $orderId => &$smmOrderData) {
    if (!isset($smmOrderData['smm_order_id'])) {
        continue;
    }
    
    $smmOrderId = $smmOrderData['smm_order_id'];
    
    if (isset($statuses->$smmOrderId)) {
        $status = $statuses->$smmOrderId;
        
        if (isset($status->error)) {
            continue;
        }
        
        $smmOrderData['status'] = $status->status ?? 'Unknown';
        $smmOrderData['charge'] = $status->charge ?? null;
        $smmOrderData['remains'] = $status->remains ?? null;
        $smmOrderData['start_count'] = $status->start_count ?? null;
        $smmOrderData['currency'] = $status->currency ?? 'USD';
        $smmOrderData['last_checked'] = date('Y-m-d H:i:s');
        
        if ($status->status === 'Completed') {
            $stmt = $pdo->prepare("UPDATE orders SET status = 'completed' WHERE id = ? AND status = 'pending'");
            $stmt->execute([$orderId]);
        } elseif ($status->status === 'Cancelled') {
            $stmt = $pdo->prepare("UPDATE orders SET status = 'cancelled' WHERE id = ? AND status = 'pending'");
            $stmt->execute([$orderId]);
        }
        
        $updated = true;
    }
}

if ($updated) {
    $stmt = $pdo->prepare("INSERT INTO app_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
    $stmt->execute(['smm_orders', json_encode($smmOrders), json_encode($smmOrders)]);
    echo "SMM orders status updated successfully\n";
} else {
    echo "No updates needed\n";
}
?>

