<?php 
require dirname(dirname(__FILE__)).'/api/Prozigzig.php';
$h = new Prozigzig();


$data = json_decode(file_get_contents('php://input'), true);
header('Content-type: application/json');

if (empty($data['driver_id'])) {
    echo json_encode([
        "TripHistory" => [],
        "ResponseCode" => "401",
        "Result" => "false",
        "ResponseMsg" => "Driver ID is missing!"
    ]);
    exit;
}

$driver_id = $data['driver_id'];

// Initialize response variables
$vop = [];
$businfo = null;

// 1. Get Bus Info
$busQuery = $h->queryfire("SELECT * FROM tbl_bus WHERE driver_id = $driver_id");
if ($busQuery && $busQuery->num_rows > 0) {
    $businfo = $busQuery->fetch_assoc();
} else {
    echo json_encode([
        "TripHistory" => [],
        "ResponseCode" => "404",
        "Result" => "false",
        "ResponseMsg" => "Bus not found for this driver!"
    ]);
    exit;
}

$busId = $businfo['id'];

// 2. Get Trip History
$tripQuery = $h->queryfire("
    SELECT bo.*, (
        SELECT 
            CASE 
                WHEN COUNT(*) != 0 THEN 
                    FORMAT(SUM(total_rate) / COUNT(*), IF(SUM(total_rate) % COUNT(*) > 0, 2, 0))
                ELSE 
                    5 
            END 
        FROM tbl_book 
        WHERE bus_id = bo.bus_id 
            AND book_status = 'Completed' 
            AND is_rate = 1
    ) AS bus_rate 
    FROM tbl_book AS bo 
    WHERE bo.bus_id = $busId 
    GROUP BY bo.bus_board_date 
    ORDER BY bo.bus_board_date 
    LIMIT 5
");

if ($tripQuery && $tripQuery->num_rows > 0) {
    while ($row = $tripQuery->fetch_assoc()) {
        $pick_datetime = new DateTime($row['bus_board_date']);
        $drop_datetime = new DateTime($row['bus_drop_date']);

        $pick_date = $pick_datetime->format('Y-m-d');
        $drop_date = $drop_datetime->format('Y-m-d');

        $countQuery = $h->queryfire("SELECT * FROM tbl_book_pessenger WHERE bus_id = $busId AND book_date = '$pick_date'");
        $count = ($countQuery) ? $countQuery->num_rows : 0;

        $vop[] = [
            'bus_id' => $businfo['id'],
            'bus_title' => $businfo['title'],
            'bus_no' => $businfo['bno'],
            'pick_date' => $pick_date,
            'drop_date' => $drop_date,
            'bus_img' => $businfo['bus_img'],
            'bus_picktime' => $row['bus_picktime'],
            'bus_droptime' => $row['bus_droptime'],
            'boarding_city' => $row['boarding_city'],
            'drop_city' => $row['drop_city'],
            'bus_rate' => $row['bus_rate'],
            'Difference_pick_drop' => $row['Difference_pick_drop'],
            'ticket_price' => $row['ticket_price'],
            'decker' => $businfo['decker'],
            'left_seat' => (string)($businfo['totl_seat'] - $count),
            'book_seat' => $count,
            'totl_seat' => $businfo['totl_seat'],
            'book_limit' => $businfo['seat_limit'],
            'bus_ac' => $businfo['bac'],
            'is_sleeper' => $businfo['is_sleeper']
        ];
    }

    $returnArr = [
        "TripHistory" => $vop,
        "ResponseCode" => "200",
        "Result" => "true",
        "ResponseMsg" => "Trip History Get Successfully!!"
    ];
} else {
    $returnArr = [
        "TripHistory" => [],
        "ResponseCode" => "204",
        "Result" => "false",
        "ResponseMsg" => "No trip history found!"
    ];
}

echo json_encode($returnArr);
