<?php 
require dirname( dirname(__FILE__) ).'/api/Prozigzig.php';
$h = new Prozigzig();
header('Content-type: application/json');

$data = json_decode(file_get_contents('php://input'), true);

if (empty($data['bus_id'])) {
    $returnArr = array("ResponseCode" => "401", "Result" => "false", "ResponseMsg" => "Something Went Wrong!");
    echo json_encode($returnArr);
    exit;
}

$bus_id = intval($data['bus_id']);
$status = $data['status'] ?? ''; // optional filter
$parcelList = [];


$allowedStatuses = ['Current', 'History'];
$status = in_array($status, $allowedStatuses) ? $status : 'Current';

$statusFilter = ($status === 'Current') 
    ? "status NOT IN ('Delivered', 'Cancelled')" 
    : "status IN ('Delivered', 'Cancelled')";

$today = date('Y-m-d');

// Add trip_date filter only if status is Current
$dateFilter = ($status === 'Current') ? "AND trip_date = '$today'" : '';

// Final SQL
$sql = "
    SELECT * 
    FROM tbl_parcel 
    WHERE bus_id = $bus_id 
      AND $statusFilter 
      $dateFilter
    ORDER BY id DESC
";

$getParcels = $h->queryfire($sql);


$getParcels = $h->queryfire($sql);
while ($row = $getParcels->fetch_assoc()) {
    // Fetch related bus info
    $bus = $h->queryfire("SELECT title, bno, bus_img FROM tbl_bus WHERE id = " . intval($bus_id))->fetch_assoc();

    // Fetch from & to city titles
    $fromCity = $h->queryfire("SELECT title FROM tbl_city WHERE id = " . intval($row['from_city']))->fetch_assoc();
    $toCity = $h->queryfire("SELECT title FROM tbl_city WHERE id = " . intval($row['to_city']))->fetch_assoc();

    $parcelList[] = array(
        "parcel_id" => $row['id'],
        "bus_id" => $bus_id,
        "bus_title" => $bus['title'] ?? '',
        "bus_no" => $bus['bno'] ?? '',
        "bus_img" => $bus['bus_img'] ?? '',
        "trip_date" => $row['trip_date'],
        "sender_name" => $row['sender_name'],
        "sender_mobile" => $row['sender_mobile'],
        "receiver_name" => $row['receiver_name'],
        "receiver_mobile" => $row['receiver_mobile'],
        "from_city" => $fromCity['title'] ?? '',
        "to_city" => $toCity['title'] ?? '',
        "parcel_weight" => $row['parcel_weight'],
        "price" => $row['price'],
        "status" => $row['status'],
        "created_at" => $row['created_at'],
        "price_per_km" => $row['price_per_km'],
        "distance" => $row['distance']
    );
}

$returnArr = array(
    "ResponseCode" => "200",
    "Result" => "true",
    "ResponseMsg" => "Parcel history fetched successfully!",
    "parcel_history" => $parcelList
);

echo json_encode($returnArr);