<?php
// ============================================================
//  cron/email-sync.php — pull new mail from every active mailbox
// ============================================================
//
//  Schedule (cPanel cron):
//    */5 * * * * curl -s "https://buylocallowveld.elegantwork.co.za/cron/email-sync.php?secret=EWG-BUYLOCAL"
//
//  Or via PHP CLI (no secret needed):
//    */5 * * * * php /path/to/cron/email-sync.php
//
//  Safe to run concurrently — each account has independent state.
//  But to keep things tidy we use a per-run lock so two parallel
//  cron firings don't both try to sync the same mailbox.
// ============================================================

require_once __DIR__ . '/_bootstrap.php';
require_once __DIR__ . '/../includes/email_sync.php';

// Increase time limit — full historical sync of a big inbox can take minutes.
@set_time_limit(0);
@ignore_user_abort(true);

// Acquire lock so concurrent cron runs don't trample each other
$lock_file = sys_get_temp_dir() . '/buylocal-email-sync.lock';
$lock = @fopen($lock_file, 'c');
if ($lock && !@flock($lock, LOCK_EX | LOCK_NB)) {
    echo "Another sync is already running. Exiting.\n";
    exit(0);
}

$started = microtime(true);
echo "Email sync started: " . date('Y-m-d H:i:s') . "\n";

$results = email_sync_all_active();

foreach ($results as $account_id => $r) {
    $acct = db_row('SELECT email_address FROM email_accounts WHERE id=:id', ['id' => $account_id]);
    $email = $acct['email_address'] ?? "#$account_id";
    if ($r['ok']) {
        echo "  ✓ {$email}: {$r['message']}";
        if ($r['evicted_count'] > 0) echo " ({$r['evicted_count']} body evictions)";
        echo "\n";
    } else {
        echo "  ✗ {$email}: {$r['message']}\n";
    }
}

$elapsed = round(microtime(true) - $started, 1);
echo "Done in {$elapsed}s\n";

if ($lock) {
    @flock($lock, LOCK_UN);
    @fclose($lock);
}