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

if ($_SERVER['REQUEST_METHOD'] !== 'GET') { jsonErr(405, 'Metodo no permitido.'); }
$jwt   = auth();
$idinv = (int)$jwt['idinv'];
$db    = getDB();

$limite = isset($_GET['limite']) ? (int)$_GET['limite'] : 24;
$pagina = isset($_GET['pagina']) ? (int)$_GET['pagina'] : 1;
$offset = ($pagina - 1) * $limite;

$stmt = $db->prepare(
    'SELECT r.idreg, r.primera, r.segunda, r.tercera, r.cuarta,
            r.total, r._real, r.apagar, r.pagado, r.calificados,
            r.status, r.fechap, r.fechaf, r.observaciones, r.cd, r.impuestos
     FROM regs2 r
     WHERE r.id_inver = ?
     ORDER BY r.idreg DESC
     LIMIT ? OFFSET ?'
);
$stmt->execute(array($idinv, $limite, $offset));
$periodos = $stmt->fetchAll();

// Totales generales
$stmtTot = $db->prepare(
    'SELECT COALESCE(SUM(apagar),0) AS pendiente,
            COALESCE(SUM(pagado),0) AS cobrado,
            COALESCE(SUM(total),0)  AS generado
     FROM regs2 WHERE id_inver = ?'
);
$stmtTot->execute(array($idinv));
$totales = $stmtTot->fetch();

// Metodo de cobro actual
$stmtDepo = $db->prepare('SELECT depo FROM inversionista WHERE id_inver = ? LIMIT 1');
$stmtDepo->execute(array($idinv));
$depo = $stmtDepo->fetchColumn();

jsonOk(array(
    'periodos'     => $periodos,
    'totales'      => $totales,
    'metodo_cobro' => $depo ?: 'banco',
    'pagina'       => $pagina,
    'limite'       => $limite,
));
