<?php
/**
 * KYC Submissions API
 * 
 * Retrieves KYC submissions for admin review
 */

header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// CRITICAL: Allow origin with credentials
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';

// Require admin authentication
requireAdmin(true);

// Load configuration and database connection
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';

try {
    // First check if kyc_requests table exists
    $stmt = $pdo->query("SHOW TABLES LIKE 'kyc_requests'");
    if ($stmt->rowCount() === 0) {
        echo json_encode(["success" => true, "kyc" => [], "message" => "KYC table not found - run installer to create database schema"]);
        exit;
    }

    // Introspect kyc_requests columns
    $cols = [];
    try {
        $c = $pdo->query("SHOW COLUMNS FROM kyc_requests");
        while ($r = $c->fetch(PDO::FETCH_ASSOC)) { $cols[$r['Field']] = true; }
    } catch (Exception $e) { /* ignore */ }

    $hasSubmittedAt = isset($cols['submitted_at']);
    $hasCreatedAt = isset($cols['created_at']);
    $hasDocType = isset($cols['document_type']);
    $hasDocNumber = isset($cols['document_number']);
    $hasDocFront = isset($cols['document_front']);
    $hasDocBack = isset($cols['document_back']);
    $hasDataJson = isset($cols['data']);

    $submittedExpr = $hasSubmittedAt ? 'k.submitted_at' : ($hasCreatedAt ? 'k.created_at' : 'NULL');
    $orderBy = $hasSubmittedAt ? 'k.submitted_at DESC' : ($hasCreatedAt ? 'k.created_at DESC' : 'k.id DESC');

    // Build select fields
    $fields = [
        'k.id',
        'k.user_id',
        'u.username',
        'u.email',
        'k.status',
        "$submittedExpr AS submitted"
    ];

    if ($hasDocType) $fields[] = 'k.document_type'; else if ($hasDataJson) $fields[] = 'k.data AS _data';
    if ($hasDocNumber) $fields[] = 'k.document_number';
    if ($hasDocFront) $fields[] = 'k.document_front';
    if ($hasDocBack) $fields[] = 'k.document_back';

    $sql = 'SELECT ' . implode(', ', $fields) . ' FROM kyc_requests k LEFT JOIN users u ON k.user_id = u.id ORDER BY ' . $orderBy;
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // If legacy JSON data is present, hydrate fields
    if ($hasDataJson && !$hasDocType) {
        foreach ($rows as &$row) {
            if (!empty($row['_data'])) {
                $d = json_decode($row['_data'], true);
                if (is_array($d)) {
                    if (!isset($row['document_type']) && isset($d['document_type'])) $row['document_type'] = $d['document_type'];
                    if (!isset($row['document_number']) && isset($d['document_number'])) $row['document_number'] = $d['document_number'];
                    if (!isset($row['document_front']) && isset($d['document_front'])) $row['document_front'] = $d['document_front'];
                    if (!isset($row['document_back']) && isset($d['document_back'])) $row['document_back'] = $d['document_back'];
                }
            }
            unset($row['_data']);
        }
        unset($row);
    }

    // Add backend URL prefix to image paths for frontend display
    $backendUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . 
                  '://' . $_SERVER['HTTP_HOST'];
    
    foreach ($rows as &$row) {
        if (!empty($row['document_front']) && !str_starts_with($row['document_front'], 'http')) {
            $row['document_front'] = $backendUrl . '/' . $row['document_front'];
        }
        if (!empty($row['document_back']) && !str_starts_with($row['document_back'], 'http')) {
            $row['document_back'] = $backendUrl . '/' . $row['document_back'];
        }
        if (!empty($row['selfie']) && !str_starts_with($row['selfie'], 'http')) {
            $row['selfie'] = $backendUrl . '/' . $row['selfie'];
        }
    }
    unset($row);
    
    echo json_encode(["success" => true, "kyc" => $rows, "endpointVersion" => "2025-10-21"]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(["success" => false, "error" => $e->getMessage()]);
}
