<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');

require_once dirname(__FILE__) . '/../../config.php';

$db = getDB();

// Validar sesión
$token = '80d174514469a13dffc050563392831fb8efcf0533f362f9457a11ba965e1a72';
$stmtSess = $db->prepare("SELECT idusuarios_sist FROM admin_sessions WHERE token = ? AND expires_at > NOW() LIMIT 1");
$stmtSess->execute([$token]);
$sess = $stmtSess->fetch(PDO::FETCH_ASSOC);
echo json_encode(['sess' => $sess]);

// Query de notas
$mes = 3; $anio = 2026;
$fechaInicio = '2026-03-01';
$fechaFin    = '2026-03-31';

$stmt = $db->prepare(
    "SELECT
        t.idtransacciones,
        DATE(t.fechat) AS fecha,
        t.nota,
        t.inversionista_id_inver AS id_inver,
        CONCAT(i.nombre,' ',i.appat,' ',COALESCE(i.apmat,'')) AS nombre_dist,
        i.referencia,
        i.rfc,
        COALESCE(SUM(DISTINCT d.puntos), 0) AS cantidad_pagada,
        COUNT(DISTINCT ns.id) AS total_nsalida,
        COALESCE(SUM(ns.asignar), 0) AS ya_asignado,
        COALESCE(SUM(CASE WHEN (ns.cant - ns.asignar) > 0 THEN (ns.cant - ns.asignar) ELSE 0 END), 0) AS pendiente_asignar
     FROM transacciones t
     JOIN inversionista i ON i.id_inver = t.inversionista_id_inver
     LEFT JOIN depositos d ON d.transacciones_idtransacciones = t.idtransacciones
     LEFT JOIN nsalida ns ON ns.transacciones_idtransacciones = t.idtransacciones
     WHERE t.tipostr_idtipostr = 11
       AND t.fechat BETWEEN ? AND ?
     GROUP BY t.idtransacciones
     ORDER BY t.idtransacciones DESC"
);
$stmt->execute([$fechaInicio, $fechaFin]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(['count' => count($rows), 'first' => $rows[0] ?? null]);
