<?php
require_once __DIR__ . '/bootstrap.php';
// endpoints/kyc.php

$auth   = requireAuth();
$userId = $auth['user_id'];
$db     = Database::getInstance();

// GET /kyc/status
if ($method === 'GET' && strpos($uri, '/kyc/status') !== false) {
    $user = $db->fetch("SELECT kyc_status FROM users WHERE id=?", [$userId]);
    $doc  = $db->fetch("SELECT * FROM kyc_documents WHERE user_id=? ORDER BY created_at DESC LIMIT 1", [$userId]);
    jsonSuccess(['kyc_status' => $user['kyc_status'], 'document' => $doc]);
}

// POST /kyc/submit
if ($method === 'POST' && strpos($uri, '/kyc/submit') !== false) {
    $user = $db->fetch("SELECT kyc_status FROM users WHERE id=?", [$userId]);
    if (in_array($user['kyc_status'], ['pending','approved'])) jsonError('KYC already ' . $user['kyc_status'] . '.');

    $docType = sanitize($_POST['doc_type'] ?? '');
    if (!in_array($docType, ['passport','national_id','drivers_license'])) jsonError('Invalid document type.');

    $uploadDir = __DIR__ . '/../../uploads/kyc/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

    $allowed = ['image/jpeg','image/png','image/gif','image/webp','application/pdf'];

    function uploadKycFile(array $file, string $prefix, int $userId, string $dir, array $allowed): ?string {
        if ($file['error'] !== UPLOAD_ERR_OK) return null;
        if (!in_array($file['type'], $allowed)) return null;
        $ext  = pathinfo($file['name'], PATHINFO_EXTENSION);
        $name = "{$prefix}_{$userId}_" . time() . ".$ext";
        move_uploaded_file($file['tmp_name'], $dir . $name);
        return $name;
    }

    if (empty($_FILES['front_image'])) jsonError('Front document image is required.');
    $front  = uploadKycFile($_FILES['front_image'],  'front',  $userId, $uploadDir, $allowed);
    $back   = isset($_FILES['back_image'])   ? uploadKycFile($_FILES['back_image'],   'back',   $userId, $uploadDir, $allowed) : null;
    $selfie = isset($_FILES['selfie_image']) ? uploadKycFile($_FILES['selfie_image'], 'selfie', $userId, $uploadDir, $allowed) : null;

    if (!$front) jsonError('Failed to upload front document.');

    $db->insert(
        "INSERT INTO kyc_documents (user_id, doc_type, front_img, back_img, selfie_img) VALUES (?,?,?,?,?)",
        [$userId, $docType, $front, $back, $selfie]
    );

    $db->query("UPDATE users SET kyc_status='pending' WHERE id=?", [$userId]);

    jsonSuccess([], 'KYC documents submitted. Review usually takes 1-2 business days.');
}
