<?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);

function distance($lat1, $lon1, $lat2, $lon2, $unit) {
    $theta = $lon1 - $lon2;
    $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
    $dist = acos($dist);
    $dist = rad2deg($dist);
    $miles = $dist * 60 * 1.1515;
    $unit = strtoupper($unit);
    if ($unit == "K") {
        return ($miles * 1.609344);
    } elseif ($unit == "N") {
        return ($miles * 0.8684);
    } else {
        return $miles;
    }
}

if ($data['owner_id'] == '' || $data['pick_state_id'] == '' || $data['drop_state_id'] == '') {
    $returnArr = array("ResponseCode" => "401", "Result" => "false", "ResponseMsg" => "Something Went Wrong!");
} else {
    $owner_id = (int)$data['owner_id'];
    $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();

    // ✅ CASE 1: If both states = 0 → return all loads
    if ($pick_state_id === 0 && $drop_state_id === 0) {
        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'];
            $op['total_lorry'] = 0;

            $vehicle_id = $pop['id'];
            $loads = $service->query("SELECT * FROM tbl_load WHERE load_status='Pending' AND vehicle_id=$vehicle_id AND lorry_id=0 AND load_type='POST_LOAD' ORDER BY id DESC");
            $p = array();

            while ($row = $loads->fetch_assoc()) {
                $vdata = $service->query("SELECT title,img FROM tbl_vehicle WHERE id=" . $row['vehicle_id'])->fetch_assoc();
                $pdata = $service->query("SELECT title FROM tbl_state WHERE id=" . $row['pick_state_id'])->fetch_assoc();
                $ddata = $service->query("SELECT title FROM tbl_state WHERE id=" . $row['drop_state_id'])->fetch_assoc();
                $owner = $service->query("SELECT name,pro_pic FROM tbl_user WHERE id=" . $row['uid'])->fetch_assoc();

                $k = array();
                $k['id'] = $row['id'];
                $k['uid'] = $row['uid'];
                $k['vehicle_title'] = $vdata['title'];
                $k['vehicle_img'] = $vdata['img'];
                $k['pickup_point'] = $row['pickup_point'];
                $k['drop_point'] = $row['drop_point'];
                $k['pickup_state'] = $pdata['title'] ?? '';
                $k['drop_state'] = $ddata['title'] ?? '';
                $k['amount'] = $row['amount'];
                $k['weight'] = $row['weight'];
                $k['amt_type'] = $row['amt_type'];
                $k['total_amt'] = $row['total_amt'];
                $k['post_date'] = $row['post_date'];
                $k['load_status'] = $row['load_status'];
                $k['owner_name'] = $owner['name'];
                $k['owner_img'] = empty($owner['pro_pic']) ? 'images/duser.png' : $owner['pro_pic'];
                $k['material_name'] = $row['material_name'];
                $k['load_distance'] = number_format((float)distance($row['pick_lat'], $row['pick_lng'], $row['drop_lat'], $row['drop_lng'], "K"), 2, '.', '') . ' KM';

                $rdata_rest = $service->query("SELECT SUM(total_lrate)/COUNT(*) AS rate_rest FROM tbl_load WHERE uid=" . $row['uid'] . " AND load_status='Completed' AND total_lrate !=0")->fetch_assoc();
                $k['owner_rating'] = empty($rdata_rest['rate_rest']) ? "5" : number_format((float)$rdata_rest['rate_rest'], 2, '.', '');

                $bid = $service->query("SELECT status,amount,amt_type,total_amt FROM tbl_load_response WHERE load_id=" . $row['id'] . " AND owner_id=$owner_id")->fetch_assoc();
                $status = $bid['status'] ?? null;
                if ($status === null) {
                    $k['is_bid'] = 0;
                } elseif ($status == 0) {
                    $k['is_bid'] = 1;
                    $k['bid_amount'] = $bid['amount'];
                    $k['bid_amount_type'] = $bid['amt_type'];
                    $k['bid_total_amt'] = $bid['total_amt'];
                } elseif ($status == 1) {
                    $k['is_bid'] = 2;
                } else {
                    $k['is_bid'] = 3;
                }
                $p[] = $k;
            }
            $op['loaddata'] = $p;
            $vom[] = $op;
        }

        $returnArr = array("FindLoadData" => $vom, "ResponseCode" => "200", "Result" => "true", "ResponseMsg" => "All Load Data Retrieved Successfully!");
    }

    // ✅ CASE 2: When pick/drop states are provided → filtered loads
    else {
        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'];

            // Matching lorries for route
            $lorry_count = $service->query("SELECT * FROM tbl_lorry WHERE vehicle_id=$vehicle_id AND owner_id=$owner_id AND routes REGEXP '\\\\b$pick_state_id\\\\b' AND routes REGEXP '\\\\b$drop_state_id\\\\b'")->num_rows;
            $op['total_lorry'] = $lorry_count;

            // Fetch loads matching these states (✅ fix — ensure data returned when exists)
            $query = "SELECT * FROM tbl_load WHERE load_status='Pending' AND vehicle_id=$vehicle_id AND lorry_id=0 AND load_type='POST_LOAD' AND pick_state_id=$pick_state_id AND drop_state_id=$drop_state_id ORDER BY id DESC";
            $list = $service->query($query);
            $p = array();

            while ($row = $list->fetch_assoc()) {
                $vdata = $service->query("SELECT title,img FROM tbl_vehicle WHERE id=" . $row['vehicle_id'])->fetch_assoc();
                $pdata = $service->query("SELECT title FROM tbl_state WHERE id=" . $row['pick_state_id'])->fetch_assoc();
                $ddata = $service->query("SELECT title FROM tbl_state WHERE id=" . $row['drop_state_id'])->fetch_assoc();
                $owner = $service->query("SELECT name,pro_pic FROM tbl_user WHERE id=" . $row['uid'])->fetch_assoc();

                $k = array();
                $k['id'] = $row['id'];
                $k['uid'] = $row['uid'];
                $k['vehicle_title'] = $vdata['title'];
                $k['vehicle_img'] = $vdata['img'];
                $k['pickup_point'] = $row['pickup_point'];
                $k['drop_point'] = $row['drop_point'];
                $k['pickup_state'] = $pdata['title'] ?? '';
                $k['drop_state'] = $ddata['title'] ?? '';
                $k['amount'] = $row['amount'];
                $k['weight'] = $row['weight'];
                $k['amt_type'] = $row['amt_type'];
                $k['total_amt'] = $row['total_amt'];
                $k['post_date'] = $row['post_date'];
                $k['load_status'] = $row['load_status'];
                $k['owner_name'] = $owner['name'];
                $k['owner_img'] = empty($owner['pro_pic']) ? 'images/duser.png' : $owner['pro_pic'];
                $k['material_name'] = $row['material_name'];
                $k['load_distance'] = number_format((float)distance($row['pick_lat'], $row['pick_lng'], $row['drop_lat'], $row['drop_lng'], "K"), 2, '.', '') . ' KM';

                $rdata_rest = $service->query("SELECT SUM(total_lrate)/COUNT(*) AS rate_rest FROM tbl_load WHERE uid=" . $row['uid'] . " AND load_status='Completed' AND total_lrate !=0")->fetch_assoc();
                $k['owner_rating'] = empty($rdata_rest['rate_rest']) ? "5" : number_format((float)$rdata_rest['rate_rest'], 2, '.', '');

                $bid = $service->query("SELECT status,amount,amt_type,total_amt FROM tbl_load_response WHERE load_id=" . $row['id'] . " AND owner_id=$owner_id")->fetch_assoc();
                $status = $bid['status'] ?? null;
                if ($status === null) {
                    $k['is_bid'] = 0;
                } elseif ($status == 0) {
                    $k['is_bid'] = 1;
                    $k['bid_amount'] = $bid['amount'];
                    $k['bid_amount_type'] = $bid['amt_type'];
                    $k['bid_total_amt'] = $bid['total_amt'];
                } elseif ($status == 1) {
                    $k['is_bid'] = 2;
                } else {
                    $k['is_bid'] = 3;
                }

                $p[] = $k;
            }

            $op['loaddata'] = $p;
            $vom[] = $op;
        }

        $returnArr = array("FindLoadData" => $vom, "ResponseCode" => "200", "Result" => "true", "ResponseMsg" => "Filtered Load Data Retrieved Successfully!");
    }
}

echo json_encode($returnArr);
?>
