<?php
require dirname(dirname(__FILE__)).'/inc/config.php';
require dirname(dirname(__FILE__)).'/inc/FunctionQuery.php';
require dirname(dirname(__FILE__)).'/inc/keyvaliation.php';
header('Content-type: application/json');

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

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

$uid = (int)$data['uid'];
$pick_state_id = (int)$data['pick_state_id'];
$drop_state_id = (int)$data['drop_state_id'];

$vehicle = $service->query("SELECT * FROM tbl_vehicle WHERE status = 1");
$vom = array();

while ($pop = $vehicle->fetch_assoc()) {

    $op = array();
    $op['id'] = $pop['id'];
    $op['title'] = $pop['title'];
    $op['min_weight'] = $pop['min_weight'];
    $op['max_weight'] = $pop['max_weight'];
    $vehicle_id = $pop['id'];

    // ✅ Main query logic
    if ($pick_state_id == 0 && $drop_state_id == 0) {
        // Fetch all lorries of this vehicle type
        $list = $service->query("SELECT * FROM tbl_lorry WHERE vehicle_id = $vehicle_id");
    } else {
        // Filtered by routes
        $list = $service->query("
            SELECT * FROM tbl_lorry 
            WHERE vehicle_id = $vehicle_id 
            AND FIND_IN_SET($pick_state_id, routes)
            AND FIND_IN_SET($drop_state_id, routes)
        ");
    }

    $p = array();

    while ($row = $list->fetch_assoc()) {
        $vdata = $service->query("SELECT title, img FROM tbl_vehicle WHERE id = ".$row['vehicle_id'])->fetch_assoc();
        $odata = $service->query("SELECT name, pro_pic FROM tbl_lowner WHERE id = ".$row['owner_id'])->fetch_assoc();

        $k = array();
        $k['lorry_id'] = $row['id'];
        $k['vehicle_id'] = $row['vehicle_id'];
        $k['lorry_owner_id'] = $row['owner_id'];
        $k['lorry_owner_title'] = $odata['name'];
        $k['lorry_owner_img'] = empty($odata['pro_pic']) ? 'images/duser.png' : $odata['pro_pic'];
        $k['lorry_img'] = $vdata['img'];
        $k['lorry_title'] = $vdata['title'];
        $k['weight'] = $row['weight'];
        $k['curr_location'] = $row['curr_location'];
        $routes = explode(',', $row['routes']);
        $k['routes_count'] = count($routes);
        $k['rc_verify'] = $row['is_verify'];
        $k['lorry_no'] = $row['lorry_no'];

        $lorry_weight_data = $service->query("SELECT weight FROM tbl_lorry WHERE id = ".$row['id'])->fetch_assoc();
        $lorry_weight = (float)$lorry_weight_data['weight'];

        $lorry_book = $service->query("
            SELECT SUM(weight) AS total_load_book 
            FROM tbl_load 
            WHERE lorry_id = ".$row['id']." 
            AND load_status NOT IN ('Completed', 'Cancelled')
        ")->fetch_assoc();

        $booked_weight = (float)$lorry_book['total_load_book'];
        $book_load = max(0, $lorry_weight - $booked_weight);

        $rdata_rest = $service->query("
            SELECT SUM(total_trate)/COUNT(*) AS rate_rest 
            FROM tbl_load 
            WHERE lorry_owner_id = ".$row['owner_id']." 
            AND load_status = 'Completed' 
            AND total_trate != 0
        ")->fetch_assoc();

        $k['review'] = (empty($rdata_rest['rate_rest'])) ? "5" : number_format((float)$rdata_rest['rate_rest'], 2, '.', '');

        if ($book_load > 0) {
            $p[] = $k;
        }
    }

    $op['lorrydata'] = $p;

    if (!empty($p)) {
        $vom[] = $op;
    }
}

$returnArr = array(
    "FindLorryData" => $vom,
    "ResponseCode" => "200",
    "Result" => "true",
    "ResponseMsg" => "Find Lorry Data Retrieved Successfully!"
);

echo json_encode($returnArr);
?>
