<?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(
        'modules/customers/_customer_quick_fields.php',
        'modules/customers/index.php',
        'modules/customers/view.php',
        'modules/customers/customer_store.php',
        'modules/customers/customer_update.php',
        'services/crm/CustomerService.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.5 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 . '.');
    }

    $fieldsSource = $root ? (string)file_get_contents($root . '/modules/customers/_customer_quick_fields.php') : '';
    $viewSource = $root ? (string)file_get_contents($root . '/modules/customers/view.php') : '';
    $report(strpos($fieldsSource, 'name="commercial_name"') !== false, 'COMMERCIAL_NAME_FIELD', 'Campo Nombre comercial disponible.');
    $report(strpos($fieldsSource, 'name="restock_days"') !== false, 'RESTOCK_FIELD', 'Campo Ciclo de recompra disponible.');
    $report(strpos($viewSource, 'updateCustomerRestockFrequency(') === false, 'READ_ONLY_VIEW', 'La ficha no sobrescribe el ciclo al abrirse.');
} catch (Throwable $e) {
    $report(false, 'EXCEPTION', $e->getMessage());
}

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