<?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");

$shop_url = "nzafrihair.myshopify.com";
$access_token = "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"; 
$db_host = "localhost";
$db_user = "afrihair_wh";
$db_pass = "wXZ@YMO[ue5efq~b";
$db_name = "order_locks";

$db = new mysqli($db_host, $db_user, $db_pass, $db_name);
$input = json_decode(file_get_contents("php://input"), true);
$action = $_GET['action'] ?? $input['action'] ?? 'get_orders';

function shopify_call($method, $endpoint, $data = []) {
    global $shop_url, $access_token;
    $url = "https://{$shop_url}/admin/api/2024-01/{$endpoint}";
    $curl = curl_init();
    $headers = ["X-Shopify-Access-Token: $access_token", "Content-Type: application/json"];
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    if ($method === 'POST' || $method === 'PUT') {
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
    }
    $response = curl_exec($curl);
    curl_close($curl);
    return json_decode($response, true);
}

if ($action == 'update_pick') {
    $order_id = $input['order_id'];
    $sku = $input['sku'];
    $qty = (int)$input['qty'];
    $staff = $input['staff'];

    $stmt = $db->prepare("INSERT INTO picked_items (order_id, sku, picked_qty, picked_by) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE picked_qty = ?, picked_by = ?");
    $stmt->bind_param("ssisis", $order_id, $sku, $qty, $staff, $qty, $staff);
    $stmt->execute();
    echo json_encode(['success' => true]); exit;
}

if ($action == 'get_picks') {
    $res = $db->query("SELECT order_id, sku, picked_qty, picked_by FROM picked_items");
    $picks = [];
    while ($row = $res->fetch_assoc()) {
        if (!isset($picks[$row['order_id']])) $picks[$row['order_id']] = [];
        $picks[$row['order_id']][$row['sku']] = [
            'qty' => (int)$row['picked_qty'],
            'by' => $row['picked_by']
        ];
    }
    echo json_encode($picks); exit;
}

if ($action == 'add_note') {
    $order_id = $input['order_id'];
    $note_text = preg_replace('/[^a-zA-Z0-9 ]/', '', $input['note']); 
    $get = shopify_call('GET', "orders/{$order_id}.json?fields=tags");
    $tags = explode(',', $get['order']['tags'] ?? '');
    $clean_tags = [];
    foreach($tags as $t) if (trim($t) && stripos(trim($t), 'Note:') !== 0) $clean_tags[] = trim($t);
    if (!empty($note_text)) $clean_tags[] = "Note: $note_text";
    shopify_call('PUT', "orders/{$order_id}.json", ['order' => ['id' => $order_id, 'tags' => implode(',', $clean_tags)]]);
    echo json_encode(['success' => true]); exit;
}

if ($action == 'check_lock') {
    $order_id = $_GET['order_id'];
    $staff = $_GET['staff'];
    $stmt = $db->prepare("SELECT staff_name FROM order_locks WHERE order_id = ? AND staff_name != ?");
    $stmt->bind_param("ss", $order_id, $staff);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    if ($res) { echo json_encode(["locked_by" => $res['staff_name']]); } 
    else {
        $stmt = $db->prepare("INSERT INTO order_locks (order_id, staff_name) VALUES (?, ?) ON DUPLICATE KEY UPDATE staff_name = ?, last_seen = NOW()");
        $stmt->bind_param("sss", $order_id, $staff, $staff);
        $stmt->execute();
        echo json_encode(["status" => "locked", "locked_by" => null]);
    }
    exit;
}

if ($action == 'release_lock') {
    $order_id = $_GET['order_id'];
    $staff = $_GET['staff'];
    $stmt = $db->prepare("DELETE FROM order_locks WHERE order_id = ? AND staff_name = ?");
    $stmt->bind_param("ss", $order_id, $staff);
    $stmt->execute();
    echo json_encode(["status" => "released"]);
    exit;
}

