<?php

require_once __DIR__ . '/../core/config.php';
require_once __DIR__ . '/../core/database.php';

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

$failed = false;
$report = static function (bool $ok, string $code, string $message) use (&$failed): void {
    echo '[' . ($ok ? 'PASS' : 'FAIL') . '] ' . $code . ': ' . $message . PHP_EOL;
    if (!$ok) $failed = true;
};

try {
    $root = realpath(dirname(__DIR__));
    $required = array(
        'assets/css/09-crm-ui.css',
        'modules/customers/_customer_quick_fields.php',
        'modules/customers/index.php',
        'modules/customers/view.php',
        'modules/customers/customer_store.php',
        'modules/customers/customer_update.php',
        'modules/customers/customer_restock_recalculate.php',
        'services/crm/CustomerService.php',
        'services/crm/CrmService.php',
        'modules/crm/opportunity_update.php',
        'api/dashboard/force_sync_facto.php',
    );
    $missing = array();
    foreach ($required as $file) {
        if (!$root || !is_file($root . '/' . $file)) $missing[] = $file;
    }
    $report(!$missing, 'FILES', $missing ? 'Faltan: ' . implode(', ', $missing) : 'Archivos CRM v7.2.6 instalados.');

    $pdo = db();
    $database = (string)$pdo->query('SELECT DATABASE()')->fetchColumn();
    $report($database === 'icylab_app', 'DATABASE', 'Base activa: ' . $database);

    foreach (array('commercial_name', 'restock_days', 'next_restock_date') as $column) {
        $stmt = $pdo->query("SHOW COLUMNS FROM crm_customers LIKE " . $pdo->quote($column));
        $exists = (bool)$stmt->fetch(PDO::FETCH_ASSOC);
        $report($exists, 'COLUMN_' . strtoupper($column), $exists ? 'crm_customers.' . $column . ' disponible.' : 'Falta crm_customers.' . $column . '.');
    }

    $fields = $root ? (string)file_get_contents($root . '/modules/customers/_customer_quick_fields.php') : '';
    $view = $root ? (string)file_get_contents($root . '/modules/customers/view.php') : '';
    $crm = $root ? (string)file_get_contents($root . '/services/crm/CrmService.php') : '';
    $opportunity = $root ? (string)file_get_contents($root . '/modules/crm/opportunity_update.php') : '';
    $forceSync = $root ? (string)file_get_contents($root . '/api/dashboard/force_sync_facto.php') : '';

    $report(strpos($fields, 'data-customer-restock-recalculate') !== false, 'FACTO_BUTTON', 'Botón de recálculo FACTO disponible.');
    $report(strpos($view, 'customer_restock_recalculate.php') === false && strpos($view, 'data-customer-restock-recalculate') !== false, 'BUTTON_BINDING', 'Interacción del botón instalada.');
    $report(strpos($crm, 'function projectCustomerRestockDate') !== false, 'CURRENT_CYCLE_PROJECTION', 'Proyección con el ciclo vigente disponible.');
    $report(strpos($opportunity, 'updateCustomerRestockFrequency(') === false, 'OPPORTUNITY_PRESERVES_CYCLE', 'Facturar una oportunidad no recalcula el ciclo.');
    $report(strpos($forceSync, 'updateCustomerRestockFrequency(') === false, 'SYNC_PRESERVES_CYCLE', 'La sincronización general no recalcula el ciclo.');
} catch (Throwable $e) {
    $report(false, 'EXCEPTION', $e->getMessage());
}

echo $failed ? 'BLOCKED: CRM CUSTOMERS V7.2.6 NOT READY' . PHP_EOL : 'READY: CRM CUSTOMERS V7.2.6' . PHP_EOL;
exit($failed ? 1 : 0);
