<?php
declare(strict_types=1);
// kyc/status.php — Devuelve el estado KYC del distribuidor y documentos subidos
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
header('Access-Control-Allow-Methods: GET, OPTIONS');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

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

$user     = auth();
$id_inver = (int)$user['id_inver'];

$db = getDB();

// Obtener isVip del distribuidor
$stmt = $db->prepare("SELECT isVip FROM inversionista WHERE id_inver = ? LIMIT 1");
$stmt->execute([$id_inver]);
$inv   = $stmt->fetch();
$isVip = (int)($inv['isVip'] ?? 0);

// Obtener documentos subidos
$stmt = $db->prepare(
    "SELECT id_archivo, nombre AS file_url, realName, subTipo, fechaCreacion, status
     FROM archivo
     WHERE id_inver = ? AND tipo = 1 AND subTipo IN (1,2,3,4)
     ORDER BY subTipo ASC"
);
$stmt->execute([$id_inver]);
$docs = $stmt->fetchAll();

$slotLabels = [
    1 => 'Comprobante de domicilio',
    2 => 'Identificacion oficial (INE/Pasaporte)',
    3 => 'Estado de cuenta bancario',
    4 => 'Fotografia (Selfie con ID)',
];

$docsBySubTipo = [];
foreach ($docs as $d) {
    $docsBySubTipo[(int)$d['subTipo']] = $d;
}

$slots = [];
foreach ([1, 2, 3, 4] as $st) {
    $doc = $docsBySubTipo[$st] ?? null;
    $slots[] = [
        'subTipo' => $st,
        'label'   => $slotLabels[$st],
        'subido'  => $doc !== null,
        'doc'     => $doc ? [
            'id'            => (int)$doc['id_archivo'],
            'file_url'      => $doc['file_url'],
            'realName'      => $doc['realName'],
            'fechaCreacion' => $doc['fechaCreacion'],
            'status'        => (int)$doc['status'],
        ] : null,
    ];
}

$statusMap = [
    0 => ['label' => 'Sin verificar', 'color' => '#DC2626'],
    1 => ['label' => 'Verificado',    'color' => '#16A34A'],
    2 => ['label' => 'En revision',   'color' => '#D97706'],
    3 => ['label' => 'Rechazado',     'color' => '#DC2626'],
];
$statusInfo = $statusMap[$isVip] ?? $statusMap[0];

jsonOk([
    'isVip'        => $isVip,
    'statusLabel'  => $statusInfo['label'],
    'statusColor'  => $statusInfo['color'],
    'totalSubidos' => count(array_filter($slots, fn($s) => $s['subido'])),
    'slots'        => $slots,
]);