if ($action == 'get_stocks') {
    $res = $db->query("SELECT * FROM packie_stocks");
    $stocks = [];
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $stocks[] = [
                'id' => (int)$row['id'],
                'name' => $row['name'],
                'serviceType' => (int)$row['serviceType'],
                'height' => (float)$row['height'],
                'width' => (float)$row['width'],
                'length' => (float)$row['length'],
                'weight' => (float)$row['weight'],
                'cubicWeight' => (float)$row['cubicWeight']
            ];
        }
    }
    echo json_encode($stocks);
    exit;
}

if ($action == 'check_status') {
    // A lightning-fast endpoint for the app to poll while waiting for the background worker
    $order_name = $_GET['order_name'] ?? $input['order_name'] ?? '';
    $clean_num = str_replace('#', '', $order_name);
    
    $stmt = $db->prepare("SELECT packie_status FROM packie_cache WHERE shopify_order_number = ?");
    $stmt->bind_param("s", $clean_num);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    
    echo json_encode(['packie_status' => $res ? $res['packie_status'] : 'PENDING']);
    exit;
}

if ($action == 'get_custom_quote') {
    $order_name = $_GET['order_name'] ?? '';
    $w = $_GET['w'] ?? 0;
    $l = $_GET['l'] ?? 0;
    $h = $_GET['h'] ?? 0;
    $weight = $_GET['weight'] ?? 0;

    $shopify_num_str = str_replace('#', '', $order_name);
    $packie_token = file_exists(__DIR__ . '/packie_token.txt') ? trim(file_get_contents(__DIR__ . '/packie_token.txt')) : null;

    if ($packie_token && $shopify_num_str) {
        $headers = ['Content-Type: application/json', 'Accept: application/json', 'Authorization: Bearer ' . $packie_token];
        
        // 1. Get the actual customer address from Packie
        $ch_search = curl_init("https://www.packie.co.nz/api/Orders/get-orders?status=1&search={$shopify_num_str}&integrationId=0&page=1&perPage=5");
        curl_setopt($ch_search, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch_search, CURLOPT_HTTPHEADER, $headers);
        $search_res = json_decode(curl_exec($ch_search), true);
        curl_close($ch_search);

        $packie_order = null;
        if (isset($search_res['result']['orders'])) {
            foreach ($search_res['result']['orders'] as $po) {
                if ($po['orderNumber'] === $shopify_num_str) { $packie_order = $po; break; }
            }
        }

        if ($packie_order) {
            // 2. Ask Packie for the quotes!
            $label_payload = [
                "consignmentParcels" => [[
                    "id" => "0", "height" => (string)$h, "width" => (string)$w, "length" => (string)$l,
                    "itemSKU" => "", "weight" => (string)$weight, "isPallet" => false, "dangerousGoodsRate" => 0,
                    "internationalDeclaredValue" => "0.00", "markupRate" => 0, "quantity" => "1", "serviceType" => 1
                ]],
                "hasDangerousGoods" => false, "integratedOrderId" => $packie_order['id'], "integrationType" => 1,
                "isInternational" => false, "receiver" => $packie_order['receiver'], "sender" => $packie_order['sender'],
                "shippingDescription" => "Fastest Delivery", "shippingMethod" => "Fastest Delivery", "signatureRequired" => false
            ];

            $ch_calc = curl_init("https://www.packie.co.nz/api/Consignments/calculate");
            curl_setopt($ch_calc, CURLOPT_POST, true);
            curl_setopt($ch_calc, CURLOPT_POSTFIELDS, json_encode($label_payload));
            curl_setopt($ch_calc, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch_calc, CURLOPT_HTTPHEADER, $headers);
            $calc_res = json_decode(curl_exec($ch_calc), true);
            curl_close($ch_calc);

            echo json_encode($calc_res['result']['rates'] ?? []);
            exit;
        }
    }
    echo json_encode([]);
    exit;
}

