<?php 
require dirname(dirname(__FILE__)).'/inc/config.php';
require dirname(dirname(__FILE__)).'/inc/keyvaliation.php';
$data = json_decode(file_get_contents('php://input'), true);
header('Content-type: application/json');

if ($data['owner_id'] == '' || $data['load_id'] == '') {
    $returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} else {

    $uid = (int)$data['owner_id'];
    $load_id = (int)$data['load_id'];

    // Check if load exists
    $check_load = $service->query("SELECT * FROM tbl_load WHERE id = $load_id")->num_rows;

    if ($check_load != 0) {

        $check_load_require = $service->query("
            SELECT vehicle_id, pick_state_id, drop_state_id 
            FROM tbl_load 
            WHERE id = $load_id
        ")->fetch_assoc();

        $vehicle_id = $check_load_require['vehicle_id'];
        $pick_state_id = $check_load_require['pick_state_id'];
        $drop_state_id = $check_load_require['drop_state_id'];

        // ✅ FIX: Find lorries by route using FIND_IN_SET
        $check = $service->query("
            SELECT * FROM tbl_lorry 
            WHERE owner_id = $uid 
            AND vehicle_id = $vehicle_id
            AND FIND_IN_SET($pick_state_id, routes)
            AND FIND_IN_SET($drop_state_id, routes)
        ");

        $arr = array();

        while ($row = $check->fetch_assoc()) {

            $vdata = $service->query("
                SELECT title, img 
                FROM tbl_vehicle 
                WHERE id = ".$row['vehicle_id']
            )->fetch_assoc();

            $op = array();
            $op['id'] = $row['id'];
            $op['lorry_img'] = $vdata['img'];
            $op['lorry_title'] = $vdata['title'];
            $op['weight'] = $row['weight'];
            $op['rc_verify'] = $row['is_verify'];
            $op['lorry_no'] = $row['lorry_no'];

            $arr[] = $op;
        }

        $returnArr = array(
            "BidLorryData" => $arr,
            "ResponseCode" => "200",
            "Result" => "true",
            "ResponseMsg" => "Lorry List Get Successfully!!"
        );

    } else {

        $returnArr = array(
            "BidLorryData" => [],
            "ResponseCode" => "200",
            "Result" => "true",
            "ResponseMsg" => "Load Not Found!!"
        );
    }
}

echo json_encode($returnArr);
?>
