<?php

header("Content-Type: application/json");

require_once '../config/database.php';

$db = getDB();

$order_number =
$_GET['order_number'] ?? '';

if(empty($order_number)){

    echo json_encode([

        "success" => false,
        "message" => "Order number missing"
    ]);

    exit;
}

$order_number =
mysqli_real_escape_string(
    $db,
    $order_number
);

$result =
$db->query("SELECT * FROM orders
WHERE order_number='$order_number'
LIMIT 1");

if(!$result){

    echo json_encode([

        "success" => false,
        "message" => $db->error
    ]);

    exit;
}

if($result->num_rows == 0){

    echo json_encode([

        "success" => false,
        "message" => "Order not found"
    ]);

    exit;
}

$order =
$result->fetch_assoc();

$status =
$order['status'];

$steps = [

    [
        "title" => "Pending",
        "active" => true
    ],

    [
        "title" => "Packed",
        "active" => false
    ],

    [
        "title" => "Dispatched",
        "active" => false
    ],

    [
        "title" => "Delivered",
        "active" => false
    ],
];

if($status == "Packed"){

    $steps[1]['active'] = true;
}

if($status == "Dispatched"){

    $steps[1]['active'] = true;
    $steps[2]['active'] = true;
}

if($status == "Delivered"){

    $steps[1]['active'] = true;
    $steps[2]['active'] = true;
    $steps[3]['active'] = true;
}

echo json_encode([

    "success" => true,

    "order" => [

        "order_number" =>
        $order['order_number'],

        "status" =>
        $status,

        "created_at" =>
        $order['created_at'],

        "steps" => $steps
    ]
]);