if ($action == 'mark_packed') {
    $order_id = $input['order_id'];
    $order_name = $input['order_name'] ?? '';
    
    // Safely wrap variables for the background command line execution
    $safe_order_id = escapeshellarg($order_id);
    $safe_staff = escapeshellarg($input['staff'] ?? 'Staff');
    $safe_stock = escapeshellarg(empty($input['stock_id']) ? 'none' : $input['stock_id']); 
    
    // NEW: Grab custom box info
    $safe_rate = escapeshellarg(empty($input['rate_id']) ? 'none' : $input['rate_id']);
    $safe_w = escapeshellarg($input['w'] ?? 0);
    $safe_l = escapeshellarg($input['l'] ?? 0);
    $safe_h = escapeshellarg($input['h'] ?? 0);
    $safe_weight = escapeshellarg($input['weight'] ?? 0);

    $shopify_num_str = str_replace('#', '', $order_name);

    // 1. Instantly clear locks and pick lists
    $db->query("DELETE FROM order_locks WHERE order_id = '$order_id'");
    $db->query("DELETE FROM picked_items WHERE order_id = '$order_id'");
    
    // 2. Instantly mark as PRINTED in cache so the app hides it forever
    if ($shopify_num_str) {
        $stmt = $db->prepare("UPDATE packie_cache SET packie_status = 'PRINTED' WHERE shopify_order_number = ?");
        $stmt->bind_param("s", $shopify_num_str);
        $stmt->execute();
    }
    
    // 3. Fire off the slow API work to the background and immediately close the connection!
    //exec("/usr/local/bin/php " . __DIR__ . "/background_pack.php $safe_order_id $safe_staff $safe_stock > /dev/null 2>&1 &");
    exec("/usr/local/bin/php " . __DIR__ . "/background_pack.php $safe_order_id $safe_staff $safe_stock $safe_rate $safe_w $safe_l $safe_h $safe_weight > /dev/null 2>&1 &");
    
    // 4. Tell the app "It's done!" in 0.05 seconds
    echo json_encode(['success' => true]); 
    exit;
}

