<?php
/**
 * Cron Job: Order Status Synchronization
 * Syncs order status from MrGoViral every 15 minutes
 * 
 * Setup with cPanel:
 * */15 * * * * /usr/bin/php /home/kagujje/public_html/cronjobs/sync_order_status.php
 */

set_time_limit(180);

require_once __DIR__ . '/../app/config.php';

$logFile = __DIR__ . '/logs/order_sync.log';
if (!is_dir(dirname($logFile))) {
    mkdir(dirname($logFile), 0755, true);
}

$log = fopen($logFile, 'a');
fwrite($log, "[" . date('Y-m-d H:i:s') . "] Syncing order status...\n");

try {
    $db = new \PDO(
        'mysql:host=' . getenv('DB_HOST') . ';dbname=' . getenv('DB_NAME') . ';charset=utf8mb4',
        getenv('DB_USER'),
        getenv('DB_PASS'),
        [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]
    );
    
    // Load API class
    require_once __DIR__ . '/../app/classes/API/MrGoViralAPI.php';
    $api = new \App\Classes\API\MrGoViralAPI();
    
    // Get pending orders from last 7 days
    $stmt = $db->query('
        SELECT id, order_id, status 
        FROM orders 
        WHERE status NOT IN ("completed", "cancelled", "refunded")
        AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
        LIMIT 100
    ');
    $orders = $stmt->fetchAll(\PDO::FETCH_ASSOC);
    
    $updated = 0;
    $completed = 0;
    $failed = 0;
    
    foreach ($orders as $order) {
        try {
            // Get status from provider
            $response = $api->getOrderStatus($order['order_id']);
            
            if ($response['success']) {
                $newStatus = $response['status'];
                
                // Only update if status changed
                if ($newStatus !== $order['status']) {
                    $updateStmt = $db->prepare('
                        UPDATE orders 
                        SET status = ?, updated_at = NOW() 
                        WHERE id = ?
                    ');
                    $updateStmt->execute([$newStatus, $order['id']]);
                    $updated++;
                    
                    if ($newStatus === 'completed') {
                        $completed++;
                    }
                    
                    fwrite($log, "  ✓ Order {$order['order_id']}: $newStatus\n");
                }
            } else {
                $failed++;
                fwrite($log, "  ✗ Failed to get status for order {$order['order_id']}\n");
            }
            
        } catch (\Exception $e) {
            $failed++;
            fwrite($log, "  ✗ Error: " . $e->getMessage() . "\n");
        }
        
        // Rate limiting
        usleep(100000); // 100ms delay between requests
    }
    
    fwrite($log, "[" . date('Y-m-d H:i:s') . "] Completed - Updated: $updated, Completed: $completed, Failed: $failed\n\n");
    
} catch (\Exception $e) {
    fwrite($log, "[" . date('Y-m-d H:i:s') . "] ❌ Error: " . $e->getMessage() . "\n\n");
}

fclose($log);
exit(0);
?>
