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

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'GET') { jsonErr(405, 'Metodo no permitido.'); }

$payload  = auth();
$id_inver = (int)($payload['idinv'] ?? 0);
if (!$id_inver) { jsonErr(401, 'Token inválido.'); }

$db = getDB();

try {
    // ── Preferencia de cobro y estado de verificación ──────────────────────────
    $stmtDepo = $db->prepare("SELECT depo, isVip FROM inversionista WHERE id_inver = ?");
    $stmtDepo->execute([$id_inver]);
    $inv   = $stmtDepo->fetch(PDO::FETCH_ASSOC);
    $depo  = $inv['depo']  ?? 'PENDIENTE';
    $isVip = (int)($inv['isVip'] ?? 0);

    // ── Historial de ganancias: últimos 6 meses de regs2 ──────────────────────
    $historial = [];
    if ($isVip === 1) {
        $stmtHist = $db->prepare("
            SELECT fechap, _real, apagar, status
            FROM regs2
            WHERE id_inver = ?
            ORDER BY fechap DESC
            LIMIT 6
        ");
        $stmtHist->execute([$id_inver]);
        $historial = $stmtHist->fetchAll(PDO::FETCH_ASSOC);
    }

    // ── Ganancias pendientes ────────────────────────────────────────────────────
    $stmtPend = $db->prepare("
        SELECT COALESCE(SUM(apagar), 0) AS pendiente
        FROM regs2
        WHERE id_inver = ? AND status = 0
    ");
    $stmtPend->execute([$id_inver]);
    $pendiente = (float)$stmtPend->fetchColumn();

    jsonOk([
        'isVip'     => $isVip,
        'depo'      => $depo,
        'pendiente' => $pendiente,
        'historial' => $historial,
    ]);

} catch (Throwable $e) {
    jsonErr(500, 'Error al obtener ganancias: ' . $e->getMessage());
}
