<?php



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

// GET /admin/ganancias/list.php
// Query params: periodo, status, page, limit

requireAdmin();

$db = getDB();
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = min(100, max(1, (int)($_GET['limit'] ?? 20)));
$offset = ($page - 1) * $limit;
$periodo = $_GET['periodo'] ?? '';
$status = $_GET['status'] ?? '';

$where = [];
$params = [];

if (!empty($periodo)) {
    $where[] = 'MONTH(r.fecha) = ? AND YEAR(r.fecha) = ?';
    [$month, $year] = explode('-', $periodo);
    $params = [(int)$month, (int)$year];
}

if (!isset($status) || $status !== '') {
    $where[] = 'r.status = ?';
    $params[] = $status ?: '0';
}

$whereClause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

$countSql = "SELECT COUNT(*) as total FROM regs2 r $whereClause";
$stmt = $db->prepare($countSql);
$stmt->execute($params);
$total = $stmt->fetch()['total'] ?? 0;

$sql = "
    SELECT r.idreg, r.id_inv, r.monto, r.fecha, r.status,
           i.nombre, i.appat, i.apmat
    FROM regs2 r
    LEFT JOIN inversionista i ON r.id_inv = i.id_inver
    $whereClause
    ORDER BY r.fecha DESC
    LIMIT ? OFFSET ?
";

$params[] = $limit;
$params[] = $offset;

$stmt = $db->prepare($sql);
$stmt->execute($params);
$ganancias = $stmt->fetchAll();

jsonOk([
    'ganancias' => $ganancias,
    'pagination' => [
        'page' => $page,
        'limit' => $limit,
        'total' => (int)$total,
        'pages' => (int)ceil($total / $limit)
    ]
]);
