<?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__ . '/../unified_config.php';
include_once __DIR__ . '/../connection.php';

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

$user_id = $data['user_id'] ?? 0;
$action = $data['action'] ?? ''; // 'verify' or 'unverify'
$admin_remark = $data['admin_remark'] ?? '';

if (!$user_id || !in_array($action, ['verify', 'unverify'])) {
    echo json_encode(["success" => false, "error" => "Invalid input"]);
    exit;
}

// Determine KYC status
$kyc_status = ($action === 'verify') ? 1 : 0;
$kycupload_status = ($action === 'verify') ? 1 : 2; // 1=approved, 2=rejected in kycupload

// Update loginusers table
$stmtUser = $conn->prepare("UPDATE loginusers SET kyc_status = ? WHERE id = ?");
$stmtUser->bind_param("ii", $kyc_status, $user_id);

// Update latest kycupload record for this user
$stmtKyc = $conn->prepare("UPDATE kycupload SET Status = ?, Admin_Remark = ?, Admin_Remark_Date = NOW() WHERE user_id = ? ORDER BY id DESC LIMIT 1");
$stmtKyc->bind_param("isi", $kycupload_status, $admin_remark, $user_id);

if ($stmtUser->execute() && $stmtKyc->execute()) {

    // Optionally send email if verify
    $email_sent = false;
    if (EMAIL_AUTOMATION_ENABLED && $action === 'verify') {
        $stmtEmail = $conn->prepare("SELECT email, first_name, last_name FROM loginusers WHERE id = ?");
        $stmtEmail->bind_param("i", $user_id);
        $stmtEmail->execute();
        $result = $stmtEmail->get_result();
        if ($userDetails = $result->fetch_assoc()) {
            $mailSystem = getMailSystem();
            $fullName = trim($userDetails['first_name'] . ' ' . $userDetails['last_name']);
            $emailResult = $mailSystem->sendKYCApproved($userDetails['email'], $fullName);
            $email_sent = $emailResult['success'];
        }
        $stmtEmail->close();
    }

    echo json_encode([
        "success" => true,
        "message" => "KYC " . ($kyc_status ? "verified" : "unverified") . " successfully",
        "email_sent" => $email_sent
    ]);
} else {
    echo json_encode(["success" => false, "error" => "Failed to update KYC: " . $conn->error]);
}

$stmtUser->close();
$stmtKyc->close();
?>
