<?php
header('Content-Type: application/json');

// Path to the orders JSON file
$ordersFile = '../database/orders.json';

// Read the input
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, true);

if (!isset($input['phone'])) {
    echo json_encode(['status' => 'error', 'message' => 'Phone number is required']);
    exit;
}

$searchPhone = trim($input['phone']);

// Load orders
if (!file_exists($ordersFile)) {
    echo json_encode(['status' => 'error', 'message' => 'Orders file not found']);
    exit;
}

$ordersJSON = file_get_contents($ordersFile);
$orders = json_decode($ordersJSON, true);

if (!is_array($orders)) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid orders data']);
    exit;
}

// Filter orders by phone
$matchedOrders = array_filter($orders, function ($order) use ($searchPhone) {
    return isset($order['phone']) && $order['phone'] === $searchPhone;
});

// If no match found
if (empty($matchedOrders)) {
    echo json_encode(['status' => 'not_found', 'message' => 'No order found for this phone number']);
    exit;
}

// Sort matched orders by created_at DESC
usort($matchedOrders, function ($a, $b) {
    return strtotime($b['created_at']) - strtotime($a['created_at']);
});

// Get the most recent entry
$latest = $matchedOrders[0];

// Respond with selected fields
$response = [
    'status' => 'success',
    'name' => $latest['name'] ?? '',
    'address' => $latest['address'] ?? '',
    'customerType' => $latest['customerType'] ?? '',
    'countryCode' => $latest['countryCode'] ?? '',
    'orderId' => $latest['orderId'] ?? '',
    'created_at' => $latest['created_at'] ?? ''
];

echo json_encode($response);
