<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Enable error reporting to see what fails
error_reporting(E_ALL);
ini_set('display_errors', 0);

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

$headers    = getallheaders();
$authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
$token      = str_replace('Bearer ', '', $authHeader);
if (empty($token)) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Token requerido']);
    exit;
}
$db  = getDB();
$now = date('Y-m-d H:i:s');
$stmtSess = $db->prepare("SELECT s.idusuarios_sist FROM admin_sessions s WHERE s.token = ? AND s.expira > ? LIMIT 1");
$stmtSess->execute([$token, $now]);
if (!$stmtSess->fetch()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Sesión inválida']);
    exit;
}

$steps = [];

// Step 1: Test centros query
try {
    $centros = $db->query("
        SELECT idusuarios_ci, nombre, tipo_usuario
        FROM usuarios_ci
        WHERE tipo_usuario IN (2, 3)
           OR idusuarios_ci IN (8, 12)
        ORDER BY idusuarios_ci
    ")->fetchAll(PDO::FETCH_ASSOC);
    $steps[] = ['step' => 'centros', 'ok' => true, 'count' => count($centros), 'data' => $centros];
} catch(Exception $e) {
    $steps[] = ['step' => 'centros', 'ok' => false, 'error' => $e->getMessage()];
    echo json_encode(['success' => false, 'steps' => $steps]);
    exit;
}

// Step 2: Test productos query
try {
    $productos = $db->query("
        SELECT id_prod, nombreProd, presentacion
        FROM productos
        WHERE activo = 'SI' AND tipoprod IN (1, 2)
        ORDER BY nombreProd
    ")->fetchAll(PDO::FETCH_ASSOC);
    $steps[] = ['step' => 'productos', 'ok' => true, 'count' => count($productos)];
} catch(Exception $e) {
    $steps[] = ['step' => 'productos', 'ok' => false, 'error' => $e->getMessage()];
    echo json_encode(['success' => false, 'steps' => $steps]);
    exit;
}

// Step 3: Test main query
$desde = '2026-03-01';
$hasta = '2026-03-29';
$where  = "t.tipostr_idtipostr IN (6, 10, 11) AND t.fechat BETWEEN ? AND ?";
$params = [$desde . ' 00:00:00', $hasta . ' 23:59:59'];

try {
    $stmtDesp = $db->prepare("
        SELECT
            p.productos_idprod                   AS idprod,
            pr.nombreProd                        AS nombre_prod,
            pr.presentacion,
            pr.tipoprod,
            t.usuarios_ci_idusuarios_ci          AS idcd,
            uc.nombre                            AS nombre_centro,
            SUM(p.cant)                          AS unidades,
            COUNT(DISTINCT t.idtransacciones)    AS notas,
            COALESCE(SUM(d.cantidad), 0)         AS monto_mxn,
            SUM(p.cant * p.puntos)               AS puntos_total
        FROM transacciones t
        JOIN pedido p    ON p.transacciones_idtransacciones = t.idtransacciones
        JOIN productos pr ON pr.id_prod = p.productos_idprod
        LEFT JOIN depositos d ON d.transacciones_idtransacciones = t.idtransacciones
        LEFT JOIN usuarios_ci uc ON uc.idusuarios_ci = t.usuarios_ci_idusuarios_ci
        WHERE {$where}
          AND pr.activo = 'SI'
          AND pr.tipoprod IN (1, 2)
        GROUP BY p.productos_idprod, t.usuarios_ci_idusuarios_ci
        ORDER BY SUM(p.cant) DESC
    ");
    $stmtDesp->execute($params);
    $rows = $stmtDesp->fetchAll(PDO::FETCH_ASSOC);
    $steps[] = ['step' => 'main_query', 'ok' => true, 'count' => count($rows)];
} catch(Exception $e) {
    $steps[] = ['step' => 'main_query', 'ok' => false, 'error' => $e->getMessage()];
    echo json_encode(['success' => false, 'steps' => $steps]);
    exit;
}

// Step 4: Test usort
try {
    $arr = [['unidades' => 5], ['unidades' => 10]];
    usort($arr, fn($a, $b) => $b['unidades'] - $a['unidades']);
    $steps[] = ['step' => 'usort', 'ok' => true];
} catch(Exception $e) {
    $steps[] = ['step' => 'usort', 'ok' => false, 'error' => $e->getMessage()];
}

// Step 5: Test date('t')
try {
    $t = (int)date('t', mktime(0,0,0,3,1,2026));
    $steps[] = ['step' => 'date_t', 'ok' => true, 'value' => $t];
} catch(Exception $e) {
    $steps[] = ['step' => 'date_t', 'ok' => false, 'error' => $e->getMessage()];
}

// Step 6: Test comparativa loop (just 1 iteration)
try {
    $year  = (int)date('Y');
    $month = (int)date('m');
    $m = $month;
    $y = $year;
    $mStart = sprintf('%04d-%02d-01 00:00:00', $y, $m);
    $mEnd   = sprintf('%04d-%02d-%02d 23:59:59', $y, $m, (int)date('t', mktime(0,0,0,$m,1,$y)));
    
    $stmtM = $db->prepare("
        SELECT COALESCE(SUM(p.cant), 0) AS unidades,
               COALESCE(SUM(d.cantidad), 0) AS monto_mxn,
               COUNT(DISTINCT t.idtransacciones) AS notas
        FROM transacciones t
        JOIN pedido p    ON p.transacciones_idtransacciones = t.idtransacciones
        JOIN productos pr ON pr.id_prod = p.productos_idprod
        LEFT JOIN depositos d ON d.transacciones_idtransacciones = t.idtransacciones
        WHERE t.tipostr_idtipostr IN (6, 10, 11)
          AND t.fechat BETWEEN ? AND ?
          AND pr.activo = 'SI'
          AND pr.tipoprod IN (1, 2)
    ");
    $stmtM->execute([$mStart, $mEnd]);
    $mRow = $stmtM->fetch(PDO::FETCH_ASSOC);
    $steps[] = ['step' => 'comparativa_1', 'ok' => true, 'data' => $mRow];
} catch(Exception $e) {
    $steps[] = ['step' => 'comparativa_1', 'ok' => false, 'error' => $e->getMessage()];
}

echo json_encode(['success' => true, 'steps' => $steps], JSON_UNESCAPED_UNICODE);
