<?php
// Run in browser:
// /fix_lead_success_from_payments.php?key=secret123
// Dry run:
// /fix_lead_success_from_payments.php?key=secret123&dry_run=1

if (php_sapi_name() !== 'cli') {
    $expectedKey = getenv('MAINTENANCE_KEY') ?: 'secret123';
    if (($_GET['key'] ?? '') !== $expectedKey) {
        http_response_code(403);
        die('Access Denied');
    }
}

require_once __DIR__ . '/../vendor/autoload.php';
$app = require_once __DIR__ . '/../app/bootstrap.php';

header('Content-Type: text/plain; charset=UTF-8');

try {
    $dryRun = (($_GET['dry_run'] ?? '0') === '1');

    if ($dryRun) {
        $pdo = $app->db->getPdo();
        $countSql = "
            SELECT COUNT(DISTINCT p.didar_contact_id)
            FROM persons p
            INNER JOIN deals d ON d.contact_didar_id = p.didar_contact_id
            INNER JOIN transactions t ON t.deal_id = d.id
            WHERE COALESCE(p.sale_status, 0) <> 1
              AND t.status = 'confirmed'
              AND COALESCE(t.amount, 0) > 0
        ";
        $eligible = (int)$pdo->query($countSql)->fetchColumn();

        echo "DRY RUN\n";
        echo "Eligible leads to update: {$eligible}\n";
        echo "No changes applied.\n";
        exit;
    }

    $result = $app->services->deal->backfillLeadSaleStatusFromSuccessfulPayments();
    echo "DONE\n";
    echo "Eligible leads: " . ($result['eligible'] ?? 0) . "\n";
    echo "Updated leads: " . ($result['updated'] ?? 0) . "\n";
} catch (\Throwable $e) {
    http_response_code(500);
    echo "ERROR\n";
    echo $e->getMessage() . "\n";
}
