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

// Get site settings (currency, etc.)
$query = "SELECT * FROM `tbl_setting`";
$set = $h->fetchData($query);

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

// Validate required input
if (!isset($data['driver_id']) || empty($data['driver_id'])) {
    echo json_encode([
        "TripDetails" => (object)[],
        "ResponseCode" => "401",
        "Result" => "false",
        "ResponseMsg" => "Driver ID is required."
    ]);
    exit;
}

$driver_id = intval($data['driver_id']);

try {
    // Fetch bus assigned to the driver
    $businfo = $h->queryfire("SELECT id FROM tbl_bus WHERE driver_id = $driver_id")->fetch_assoc();
    if (!$businfo) {
        echo json_encode([
            "TripDetails" => (object)[],
            "ResponseCode" => "401",
            "Result" => "false",
            "ResponseMsg" => "No bus found for this driver."
        ]);
        exit;
    }

    $bus_id = intval($businfo['id']);

    // Fetch boarding and drop points
    $getboardinfo = $h->queryfire("SELECT * FROM tbl_board_drop_points WHERE bus_id = $bus_id LIMIT 1")->fetch_assoc();
    if (!$getboardinfo) {
        echo json_encode([
            "TripDetails" => (object)[],
            "ResponseCode" => "401",
            "Result" => "false",
            "ResponseMsg" => "No boarding/drop points found for this bus."
        ]);
        exit;
    }

    $fromCity = intval($getboardinfo['bpoint']);
    $toCity = intval($getboardinfo['dpoint']);
    $trip_date = date("Y-m-d");

    // Determine trip day
    $trip_day_of_week_numeric = date('w', strtotime($trip_date));
    $days_of_week = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    $trip_day_of_week = $days_of_week[$trip_day_of_week_numeric];
    $offday_check = "AND FIND_IN_SET('$trip_day_of_week', bus.offday) = 0";

    // Main bus trip info query
    $sql = "
        SELECT 
            bp.bus_id,
            bp.bpoint,
            bp.id AS id_pickup_drop, 
            bp.dpoint, 
            bp.btime AS pick_time, 
            bp.dtime AS drop_time,
            bp.differncetime AS Difference_pick_drop,    
            bus.title, 
            bus.bno, 
            bus.bus_img,
            bus.bstatus, 
            bus.rate, 
            bus.tick_price, 
            bus.decker, 
            bus.driver_direction, 
            bus.totl_seat, 
            bus.seat_limit, 
            bus.bac, 
            bus.is_sleeper, 
            bus.seat_layout, 
            bus.offday,
            (
                SELECT 
                    CASE 
                        WHEN COUNT(*) != 0 THEN 
                            FORMAT(SUM(total_rate) / COUNT(*), IF(SUM(total_rate) % COUNT(*) > 0, 2, 0))
                        ELSE 
                            bus.rate 
                    END 
                FROM tbl_book 
                WHERE bus_id = bp.bus_id 
                    AND book_status = 'Completed' 
                    AND is_rate = 1
            ) AS bus_rate,
            (
                SELECT GROUP_CONCAT(title) 
                FROM tbl_facility 
                WHERE FIND_IN_SET(tbl_facility.id, bus.bus_facility)
            ) AS bus_facilities,
            (
                SELECT GROUP_CONCAT(img) 
                FROM tbl_facility 
                WHERE FIND_IN_SET(tbl_facility.id, bus.bus_facility)
            ) AS facility_imgs,
            (SELECT title FROM tbl_city WHERE id = $fromCity) AS boarding_city,
            (SELECT title FROM tbl_city WHERE id = $toCity) AS drop_city
        FROM tbl_board_drop_points as bp
        JOIN tbl_bus as bus ON bp.bus_id = bus.id
        WHERE bp.bpoint = $fromCity
        AND bp.dpoint = $toCity
        AND bus.bstatus = 1
        AND bus.driver_id = $driver_id
        $offday_check
    ";

    $busfetch = $h->queryfire($sql)->fetch_assoc();
    if (!$busfetch) {
        echo json_encode([
            "TripDetails" => (object)[],
            "ResponseCode" => "401",
            "Result" => "false",
            "ResponseMsg" => "No active trip found for this driver today."
        ]);
        exit;
    }

    // Handle pick/drop date logic
    $pick_datetime = new DateTime($trip_date . ' ' . $busfetch['pick_time']);
    $drop_datetime = new DateTime($trip_date . ' ' . $busfetch['drop_time']);

    if ($drop_datetime < $pick_datetime) {
        $pick_date = $pick_datetime->format('Y-m-d');
        $drop_datetime->modify('+1 day');
        $dropdate = $drop_datetime->format('Y-m-d');
    } else {
        $pick_date = $pick_datetime->format('Y-m-d');
        $dropdate = $drop_datetime->format('Y-m-d');
    }

    // Calculate booked and left seats
    $count = $h->queryfire("SELECT * FROM tbl_book_pessenger WHERE bus_id = $bus_id AND book_date = '$trip_date'")->num_rows;
    $left_seat = $busfetch['totl_seat'] - $count;

    // Final response array
    $bu = [
        'bus_id' => $busfetch['bus_id'],
        'id_pickup_drop' => $busfetch['id_pickup_drop'],
        'bus_title' => $busfetch['title'],
        'bus_no' => $busfetch['bno'],
        'pick_date' => $pick_date,
        'drop_date' => $dropdate,
        'bus_img' => $busfetch['bus_img'],
        'bus_picktime' => $busfetch['pick_time'],
        'bus_droptime' => $busfetch['drop_time'],
        'boarding_city' => $busfetch['boarding_city'],
        'drop_city' => $busfetch['drop_city'],
        'bus_rate' => $busfetch['bus_rate'],
        'Difference_pick_drop' => $busfetch['Difference_pick_drop'],
        'ticket_price' => $busfetch['tick_price'],
        'decker' => $busfetch['decker'],
        'left_seat' => $left_seat,
        'book_seat' => $count,
        'totl_seat' => $busfetch['totl_seat'],
        'book_limit' => $busfetch['seat_limit'],
        'bus_ac' => $busfetch['bac'],
        'is_sleeper' => $busfetch['is_sleeper']
    ];

    $returnArr = [
        "TripDetails" => $bu,
        "currency" => $set['currency'],
		"g_key"=>$set['g_key'],
        "ResponseCode" => "200",
        "Result" => "true",
        "ResponseMsg" => "Trip Details Get Successfully!!"
    ];

    echo json_encode($returnArr);

} catch (Exception $e) {
    echo json_encode([
        "TripDetails" => (object)[],
        "ResponseCode" => "500",
        "Result" => "false",
        "ResponseMsg" => "Internal Server Error: " . $e->getMessage()
    ]);
}
