<?php
/**
 * agrupacion-buscar.php
 * Busca notas elegibles para agrupar: tipo 10 u 11, statusentrega = PENDIENTE
 *
 * GET params:
 *   filtro  = "hoy" | "tx" | "ref"
 *   valor   = (requerido si filtro=tx o filtro=ref)
 */
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

require_once __DIR__ . '/../../config.php';
$db = getDB();

// ── Validar token ─────────────────────────────────────────────────────────────
$headers    = getallheaders();
$authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
if (!preg_match('/Bearer\s+(.+)/i', $authHeader, $m)) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Token requerido']);
    exit;
}
$token = trim($m[1]);
$stmtTok = $db->prepare("SELECT idusuarios_sist FROM admin_sessions WHERE token = ? AND expira > NOW()");
$stmtTok->execute([$token]);
if (!$stmtTok->fetch()) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Sesión inválida o expirada']);
    exit;
}

$filtro = $_GET['filtro'] ?? 'hoy';
$valor  = trim($_GET['valor'] ?? '');

try {
    $db->exec("SET NAMES utf8mb4 COLLATE utf8mb4_general_ci");

    $where  = "t.tipostr_idtipostr IN (10, 11)
               AND t.statusentrega = 'PENDIENTE'";
    $params = [];

    if ($filtro === 'hoy') {
        $where .= " AND DATE(t.fechat) = CURDATE()";
    } elseif ($filtro === 'tx' && $valor !== '') {
        $where .= " AND t.idtransacciones = ?";
        $params[] = (int)$valor;
    } elseif ($filtro === 'ref' && $valor !== '') {
        $where .= " AND i.referencia LIKE ?";
        $params[] = '%' . $valor . '%';
    }

    $sql = "
        SELECT
            t.idtransacciones,
            t.fechat,
            t.tipostr_idtipostr   AS tipo,
            t.cdentrega,
            t.statusentrega,
            i.referencia,
            CONCAT(i.nombre,' ',i.appat,' ',COALESCE(i.apmat,'')) AS nombre_dist,
            COALESCE(d.puntos, 0) AS puntos
        FROM transacciones t
        JOIN inversionista i ON i.id_inver = t.inversionista_id_inver
        LEFT JOIN depositos d ON d.transacciones_idtransacciones = t.idtransacciones
        WHERE $where
        ORDER BY t.fechat DESC
        LIMIT 200
    ";

    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmtProd = $db->prepare("
        SELECT p.productos_idprod AS id_prod, p.cant,
               COALESCE(pr.nombreProd, pm.promodesc, CONCAT('ID:',p.productos_idprod)) AS nombre
        FROM pedido p
        LEFT JOIN productos pr ON pr.id_prod = p.productos_idprod AND p.productos_idprod < 1000
        LEFT JOIN promod pm    ON pm.id_promo = p.productos_idprod AND p.productos_idprod >= 1000
        WHERE p.transacciones_idtransacciones = ?
    ");

    foreach ($rows as &$r) {
        $r['idtransacciones'] = (int)$r['idtransacciones'];
        $r['tipo']            = (int)$r['tipo'];
        $r['cdentrega']       = (int)$r['cdentrega'];
        $r['puntos']          = (float)$r['puntos'];
        $stmtProd->execute([$r['idtransacciones']]);
        $prods = $stmtProd->fetchAll(PDO::FETCH_ASSOC);
        foreach ($prods as &$p) {
            $p['id_prod'] = (int)$p['id_prod'];
            $p['cant']    = (int)$p['cant'];
        }
        unset($p);
        $r['productos'] = $prods;
    }
    unset($r);

    echo json_encode(['ok' => true, 'success' => true, 'data' => ['notas' => $rows]]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'success' => false, 'message' => 'Error al buscar notas: ' . $e->getMessage()]);
}
