<?php
header('Content-Type: application/json');
require_once '../../config/config.php';
require_once '../../config/middleware.php';

try {
    $id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
    $waybill = isset($_GET['waybill']) ? trim($_GET['waybill']) : '';

    if ($id <= 0 && $waybill === '') {
        echo json_encode(['status' => 'error', 'message' => 'Provide id or waybill']);
        exit;
    }

    $sql = "SELECT b.*,
            c.partner_name as courier_name, c.partner_code as courier_code,
            p.name as pickup_point_name, p.pickup_point_code, p.address as pickup_address, p.phone as pickup_phone, p.city as pickup_city, p.pin as pickup_pin, p.branch_id as branch_id,
            br.branch_name, co.company_name
            FROM tbl_bookings b
            LEFT JOIN tbl_courier_partner c ON b.courier_id = c.id
            LEFT JOIN tbl_pickup_points p ON b.pickup_point_id = p.id
            LEFT JOIN tbl_branch br ON p.branch_id = br.id
            LEFT JOIN tbl_company co ON br.company_id = co.id
            WHERE 1=1";
    $params = [];

    if ($id > 0) {
        $sql .= " AND b.id = :id";
        $params[':id'] = $id;
    } else {
        $sql .= " AND b.waybill_no = :waybill";
        $params[':waybill'] = $waybill;
    }

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        echo json_encode(['status' => 'error', 'message' => 'Booking not found']);
        exit;
    }

    // api_response is stored as JSON (full ShipmentData item: {"Shipment":{...}})
    if (!empty($row['api_response'])) {
        $row['ShipmentData'] = is_string($row['api_response']) ? json_decode($row['api_response'], true) : $row['api_response'];
    } else {
        $row['ShipmentData'] = null;
    }

    echo json_encode(['status' => 'success', 'data' => $row]);

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
