<?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 == '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']); 

    $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 &");
    
    // 4. Tell the app "It's done!" in 0.05 seconds
    echo json_encode(['success' => true]); 
    exit;
}

if ($action == 'get_orders') {
    exec("/usr/local/bin/php " . __DIR__ . "/cron_sync.php > /dev/null 2>&1 &");

    $orders_res = shopify_call('GET', 'orders.json?status=open&fulfillment_status=unfulfilled&limit=50');
    $raw_orders = $orders_res['orders'] ?? [];
    
    $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;
    }

    $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'];
        }
    }

    $output = [];
    foreach ($raw_orders as $o) {
        $clean_order_num = str_replace('#', '', $o['name']);
        $p_status = $packie_statuses[$clean_order_num] ?? 'PENDING';

        // --- NEW: INSTANTLY HIDE ORDERS IN THE PRINT QUEUE ---
        // Even if Shopify hasn't updated yet, this stops it showing on the scanner
        if ($p_status === 'PRINTED') continue;

        $skip_order = false;
        $display_note = '';
        $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, '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
        ];
    }
    echo json_encode($output);
}
?>