<?php
declare(strict_types=1);
// kyc/status.php — Devuelve el estado KYC del distribuidor (lee del filesystem)
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';

$jwt      = auth();
$id_inver = (int)$jwt['idinv'];
$db       = getDB();

// ── Estado de verificación del distribuidor ───────────────────────────────────
$isVip = 0;
try {
    $stmt = $db->prepare("SELECT isVip FROM inversionista WHERE id_inver = ? LIMIT 1");
    $stmt->execute([$id_inver]);
    $inv   = $stmt->fetch();
    $isVip = (int)($inv['isVip'] ?? 0);
} catch (Throwable $e) {
    $isVip = 0;
}

// ── Leer archivos del filesystem ──────────────────────────────────────────────
// Ruta: public_html/app-api/uploads/kyc/{id_inver}/
// Nombre: kyc_{id}_sub{1-4}_{timestamp}.ext
$baseUploadPath = dirname(__DIR__) . '/uploads/kyc/';
$baseUploadUrl  = 'https://api.sistemarrb.com/app-api/uploads/kyc/';
$userDir        = $baseUploadPath . $id_inver . '/';

$slotLabels = [
    1 => 'Comprobante de domicilio',
    2 => 'Identificación oficial (INE/Pasaporte)',
    3 => 'Estado de cuenta bancario',
    4 => 'Fotografía (Selfie con ID)',
];

// Encontrar archivo por subTipo desde el nombre
$found = [1 => null, 2 => null, 3 => null, 4 => null];
if (is_dir($userDir)) {
    $files = @scandir($userDir);
    if ($files) {
        foreach ($files as $f) {
            if ($f === '.' || $f === '..') continue;
            // Patrón: kyc_{id}_sub{N}_{timestamp}.ext
            if (preg_match('/^kyc_\d+_sub(\d)_\d+\.\w+$/i', $f, $m)) {
                $st = (int)$m[1];
                if ($st >= 1 && $st <= 4) {
                    $found[$st] = $f;
                }
            }
        }
    }
}

// ── Construir slots ───────────────────────────────────────────────────────────
$totalSubidos = 0;
$slots = [];
foreach ([1, 2, 3, 4] as $st) {
    $fileName = $found[$st];
    $subido   = $fileName !== null;
    if ($subido) $totalSubidos++;

    $ext = $subido ? strtolower(pathinfo($fileName, PATHINFO_EXTENSION)) : null;

    $slots[] = [
        'subTipo' => $st,
        'label'   => $slotLabels[$st],
        'subido'  => $subido,
        'doc'     => $subido ? [
            'realName' => $fileName,
            'file_url' => $baseUploadUrl . $id_inver . '/' . rawurlencode($fileName),
            'ext'      => $ext,
            'esPdf'    => $ext === 'pdf',
            'status'   => $isVip === 1 ? 1 : ($isVip === 3 ? 3 : 0),
        ] : null,
    ];
}

$statusMap = [
    0 => 'sin_verificar',
    1 => 'aprobado',
    2 => 'en_revision',
    3 => 'rechazado',
];

jsonOk([
    'isVip'        => $isVip,
    'statusKey'    => $statusMap[$isVip] ?? 'sin_verificar',
    'totalSubidos' => $totalSubidos,
    'slots'        => $slots,
]);
