<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

include_once __DIR__ . '/connection.php';
include_once __DIR__ . '/config.php';

// Optional search filter (by trade_id or email)
$search = $_GET['search'] ?? null;

$query = "SELECT id, trade_id, email, kyc_type, kyc_frontside, front_image, 
                 kyc_backside, back_image, registered_date_js, 
                 Admin_Remark, Admin_Remark_Date, Status 
          FROM kycupload";

$params = [];
$types = "";

// If search filter is provided
if ($search) {
    $query .= " WHERE trade_id LIKE ? OR email LIKE ?";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $types = "ss";
}

$stmt = $conn->prepare($query);

if ($search) {
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$result = $stmt->get_result();

$kycDocs = [];
while ($row = $result->fetch_assoc()) {
    $kycDocs[] = [
        "id" => $row['id'],
        "trade_id" => $row['trade_id'],
        "email" => $row['email'],
        "kyc_type" => $row['kyc_type'],
        "kyc_frontside" => $row['kyc_frontside'],
        "front_image" => $row['front_image'],
        "kyc_backside" => $row['kyc_backside'],
        "back_image" => $row['back_image'],
        "registered_date_js" => $row['registered_date_js'],
        "Admin_Remark" => $row['Admin_Remark'],
        "Admin_Remark_Date" => $row['Admin_Remark_Date'],
        "Status" => intval($row['Status']) // 0 = Pending, 1 = Approved, 2 = Rejected
    ];
}

echo json_encode([
    "success" => true,
    "kyc_documents" => $kycDocs
]);

$stmt->close();
$conn->close();
