<?php
declare(strict_types=1);

require_once __DIR__ . '/_bootstrap.php';

$master = golder_master_pdo();
$jobId = golder_job_start($master, 'cron_license_audit');

try {
    golder_ensure_customers_columns($master);
    golder_ensure_plan_tables($master);

    $customers = $master->query('SELECT * FROM customers')->fetchAll() ?: [];
    $expiredCount = 0;
    $activeCount = 0;
    $demoExpiredCount = 0;

    $updateStatus = $master->prepare(
        'UPDATE customers
         SET license_status = :status
         WHERE id = :id'
    );

    foreach ($customers as $customer) {
        $customerId = (int)($customer['id'] ?? 0);
        if ($customerId <= 0) {
            continue;
        }

        $currentStatus = strtolower(trim((string)($customer['license_status'] ?? 'active')));
        $nextStatus = $currentStatus !== '' ? $currentStatus : 'active';

        if ((int)($customer['is_demo'] ?? 0) === 1 && golder_is_expired_datetime((string)($customer['demo_expires_at'] ?? ''))) {
            $nextStatus = 'expired';
        } elseif (!in_array($currentStatus, ['cancelled', 'suspended'], true)) {
            $nextStatus = golder_customer_desktop_access_expired($customer) ? 'expired' : 'active';
        }

        if ($nextStatus === $currentStatus) {
            continue;
        }

        $updateStatus->execute([
            ':status' => $nextStatus,
            ':id' => $customerId,
        ]);

        if ($nextStatus === 'expired') {
            $expiredCount++;
            if ((int)($customer['is_demo'] ?? 0) === 1) {
                $demoExpiredCount++;
            }
        } elseif ($nextStatus === 'active') {
            $activeCount++;
        }
    }

    golder_job_finish($master, $jobId, 'ok', [
        'expired_marked' => $expiredCount,
        'active_marked' => $activeCount,
        'demo_expired_marked' => $demoExpiredCount,
    ]);

    echo "cron_license_audit finished.\n";
} catch (Throwable $e) {
    golder_job_finish($master, $jobId, 'error', ['error' => $e->getMessage()]);
    echo "cron_license_audit failed: {$e->getMessage()}\n";
    exit(1);
}
