<?php
require_once 'auth.php';
require_once  'config.php';
require_once __DIR__ . '/kyc_helpers.php';

$auth = getAuth();
$auth->requireAuth();
$user = $auth->getCurrentUser();
$db = getDatabaseConnection(); 
$logPrefix = '[start_kyc] user:' . ($user['id'] ?? 'n/a');

header('Content-Type: application/json');
 
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Metodo no permitido']);
    exit;
}

$kyc = getUserKyc($db, $user['id']);
if (($kyc['kyc_estado'] ?? 'no_iniciado') === 'verificado') {
    echo json_encode(['success' => true, 'alreadyVerified' => true, 'message' => 'Identidad verificada', 'redirectUrl' => '']);
    exit;
}  

if (!DIDIT_API_KEY) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Configura DIDIT_API_KEY en el entorno']);
    exit;
}

if (!DIDIT_FLOW_ID) { 
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Configura DIDIT_FLOW_ID en el entorno']);
    exit;
}

$callbackUrl = rtrim(BASE_URL, '/') . '/didit_webhook';
if (DIDIT_WEBHOOK_TOKEN) {
    $callbackUrl .= '?token=' . urlencode(DIDIT_WEBHOOK_TOKEN);
}

// Payload para el endpoint de sesión v2 de Didit.
$payload = [
    'workflow_id' => DIDIT_FLOW_ID,
    'vendor_data' => (string)$user['id'],
    'callback' => $callbackUrl
];

try {
    $resp = diditRequest('POST', '/v2/session/', $payload);
    $redirectUrl = $resp['url'] ?? $resp['redirect_url'] ?? $resp['session_url'] ?? null;
    $sessionId = $resp['id'] ?? $resp['session_id'] ?? $resp['request_id'] ?? null;

    if ($sessionId) {
        setUserKycStatus($db, $user['id'], 'pendiente', $sessionId, null);
    }

    if (!$redirectUrl) {
        throw new Exception('Didit no devolvio una URL de verificacion');
    }

    echo json_encode([
        'success' => true,
        'redirectUrl' => $redirectUrl,
        'status' => 'pendiente'
    ]);
} catch (Throwable $e) {
    error_log($logPrefix . ' error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
