<?php
/**
 * ================================================================
 * KYC CALLBACK — Dojah Web SDK Redirect Handler
 * ================================================================
 * File: kyc-callback.php (project root)
 *
 * Dojah redirects here after the user completes (or fails) the
 * widget popup. Dojah appends ?verification_id=xxx to the URL
 * you set as the callback URL in your Dojah dashboard.
 *
 * We also pass ?verification_type=xxx when building the button URL
 * on each page, so we know which flow was completed.
 *
 * Flow:
 *   1. Dojah popup completes
 *   2. Dojah redirects to:
 *      kyc-callback.php?verification_id=xxx&verification_type=xxx
 *   3. This file processes the result
 *   4. Redirects back to the originating page with a status message
 * ================================================================
 */

session_start();
require_once __DIR__ . '/app/Core/init.php';
require_once __DIR__ . '/app/Core/DojahKYC.php';

// ── Helper: redirect with a flash message ────────────────────────
function redirectWithMessage(string $url, string $type, string $message): void {
    $_SESSION['kyc_flash'] = ['type' => $type, 'message' => $message];
    header('Location: ' . $url);
    exit;
}

// ── Must be logged in ─────────────────────────────────────────────
if (empty($_SESSION['user_id']) || empty($_SESSION['user_type'])) {
    header('Location: ' . APP_URL . '/auth/login.php');
    exit;
}

$user_id   = (int)$_SESSION['user_id'];
$user_type = $_SESSION['user_type'];

// ── Read query parameters from Dojah redirect ────────────────────
$verification_id   = trim($_GET['verification_id']   ?? '');
$verification_type = trim($_GET['verification_type'] ?? '');

// Determine where to redirect back to based on user type
$return_url = ($user_type === 'vendor')
    ? APP_URL . '/vendor/kyc.php'
    : APP_URL . '/customer/profile.php#kycSection';

// ── Validate ──────────────────────────────────────────────────────
if (empty($verification_id)) {
    redirectWithMessage($return_url, 'warning', 'Verification was not completed. Please try again.');
}

if (empty($verification_type)) {
    // Try to infer from user type if not passed
    $verification_type = ($user_type === 'customer')
        ? DojahKYC::TYPE_CUSTOMER_IDENTITY
        : DojahKYC::TYPE_VENDOR_PERSONAL;
}

// ── Authorisation check ───────────────────────────────────────────
$customer_types = [DojahKYC::TYPE_CUSTOMER_IDENTITY];
$vendor_types   = [DojahKYC::TYPE_VENDOR_PERSONAL, DojahKYC::TYPE_VENDOR_BUSINESS];

if ($user_type === 'customer' && !in_array($verification_type, $customer_types, true)) {
    redirectWithMessage($return_url, 'danger', 'Invalid verification type.');
}
if ($user_type === 'vendor' && !in_array($verification_type, $vendor_types, true)) {
    redirectWithMessage($return_url, 'danger', 'Invalid verification type.');
}

// ── Already verified? ─────────────────────────────────────────────
$kycService = new DojahKYC();

if ($kycService->isTypeVerified($user_id, $verification_type)) {
    redirectWithMessage($return_url, 'info', 'You are already verified.');
}

// ── Process ───────────────────────────────────────────────────────
$result = $kycService->processCallback($user_id, $verification_id, $verification_type);

if ($result['success']) {
    $data = $result['data'];

    if ($verification_type === DojahKYC::TYPE_VENDOR_BUSINESS) {
        $msg = 'Business verified successfully! Business name: ' . ($data['business_name'] ?? '');
    } else {
        $msg = 'Identity verified successfully! Welcome, ' .
               ($data['first_name'] ?? '') . ' ' . ($data['last_name'] ?? '') . '.';
    }

    redirectWithMessage($return_url, 'success', $msg);
} else {
    redirectWithMessage($return_url, 'danger', 'Verification failed: ' . $result['message']);
}