<?php
// Endpoint: subir documento KYC
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

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

function error_response($msg, $code = 400) {
    http_response_code($code);
    echo json_encode(['success' => false, 'error' => $msg]);
    exit;
}

if (!isset($_SESSION['client_id'])) {
    error_response('No autenticado', 401);
}
$client_id = (int)$_SESSION['client_id'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    error_response('Método no permitido', 405);
}

$type = isset($_POST['type']) ? strtolower(trim($_POST['type'])) : '';
$allowedTypes = ['id','address','selfie','other'];
if (!in_array($type, $allowedTypes, true)) {
    error_response('Tipo de documento inválido');
}

if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    error_response('Archivo no recibido o con error');
}

$file = $_FILES['file'];
$originalName = $file['name'];
$tmpPath = $file['tmp_name'];
$size = (int)$file['size'];

// Validar MIME básico
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $tmpPath);
finfo_close($finfo);
$allowedMime = [
    'image/jpeg','image/png','image/gif','application/pdf'
];
if (!in_array($mime, $allowedMime, true)) {
    error_response('Tipo de archivo no permitido');
}

// Preparar carpeta destino
$dir = BASE_PATH . '/uploads/documents/' . $client_id;
if (!is_dir($dir)) { @mkdir($dir, 0775, true); }

$ext = pathinfo($originalName, PATHINFO_EXTENSION);
$safeExt = preg_replace('/[^a-zA-Z0-9]/', '', $ext);
$unique = uniqid($type . '_', true) . ($safeExt ? ('.' . $safeExt) : '');
$dest = $dir . '/' . $unique;

if (!move_uploaded_file($tmpPath, $dest)) {
    error_response('Error al guardar el archivo');
}

// Guardar en BD
$db = Database::getInstance();
$pdo = $db->getConnection();
$relPath = '/uploads/documents/' . $client_id . '/' . $unique;

$stmt = $pdo->prepare("INSERT INTO client_documents (client_id, type, filename, original_name, mime_type, size, status, uploaded_at) VALUES (?,?,?,?,?,?, 'submitted', NOW())");
$stmt->execute([$client_id, $type, $relPath, $originalName, $mime, $size]);

echo json_encode([
    'success' => true,
    'type' => $type,
    'filename' => $relPath,
    'original_name' => $originalName,
    'mime' => $mime,
    'size' => $size,
    'date' => date('Y-m-d H:i:s')
]);
?>