<?php

if (PHP_SAPI !== 'cli') {
    http_response_code(404);
    exit;
}

require_once __DIR__ . '/../core/config.php';
require_once __DIR__ . '/../core/database.php';
require_once __DIR__ . '/../services/crm/QuoteInvoiceReconciliationService.php';

$options = getopt('', array('env:', 'limit::', 'apply::'));
$environment = strtolower(trim((string)($options['env'] ?? 'production')));
$limit = max(1, min(10000, (int)($options['limit'] ?? 1000)));
$confirmation = trim((string)($options['apply'] ?? ''));

if (!in_array($environment, array('sandbox', 'production'), true)) {
    fwrite(STDERR, "ERROR: --env must be sandbox or production.\n");
    exit(2);
}

$pdo = db();
$countStmt = $pdo->prepare("
    SELECT COUNT(*)
    FROM facto_documents
    WHERE environment=?
      AND received_issued_flag=1
      AND document_status=1
      AND document_type_id IN (2,32,46)
      AND COALESCE(payment_status,'')<>'anulado'
");
$countStmt->execute(array($environment));
$candidateCount = (int)$countStmt->fetchColumn();

if ($confirmation !== 'RECONCILE_QUOTES') {
    echo "Candidate invoices: " . $candidateCount . PHP_EOL;
    echo "No changes applied. Re-run with --apply=RECONCILE_QUOTES after reviewing the backup and preflight.\n";
    exit(0);
}

$stmt = $pdo->prepare("
    SELECT document_id
    FROM facto_documents
    WHERE environment=?
      AND received_issued_flag=1
      AND document_status=1
      AND document_type_id IN (2,32,46)
      AND COALESCE(payment_status,'')<>'anulado'
    ORDER BY issue_date ASC, id ASC
    LIMIT " . $limit . "
");
$stmt->execute(array($environment));

$service = new QuoteInvoiceReconciliationService($pdo);
$summary = array('processed' => 0, 'matched' => 0, 'changed' => 0, 'ambiguous' => 0, 'unmatched' => 0, 'errors' => 0);

foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $documentId) {
    $summary['processed']++;
    try {
        $result = $service->reconcileDocument($environment, (string)$documentId, true);
        if (!empty($result['matched'])) {
            $summary['matched']++;
            if (!empty($result['status_changed'])) {
                $summary['changed']++;
            }
        } elseif (!empty($result['ambiguous'])) {
            $summary['ambiguous']++;
        } else {
            $summary['unmatched']++;
        }
    } catch (Throwable $e) {
        $summary['errors']++;
        fwrite(STDERR, 'ERROR document ' . $documentId . ': ' . $e->getMessage() . PHP_EOL);
    }
}

echo json_encode($summary, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL;
exit($summary['errors'] > 0 ? 1 : 0);
