<?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);

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

// Fetch KYC request
$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 status
if ($action === 'approve_kyc') {
    $status = 1;
} elseif ($action === 'reject_kyc') {
    $status = 2;
} else {
    echo json_encode(["success" => false, "error" => "Invalid action"]);
    exit;
}

// Update kycupload
$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()) {

    // ============================
    // FIXED + DEBUG LOGS ADDED
    // ============================
    $user_id = $kycRequest['user_id'];

    if (!$user_id || $user_id == 0) {
        echo json_encode([
            "success" => false,
            "error" => "User ID missing in kycupload table",
            "debug" => $kycRequest
        ]);
        exit;
    }

    $loginStatus = ($status === 1) ? 2 : 3;

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

    if (!$stmtUser->execute()) {
        echo json_encode([
            "success" => false,
            "error" => "Failed to update loginusers",
            "mysqli_error" => $stmtUser->error,
            "user_id" => $user_id
        ]);
        exit;
    }

    $stmtUser->close();
    // ============================

    // Send email on approval
    if (EMAIL_AUTOMATION_ENABLED && $status === 1) {
        $stmtUserDetails = $conn->prepare("SELECT email, first_name, last_name FROM loginusers WHERE id = ?");
        $stmtUserDetails->bind_param("i", $user_id);
        $stmtUserDetails->execute();
        $userResult = $stmtUserDetails->get_result();
        
        if ($userDetails = $userResult->fetch_assoc()) {
            $mailSystem = getMailSystem();
            $fullName = trim($userDetails['first_name'] . ' ' . $userDetails['last_name']);
            $mailSystem->sendKYCApproved($userDetails['email'], $fullName);
        }
        $stmtUserDetails->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]);
}

?>
