<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

// Capturar errores PHP
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

$errors = [];
$steps  = [];

try {
    $steps[] = 'step1: require config';
    require_once dirname(__FILE__) . '/../config.php';
    $steps[] = 'step2: config ok';

    $db  = getDB();
    $steps[] = 'step3: db ok';

    // Parámetros
    $desde  = $_GET['desde']  ?? date('Y-m-01');
    $hasta  = $_GET['hasta']  ?? date('Y-m-d');
    $idprod = isset($_GET['idprod']) ? (int)$_GET['idprod'] : 319;
    $steps[] = "step4: params ok idprod=$idprod";

    // Query simplificada
    $stmt = $db->prepare("
        SELECT t.idtransacciones, p.cant, t.fechat, t.usuarios_ci_idusuarios_ci, t.cdentrega
        FROM transacciones t
        JOIN pedido p ON p.transacciones_idtransacciones = t.idtransacciones
        WHERE t.tipostr_idtipostr IN (6, 10, 11)
          AND t.fechat BETWEEN ? AND ?
          AND p.productos_idprod = ?
        ORDER BY t.fechat DESC
        LIMIT 50
    ");
    $steps[] = 'step5: prepare ok';
    $stmt->execute([$desde . ' 00:00:00', $hasta . ' 23:59:59', $idprod]);
    $steps[] = 'step6: execute ok';
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $steps[] = 'step7: fetch ok rows=' . count($rows);

    echo json_encode(['success' => true, 'steps' => $steps, 'count' => count($rows), 'sample' => array_slice($rows, 0, 3)], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    echo json_encode(['success' => false, 'steps' => $steps, 'error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
}
