<?php
/**
 * Cron Job: Service Synchronization
 * Syncs services from MrGoViral every hour
 * 
 * Setup with cPanel:
 * Run every hour: 0 * * * * /usr/bin/php /home/kagujje/public_html/cronjobs/sync_services.php
 */

// Set script timeout to 5 minutes
set_time_limit(300);

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

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

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

try {
    // Initialize database
    $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,
            \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC
        ]
    );
    
    // Load sync controller
    require_once __DIR__ . '/../app/controller/SyncController.php';
    $syncController = new \App\Controller\SyncController($db);
    
    // Run sync
    $result = $syncController->syncServices();
    
    if ($result['success']) {
        fwrite($log, "[" . date('Y-m-d H:i:s') . "] ✅ Sync completed\n");
        fwrite($log, "  - Added: {$result['added']}\n");
        fwrite($log, "  - Updated: {$result['updated']}\n");
        fwrite($log, "  - Removed: {$result['removed']}\n");
    } else {
        fwrite($log, "[" . date('Y-m-d H:i:s') . "] ❌ Sync failed: {$result['error']}\n");
    }
    
} catch (\Exception $e) {
    fwrite($log, "[" . date('Y-m-d H:i:s') . "] ❌ Error: " . $e->getMessage() . "\n");
}

fwrite($log, "[" . date('Y-m-d H:i:s') . "] Sync completed\n\n");
fclose($log);

exit(0);
?>
