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

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(200); exit; }

try {
    $payload  = auth(); // devuelve array con idinv, exp, etc.
    $id_inver = (int)($payload['idinv'] ?? 0);
    if (!$id_inver) { jsonErr(401, 'Token inválido.'); }
} catch (Exception $e) {
    http_response_code(401);
    echo json_encode(['error' => 'Token inválido.']);
    exit;
}

try {
    // ── Preferencia de cobro (campo depo) ─────────────────────────────────────
    $stmtDepo = $pdo->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 ─────────────────────
    // Solo para usuarios verificados (isVip = 1)
    $historial = [];
    if ($isVip === 1) {
        $stmtHist = $pdo->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 (suma de apagar donde status=0) ─────────────────
    $stmtPend = $pdo->prepare("
        SELECT COALESCE(SUM(apagar), 0) AS pendiente
        FROM regs2
        WHERE id_inver = ?
          AND status = 0
    ");
    $stmtPend->execute([$id_inver]);
    $pendiente = (float)$stmtPend->fetchColumn();

    echo json_encode([
        'success'   => true,
        'isVip'     => $isVip,
        'depo'      => $depo,
        'pendiente' => $pendiente,
        'historial' => $historial,
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Error al obtener ganancias.', 'detail' => $e->getMessage()]);
}
