<?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 line_v85(string $name, bool $ok, string $detail=''): void {
    echo ($ok ? 'PASS' : 'FAIL') . ' | ' . $name . ($detail!=='' ? ' | '.$detail : '') . PHP_EOL;
}

$requiredCustomerColumns = array('restock_cycle_source','restock_confidence','restock_observations','last_purchase_date','customer_lifecycle_status','customer_lifecycle_updated_at');
$columns = $pdo->query("SELECT column_name FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='crm_customers'")->fetchAll(PDO::FETCH_COLUMN);
foreach ($requiredCustomerColumns as $column) {
    $ok=in_array($column,$columns,true); line_v85('crm_customers.'.$column,$ok); if(!$ok)$failures[]=$column;
}
$oppColumns = $pdo->query("SELECT column_name FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='crm_opportunities'")->fetchAll(PDO::FETCH_COLUMN);
$ok=in_array('restock_forecast_id',$oppColumns,true); line_v85('crm_opportunities.restock_forecast_id',$ok); if(!$ok)$failures[]='restock_forecast_id';
$tableOk=(int)$pdo->query("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='crm_restock_forecasts'")->fetchColumn()===1;
line_v85('crm_restock_forecasts',$tableOk); if(!$tableOk)$failures[]='crm_restock_forecasts';

$restockDefault=$pdo->query("SELECT column_default FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='crm_customers' AND column_name='restock_days' LIMIT 1")->fetchColumn();
$defaultOk=$restockDefault===null;
line_v85('restock_days default NULL',$defaultOk,'default=' . ($restockDefault===null?'NULL':(string)$restockDefault)); if(!$defaultOk)$failures[]='restock_days_default';

$forceSync=file_get_contents(__DIR__.'/../api/dashboard/force_sync_facto.php');
$decoupled=strpos($forceSync,'INSERT INTO crm_opportunities')===false && strpos($forceSync,"decoupled_daily_bi_job")!==false;
line_v85('FACTO desacoplado del embudo',$decoupled); if(!$decoupled)$failures[]='force_sync_facto';
$daily=file_get_contents(__DIR__.'/../cron/daily_jobs.php');
$jobOk=strpos($daily,'RestockForecastService')!==false && strpos($daily,'processDaily')!==false;
line_v85('daily_jobs motor BI',$jobOk); if(!$jobOk)$failures[]='daily_jobs';

if (!$failures) {
    $remaining=(int)$pdo->query("SELECT COUNT(*) FROM crm_opportunities WHERE id BETWEEN 443 AND 645 AND deleted_at IS NULL AND title LIKE 'Reposición Programada - %' AND owner_name='Sistema' AND COALESCE(expected_value,0)=0")->fetchColumn();
    line_v85('lote masivo eliminado',$remaining===0,'restantes='.$remaining); if($remaining>0)$failures[]='bad_batch';
    $supplierCycles=(int)$pdo->query("SELECT COUNT(*) FROM crm_customers WHERE deleted_at IS NULL AND counterparty_type='supplier' AND restock_days IS NOT NULL")->fetchColumn();
    line_v85('proveedores sin ciclo comercial',$supplierCycles===0,'restantes='.$supplierCycles); if($supplierCycles>0)$warnings[]='supplier_cycles';
    $forecastCount=(int)$pdo->query("SELECT COUNT(*) FROM crm_restock_forecasts")->fetchColumn();
    line_v85('pronosticos existentes',true,'total='.$forecastCount);
    $oldActive=(int)$pdo->query("SELECT COUNT(*) FROM crm_restock_forecasts WHERE status IN ('pending','ready') AND last_purchase_date<DATE_SUB(CURDATE(),INTERVAL 90 DAY)")->fetchColumn();
    line_v85('pronosticos activos dentro de 90 dias',$oldActive===0,'fuera_ventana='.$oldActive); if($oldActive>0)$failures[]='old_active_forecasts';
    $duplicateActive=(int)$pdo->query("SELECT COUNT(*) FROM (SELECT customer_id FROM crm_restock_forecasts WHERE status IN ('pending','ready') GROUP BY customer_id HAVING COUNT(*)>1) x")->fetchColumn();
    line_v85('un pronostico activo por cliente',$duplicateActive===0,'duplicados='.$duplicateActive); if($duplicateActive>0)$failures[]='duplicate_forecasts';
    $active=(int)$pdo->query("SELECT COUNT(*) FROM crm_customers WHERE deleted_at IS NULL AND customer_lifecycle_status='active'")->fetchColumn();
    $risk=(int)$pdo->query("SELECT COUNT(*) FROM crm_customers WHERE deleted_at IS NULL AND customer_lifecycle_status='at_risk'")->fetchColumn();
    $lost=(int)$pdo->query("SELECT COUNT(*) FROM crm_customers WHERE deleted_at IS NULL AND customer_lifecycle_status='lost'")->fetchColumn();
    line_v85('clasificacion clientes',true,'activos='.$active.', riesgo='.$risk.', perdidos='.$lost);
}

foreach (array('restock_recent_purchase_days','restock_activation_lead_days','restock_opportunity_grace_days','customer_lost_min_days','customer_lost_max_days','customer_lost_cycle_multiplier') as $setting) {
    $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;
    line_v85('setting '.$setting,$ok,$ok?(string)$value:'ausente'); if(!$ok)$failures[]=$setting;
}

echo PHP_EOL;
if($failures){echo 'PREFLIGHT FAIL | '.implode(', ',$failures).PHP_EOL;exit(1);}
if($warnings){echo 'PREFLIGHT PASS WITH WARNINGS | '.implode(', ',$warnings).PHP_EOL;exit(0);}
echo 'PREFLIGHT PASS | Flujo de reposicion predictiva operativo.' . PHP_EOL;
