<?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',
        'assets/css/app.css',
        'layouts/header.php',
        '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/CrmService.php',
        'modules/crm/opportunity_create.php',
        'modules/crm/opportunity_store.php',
        'modules/crm/index.php',
        'modules/crm/embudo.php',
        'modules/crm/quotes.php',
        'modules/crm/quote_customer_save_ajax.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.7 instalados.');

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

    foreach (array('commercial_name', 'business_activity', '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') : '';
    $css = $root ? (string)file_get_contents($root . '/assets/css/09-crm-ui.css') : '';
    $appCss = $root ? (string)file_get_contents($root . '/assets/css/app.css') : '';
    $header = $root ? (string)file_get_contents($root . '/layouts/header.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') : '';
    $opportunityCreate = $root ? (string)file_get_contents($root . '/modules/crm/opportunity_create.php') : '';
    $opportunityModal = $root ? (string)file_get_contents($root . '/modules/crm/index.php') : '';
    $pipelineModal = $root ? (string)file_get_contents($root . '/modules/crm/embudo.php') : '';
    $quotes = $root ? (string)file_get_contents($root . '/modules/crm/quotes.php') : '';
    $opportunityStore = $root ? (string)file_get_contents($root . '/modules/crm/opportunity_store.php') : '';
    $quoteCustomerStore = $root ? (string)file_get_contents($root . '/modules/crm/quote_customer_save_ajax.php') : '';

    $activityIsInput = preg_match('/<input[^>]+name="business_activity"/', $fields) === 1;
    $activityIsTextarea = preg_match('/<textarea[^>]+name="business_activity"/', $fields) === 1;
    $report($activityIsInput && !$activityIsTextarea, 'COMPACT_ACTIVITY', 'Actividad comercial utiliza un campo simple.');
    $report(strpos($fields, "fieldClass('website', 'span-4')") !== false, 'COMPACT_GRID', 'Fila final distribuida en columnas.');
    $report(strpos($css, 'CRM Clientes v7.2.7') !== false, 'FORM_STYLES', 'Estilos compactos de creación y edición instalados.');
    $report(strpos($appCss, '09-crm-ui.css?v=1.4.2') !== false && strpos($header, "\$v = '1.4.2'") !== false, 'CSS_CACHE_VERSION', 'Cache-buster CSS v1.4.2 instalado.');
    $report(strpos($fields, 'customer-quick-grid--polished') !== false, 'SHARED_FORM_STYLE', 'Estilo compartido disponible para todos los formularios rápidos.');
    $opportunityFormsReady = strpos($opportunityCreate, "'show_commercial_name' => true") !== false
        && strpos($opportunityModal, "'show_commercial_name' => true") !== false
        && strpos($pipelineModal, "'show_commercial_name' => true") !== false;
    $report($opportunityFormsReady, 'OPPORTUNITY_CUSTOMER_FORMS', 'Nombre comercial habilitado en los formularios de oportunidad.');
    $report(strpos($quotes, "'show_commercial_name' => true") !== false, 'QUOTE_CUSTOMER_FORM', 'Nombre comercial habilitado en cotizaciones.');
    $report(strpos($opportunityStore, "'commercial_name' => \$commercialName") !== false, 'OPPORTUNITY_COMMERCIAL_NAME_SAVE', 'Oportunidades guardan el nombre comercial.');
    $report(strpos($quoteCustomerStore, "'commercial_name' => \$_POST['commercial_name']") !== false, 'QUOTE_COMMERCIAL_NAME_SAVE', 'Cotizaciones guardan el nombre comercial.');
    $report(strpos($fields, 'data-customer-restock-recalculate') !== false, 'FACTO_BUTTON', 'Botón FACTO conservado.');
    $report(strpos($opportunity, 'updateCustomerRestockFrequency(') === false, 'OPPORTUNITY_PRESERVES_CYCLE', 'Facturar una oportunidad conserva el ciclo vigente.');
    $report(strpos($forceSync, 'updateCustomerRestockFrequency(') === false, 'SYNC_PRESERVES_CYCLE', 'Sincronizar FACTO conserva el ciclo vigente.');
} catch (Throwable $e) {
    $report(false, 'EXCEPTION', $e->getMessage());
}

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