<?php

require_once __DIR__ . '/../core/cron_guard.php';
icylab_require_cron_access();
require_once __DIR__ . '/../core/config.php';
require_once __DIR__ . '/../core/database.php';

if (PHP_SAPI !== 'cli') header('Content-Type: text/plain; charset=utf-8');

$pdo = db();
$failures = array();
$warnings = array();

function pf_line(string $name, bool $ok, string $detail = ''): void
{
    echo ($ok ? 'PASS' : 'FAIL') . ' | ' . $name . ($detail !== '' ? ' | ' . $detail : '') . PHP_EOL;
}

$requiredColumns = array(
    'commercial_closed_at', 'archived_at', 'archived_by_user_id',
    'archive_source', 'archive_exempt_until', 'archive_hold_reason'
);
$stmt = $pdo->prepare("SELECT column_name FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='crm_opportunities'");
$stmt->execute();
$columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
foreach ($requiredColumns as $column) {
    $ok = in_array($column, $columns, true);
    pf_line('crm_opportunities.' . $column, $ok);
    if (!$ok) $failures[] = $column;
}

$stmt = $pdo->query("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='crm_opportunity_lifecycle_history'");
$tableOk = (int)$stmt->fetchColumn() === 1;
pf_line('crm_opportunity_lifecycle_history', $tableOk);
if (!$tableOk) $failures[] = 'crm_opportunity_lifecycle_history';

if (!$failures) {
    $terminalMissing = (int)$pdo->query("SELECT COUNT(*) FROM crm_opportunities WHERE deleted_at IS NULL AND stage IN ('ganada','perdida','facturada') AND commercial_closed_at IS NULL")->fetchColumn();
    pf_line('terminales con cierre comercial', $terminalMissing === 0, 'faltantes=' . $terminalMissing);
    if ($terminalMissing > 0) $failures[] = 'terminal_without_commercial_close';

    $archivedActive = (int)$pdo->query("SELECT COUNT(*) FROM crm_opportunities WHERE deleted_at IS NULL AND archived_at IS NOT NULL AND stage IN ('nuevo','contactado','cotizando','negociacion')")->fetchColumn();
    pf_line('archivadas en etapa activa', $archivedActive === 0, 'inconsistentes=' . $archivedActive);
    if ($archivedActive > 0) $warnings[] = 'archived_active_stage';

    $invoicedInvalid = (int)$pdo->query("SELECT COUNT(*) FROM crm_opportunities o WHERE o.deleted_at IS NULL AND o.archived_at IS NOT NULL AND o.closure_outcome='invoiced' AND NOT EXISTS (SELECT 1 FROM facto_documents f WHERE (f.document_id=o.facto_document_id OR f.crm_opportunity_id=o.id) AND f.received_issued_flag=1 AND f.document_status=1 AND COALESCE(f.payment_status,'')<>'anulado' AND COALESCE(f.document_type_taxbureau,'') NOT IN ('61','801'))")->fetchColumn();
    pf_line('facturadas archivadas con DTE vigente', $invoicedInvalid === 0, 'sin respaldo=' . $invoicedInvalid);
    if ($invoicedInvalid > 0) $warnings[] = 'archived_invoiced_without_valid_dte';

    $visible = (int)$pdo->query("SELECT COUNT(*) FROM crm_opportunities WHERE deleted_at IS NULL AND archived_at IS NULL")->fetchColumn();
    $archived = (int)$pdo->query("SELECT COUNT(*) FROM crm_opportunities WHERE deleted_at IS NULL AND archived_at IS NOT NULL")->fetchColumn();
    pf_line('conteo de oportunidades', true, 'kanban=' . $visible . ', archivadas=' . $archived);
}

$settings = array('crm_month_end_archive_enabled','crm_month_end_archive_day','crm_month_end_archive_require_valid_dte');
foreach ($settings as $setting) {
    try {
        $stmt = $pdo->prepare("SELECT setting_value FROM dashboard_settings WHERE setting_key=? AND status='approved' LIMIT 1");
        $stmt->execute(array($setting));
        $value = $stmt->fetchColumn();
        $ok = $value !== false;
        pf_line('setting ' . $setting, $ok, $ok ? (string)$value : 'ausente');
        if (!$ok) $failures[] = $setting;
    } catch (Throwable $e) {
        pf_line('setting ' . $setting, false, $e->getMessage());
        $failures[] = $setting;
    }
}

echo PHP_EOL;
if ($failures) {
    echo 'PREFLIGHT FAIL | Corrige antes de habilitar produccion.' . PHP_EOL;
    exit(1);
}
if ($warnings) {
    echo 'PREFLIGHT PASS WITH WARNINGS | ' . implode(', ', $warnings) . PHP_EOL;
    exit(0);
}
echo 'PREFLIGHT PASS | Esquema y reglas criticas operativas.' . PHP_EOL;
