<?php
declare(strict_types=1);

require_once __DIR__ . '/_bootstrap.php';

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

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

    $customers = $master->query(
        "SELECT *
         FROM customers
         WHERE COALESCE(license_status, 'active') = 'active'"
    )->fetchAll() ?: [];

    $generated = 0;
    $skipped = 0;
    $errors = [];

    foreach ($customers as $customer) {
        try {
            $customerId = (int)($customer['id'] ?? 0);
            if ($customerId <= 0) {
                continue;
            }
            if (!golder_customer_plan_feature_enabled($customer, 'BACKUP_AUTO')) {
                $skipped++;
                continue;
            }

            $tenant = golder_tenant_pdo_from_customer($customer);
            $profiles = $tenant->query("SELECT id FROM profiles WHERE COALESCE(is_deleted, 0) = 0")->fetchAll() ?: [];

            foreach ($profiles as $profileRow) {
                $profileId = trim((string)($profileRow['id'] ?? ''));
                if ($profileId === '') {
                    continue;
                }

                $st = $master->prepare(
                    "SELECT COUNT(*)
                     FROM backup_files
                     WHERE customer_id = :cid
                       AND profile_id = :pid
                       AND backup_type = 'auto'
                       AND DATE(created_at) = UTC_DATE()"
                );
                $st->execute([':cid' => $customerId, ':pid' => $profileId]);
                if ((int)$st->fetchColumn() > 0) {
                    $skipped++;
                    continue;
                }

                $res = golder_create_profile_backup($master, $customer, $profileId, 'auto');
                if (!empty($res['ok'])) {
                    $generated++;
                } else {
                    $errors[] = [
                        'customer_id' => $customerId,
                        'profile_id' => $profileId,
                        'message' => (string)($res['message'] ?? 'unknown'),
                    ];
                }
            }
        } catch (Throwable $e) {
            $errors[] = [
                'customer_id' => (int)($customer['id'] ?? 0),
                'message' => $e->getMessage(),
            ];
        }
    }

    golder_job_finish($master, $jobId, 'ok', [
        'generated' => $generated,
        'skipped' => $skipped,
        'error_count' => count($errors),
        'errors' => array_slice($errors, 0, 20),
    ]);
    echo "cron_backup finished. generated={$generated} skipped={$skipped}\n";
} catch (Throwable $e) {
    golder_job_finish($master, $jobId, 'error', ['error' => $e->getMessage()]);
    echo "cron_backup failed: {$e->getMessage()}\n";
    exit(1);
}