if ($action == 'update_address') {
    $input = json_decode(file_get_contents('php://input'), true);
    $order_id = $input['order_id'] ?? null;
    
    // 0. Setup Logger
    $log_file = __DIR__ . '/address_debug.txt';
    file_put_contents($log_file, "\n\n=== START UPDATE: " . date('Y-m-d H:i:s') . " ===\n", FILE_APPEND);
    file_put_contents($log_file, "Input Payload: " . json_encode($input) . "\n", FILE_APPEND);

    if (!$order_id) { 
        file_put_contents($log_file, "ERROR: No order ID\n", FILE_APPEND);
        echo json_encode(["success" => false, "error" => "No order ID"]); 
        exit; 
    }

    // 1. Fetch current order info from Shopify
    $get_res = shopify_call('GET', "orders/{$order_id}.json?fields=tags,name,email,phone,shipping_address");
    $current_tags = $get_res['order']['tags'] ?? '';
    $order_name = str_replace('#', '', $get_res['order']['name'] ?? '');
    file_put_contents($log_file, "Order Name: {$order_name}\n", FILE_APPEND);
    
    $ship = $get_res['order']['shipping_address'] ?? [];
    $contactName = $ship['name'] ?? 'Customer';
    $company = $ship['company'] ?? '';
    $phone = $ship['phone'] ?? $get_res['order']['phone'] ?? '';
    $email = $get_res['order']['email'] ?? '';

    // Clean ALL warning and rural tags from Shopify
    $tags_array = array_map('trim', explode(',', $current_tags));
    $clean_tags = array_filter($tags_array, function($t) {
        $t_clean = strtolower(trim($t));
        return !in_array($t_clean, ['check address', 'risk warning', 'rural', 'rural delivery', 'rd', 'rd address']);
    });
    $new_tags_string = implode(', ', $clean_tags);

    // 2. Push to Shopify
    $update_payload = [
        "order" => [
            "id" => $order_id,
            "tags" => $new_tags_string,
            "shipping_address" => [
                "address1" => $input['address1'] ?? '',
                "address2" => $input['address2'] ?? '',
                "city" => $input['city'] ?? '',
                "zip" => $input['zip'] ?? ''
            ]
        ]
    ];
    $update_res = shopify_call('PUT', "orders/{$order_id}.json", $update_payload);
    file_put_contents($log_file, "Shopify Update Success: " . (isset($update_res['order']) ? 'YES' : 'NO') . "\n", FILE_APPEND);

    // 3. THE PACKIE PIGGYBACK
    $new_status = 'INVALID'; // Default to error if we can't find it
    $packie_token = file_exists(__DIR__ . '/packie_token.txt') ? trim(file_get_contents(__DIR__ . '/packie_token.txt')) : null;
    $packie_order_id = null;
    
    if ($packie_token && $order_name) {
        $headers = ['Content-Type: application/json', 'Accept: application/json', 'Authorization: Bearer ' . $packie_token];

        // A. Brute-force search Packie's statuses to find the order ID
        $statuses_to_try = [1, 2, 3, 4, 5, 0, 99]; 
        $found_status = 'NONE';
        
        foreach ($statuses_to_try as $stat) {
            $ch_search = curl_init("https://www.packie.co.nz/api/Orders/get-orders?status={$stat}&search={$order_name}&integrationId=0&page=1&perPage=5");
            curl_setopt($ch_search, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch_search, CURLOPT_HTTPHEADER, $headers);
            $search_res = json_decode(curl_exec($ch_search), true);
            curl_close($ch_search);

            if (!empty($search_res['result']['orders'])) {
                foreach ($search_res['result']['orders'] as $po) {
                    if ($po['orderNumber'] === $order_name) { 
                        $packie_order_id = $po['id']; 
                        $found_status = $stat;
                        break 2; // Found it! Break out of both loops instantly.
                    }
                }
            }
        }
        
        file_put_contents($log_file, "Packie Order ID Found: " . ($packie_order_id ?? 'NONE') . " (in status bucket: {$found_status})\n", FILE_APPEND);

        if ($packie_order_id) {
            // B. FORMAT 1: Update Packie Database 
            $packie_payload = [
                "company" => $company, "contactName" => $contactName, "email" => $email, "phone" => $phone,
                "address1" => $input['address1'] ?? "", "building" => "", "city" => $input['city'] ?? "",
                "country" => "NZ", "notes" => "", "state" => "", "unit" => "",
                "postcode" => $input['zip'] ?? "", 
                "street" => $input['address1'] ?? "", 
                "suburb" => $input['address2'] ?? ""
            ];

            file_put_contents($log_file, "EditReceiver Payload: " . json_encode($packie_payload) . "\n", FILE_APPEND);

            $ch_edit = curl_init("https://www.packie.co.nz/api/Orders/EditReceiver/" . $packie_order_id);
            curl_setopt($ch_edit, CURLOPT_CUSTOMREQUEST, "POST"); 
            curl_setopt($ch_edit, CURLOPT_POSTFIELDS, json_encode($packie_payload));
            curl_setopt($ch_edit, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch_edit, CURLOPT_HTTPHEADER, $headers);
            $edit_raw = curl_exec($ch_edit);
            curl_close($ch_edit);
            
            file_put_contents($log_file, "EditReceiver Response: " . $edit_raw . "\n", FILE_APPEND);

            // C. FORMAT 2: Verify Rate with Packie Calculator
            $calc_receiver = [
                "contactName" => $contactName, "company" => $company, "building" => "", 
                "suburb" => $input['address2'] ?? "", 
                "city" => $input['city'] ?? "", "country" => "NZ", "phoneNumber" => $phone, "email" => $email,
                "streetAddress" => $input['address1'] ?? "",
                "postCode" => $input['zip'] ?? "" 
            ];

            $check_payload = [
                "consignmentParcels" => [["id" => "4", "height" => "29.7", "width" => "1", "length" => "21", "weight" => "1", "quantity" => "1", "serviceType" => 4]],
                "hasDangerousGoods" => false, "integrationType" => 1, "isInternational" => false,
                "receiver" => $calc_receiver,
                "sender" => ["contactName" => "Daniel", "company" => "Afrihair", "streetAddress" => "247 Cuba Street", "city" => "Palmerston North", "postCode" => "4410", "country" => "NZ"]
            ];

            file_put_contents($log_file, "Calculate Payload: " . json_encode($check_payload) . "\n", FILE_APPEND);

            $ch_calc = curl_init("https://www.packie.co.nz/api/Consignments/calculate");
            curl_setopt($ch_calc, CURLOPT_POST, true); 
            curl_setopt($ch_calc, CURLOPT_POSTFIELDS, json_encode($check_payload));
            curl_setopt($ch_calc, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch_calc, CURLOPT_HTTPHEADER, $headers);
            $calc_raw = curl_exec($ch_calc);
            curl_close($ch_calc);
            
            file_put_contents($log_file, "Calculate Response: " . $calc_raw . "\n", FILE_APPEND);

            // D. Check what the Calculator says
            $calc_res = json_decode($calc_raw, true);
            $new_status = 'READY'; // Assume the address is fixed
            if (isset($calc_res['success']) && $calc_res['success'] == false) {
                $new_status = 'INVALID';
                file_put_contents($log_file, "Calc failed (success=false)\n", FILE_APPEND);
            } else if (!empty($calc_res['result']['rates'])) {
                $is_rural = false;
                foreach ($calc_res['result']['rates'] as $rate) {
                    if ((isset($rate['rural_rate']) && $rate['rural_rate'] > 0) || 
                        (isset($rate['parcels'][0]['rural_rate']) && $rate['parcels'][0]['rural_rate'] > 0) ||
                        (isset($rate['parcels'][0]['is_rural']) && $rate['parcels'][0]['is_rural'] == true)) {
                        $is_rural = true;
                        break;
                    }
                }
                if ($is_rural) { 
                    $new_status = 'RURAL'; 
                    file_put_contents($log_file, "Calc detected RURAL flag/rate.\n", FILE_APPEND);
                } else {
                    file_put_contents($log_file, "Calc detected NO rural flags. Setting READY.\n", FILE_APPEND);
                }
            } else {
                $new_status = 'INVALID';
                file_put_contents($log_file, "Calc returned no rates.\n", FILE_APPEND);
            }
        } else {
            file_put_contents($log_file, "Skipped Packie Update: No Packie Order ID found.\n", FILE_APPEND);
        }
    } else {
        file_put_contents($log_file, "Skipped Packie Update: Missing Token or Order Name.\n", FILE_APPEND);
    }

    file_put_contents($log_file, "Final DB Status to write: {$new_status}\n", FILE_APPEND);

// 4. Force local database to verified status
    $stmt = $db->prepare("UPDATE packie_cache SET packie_status = ? WHERE shopify_order_number = ?");
    $stmt->bind_param("ss", $new_status, $order_name);
    $stmt->execute();
    
    echo json_encode(["success" => true, "new_status" => $new_status]);
    exit;
}


