<?php
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

if (!empty($origin)) {
    header("Access-Control-Allow-Origin: $origin");
    header("Access-Control-Allow-Credentials: true");
} else {
    header("Access-Control-Allow-Origin: *");
}

header('Content-Type: application/json');
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header('Access-Control-Max-Age: 1728000');

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

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

$input = file_get_contents("php://input");
$data = json_decode($input, true);

$kyc_id = $data['kyc_id'] ?? 0;
$admin_remark = $data['admin_remark'] ?? '';
$action = $data['action'] ?? '';

// Fetch the KYC request regardless of its status
$stmt = $conn->prepare("SELECT * FROM kycupload WHERE id = ?");
$stmt->bind_param("i", $kyc_id);
$stmt->execute();
$kycRequest = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$kycRequest) {
    echo json_encode(["success" => false, "error" => "KYC request not found"]);
    exit;
}

// Determine new status based on action
if ($action === 'approve_kyc') {
    $status = 1; // Approved
} elseif ($action === 'reject_kyc') {
    $status = 2; // Rejected
} else {
    echo json_encode(["success" => false, "error" => "Invalid action"]);
    exit;
}

// Update kycupload table
$stmtUpdate = $conn->prepare("UPDATE kycupload SET Status = ?, Admin_Remark = ?, Admin_Remark_Date = NOW() WHERE id = ?");
$stmtUpdate->bind_param("isi", $status, $admin_remark, $kyc_id);

if ($stmtUpdate->execute()) {
    // ✅ Update loginusers table
    $user_id = $kycRequest['user_id'];
    $stmtUser = $conn->prepare("UPDATE loginusers SET kyc_status = ? WHERE id = ?");
    $stmtUser->bind_param("ii", $status, $user_id);
    $stmtUser->execute();
    $stmtUser->close();

    $msg = ($status === 1) ? "KYC approved successfully" : "KYC rejected successfully";
    echo json_encode(["success" => true, "message" => $msg]);
} else {
    echo json_encode(["success" => false, "error" => "Failed to update KYC: ".$stmtUpdate->error]);
}
?>