if ($action == 'address_autocomplete') {
    $term = $_GET['term'] ?? '';
    if (strlen($term) < 3) { echo json_encode(["result" => []]); exit; }

    $packie_token = file_exists(__DIR__ . '/packie_token.txt') ? trim(file_get_contents(__DIR__ . '/packie_token.txt')) : null;
    if ($packie_token) {
        $headers = ['Accept: application/json', 'Authorization: Bearer ' . $packie_token];
        // Ping Packie's hidden endpoint
        $url = "https://www.packie.co.nz/api/Address/search-domestic-address?term=" . urlencode($term);

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $res = curl_exec($ch);
        curl_close($ch);

        echo $res; // Pass it straight back to the app!
    } else {
        echo json_encode(["result" => []]);
    }
    exit;
}


if ($action == 'get_orders') {
    // 1. Fetch live orders from Shopify first
    $orders_res = shopify_call('GET', 'orders.json?status=open&fulfillment_status=unfulfilled&limit=50');
    $raw_orders = $orders_res['orders'] ?? [];
    
    // 2. Grab our local cache of Packie statuses
    $packie_statuses = [];
    $res = $db->query("SELECT shopify_order_number, packie_status FROM packie_cache");
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $packie_statuses[$row['shopify_order_number']] = $row['packie_status'];
        }
    }

    // 3. REACTIVE SYNC CHECK: Are there any Shopify orders missing from our cache?
    $needs_import = false;
    foreach ($raw_orders as $o) {
        $clean_order_num = str_replace('#', '', $o['name']);
        if (!isset($packie_statuses[$clean_order_num])) {
            $needs_import = true;
            break; // We found at least one new order, trigger the import!
        }
    }

    // 4. Fire the background worker with the correct instructions
    if ($needs_import) {
        // Force Packie to import from Shopify
        exec("/usr/local/bin/php " . __DIR__ . "/cron_sync.php > /dev/null 2>&1 &");
    } else {
        // Tell the worker to skip the import and just update the UI stocks/statuses
        exec("/usr/local/bin/php " . __DIR__ . "/cron_sync.php skip_import > /dev/null 2>&1 &");
    }

    // 5. Build the images map and the final output for the app (Normal logic continues...)
    $product_ids = [];
    foreach ($raw_orders as $o) foreach($o['line_items'] as $item) if($item['product_id']) $product_ids[] = $item['product_id'];

    $images_map = [];
    if (!empty($product_ids)) {
        $ids_string = implode(',', array_slice(array_unique($product_ids), 0, 100));
        $prod_res = shopify_call('GET', "products.json?ids={$ids_string}&fields=id,image");
        if (isset($prod_res['products'])) foreach ($prod_res['products'] as $p) $images_map[$p['id']] = $p['image']['src'] ?? null;
    }

    $output = [];
    foreach ($raw_orders as $o) {
        $clean_order_num = str_replace('#', '', $o['name']);
        $p_status = $packie_statuses[$clean_order_num] ?? 'PENDING';

        if ($p_status === 'PRINTED') continue; // Hide printed orders

        $skip_order = false;
        $display_note = '';
        $is_risky = false;
        $needs_address_check = false; // <--- NEW
        
        $tags = explode(',', $o['tags'] ?? '');
        foreach($tags as $t) {
            $clean_tag = trim($t);
            if(stripos($clean_tag, 'Note:') === 0) $display_note = trim(substr($clean_tag, 5));
            if(strcasecmp($clean_tag, 'Risk Warning') === 0) $is_risky = true; // <--- NEW
            if(strcasecmp($clean_tag, 'Check Address') === 0) $needs_address_check = true; // <--- NEW
            if(strcasecmp($clean_tag, 'Packed') === 0 || stripos($clean_tag, 'Packed by') === 0) {
                $skip_order = true;
            }
        }
        
        if ($skip_order) continue; 

        $items = [];
        foreach($o['line_items'] as $i) {
            $items[] = [
                'name' => $i['name'], 'qty' => $i['quantity'], 'sku' => $i['sku'] ?: 'No SKU', 
                'img' => $images_map[$i['product_id']] ?? 'https://placehold.co/100x100/png?text=No+Img'
            ];
        }

        $method = $o['shipping_lines'][0]['title'] ?? 'Standard';
        $is_pickup = (stripos($method, 'Pickup') !== false || stripos($method, 'Collect') !== false || stripos($method, '247 Cuba') !== false);

        $address_line = $o['shipping_address']['address1'] ?? '';
        $city = $o['shipping_address']['city'] ?? '';
        $full_address = trim($address_line . ($city ? ', ' . $city : '')); 
        $postcode = $o['shipping_address']['zip'] ?? '';

        $output[] = [
            'id' => (string)$o['id'], 'name' => $o['name'], 'customer' => $o['shipping_address']['name'] ?? 'Customer',
            'address' => $full_address, 'postcode' => $postcode, 
            'country' => $o['shipping_address']['country_code'] ?? '', 'method' => $method,
            'is_pickup' => $is_pickup, 'unpaid' => ($o['financial_status'] !== 'paid'), 
            'note' => $display_note, 'items' => $items,
            'packie_status' => $p_status,
            'is_risky' => $is_risky,                       // <--- NEW
            'needs_address_check' => $needs_address_check  // <--- NEW
        ];
    }
    echo json_encode($output);
}


?>