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

// ====== DISTANCE FUNCTION ADDED ======
function calculateDistanceKM($lat1, $lon1, $lat2, $lon2) {
    $earthRadius = 6371; // KM

    $dLat = deg2rad($lat2 - $lat1);
    $dLon = deg2rad($lon2 - $lon1);

    $lat1 = deg2rad($lat1);
    $lat2 = deg2rad($lat2);

    $a = sin($dLat / 2) * sin($dLat / 2) +
         sin($dLon / 2) * sin($dLon / 2) * cos($lat1) * cos($lat2);

    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));

    return round($earthRadius * $c, 2);
}
// ======================================

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

    $owner_id = $data['owner_id'];
    $status = $data['status'];
    $lorry_id = $data['lorry_id'];

    if ($status == 'Current') {
        $list = $service->query("
            SELECT id,vehicle_id,pickup_point,drop_point,amount,amt_type,total_amt,post_date,
            load_status,pick_state_id,drop_state_id,visible_hours,pick_lat,pick_lng,drop_lat,drop_lng 
            FROM tbl_load 
            WHERE lorry_owner_id=$owner_id AND lorry_id=$lorry_id 
            AND load_status IN('Load_start','Accepted') 
            AND load_type='POST_LOAD' 
            ORDER BY id DESC
        ");
    } else {
        $list = $service->query("
            SELECT id,vehicle_id,pickup_point,drop_point,amount,amt_type,total_amt,post_date,
            load_status,pick_state_id,drop_state_id,visible_hours,pick_lat,pick_lng,drop_lat,drop_lng 
            FROM tbl_load 
            WHERE lorry_owner_id=$owner_id AND lorry_id=$lorry_id 
            AND load_status='Completed' 
            AND load_type='POST_LOAD'
            ORDER BY id DESC
        ");
    }

    $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();

        $k['id'] = $row['id'];
        $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['amt_type'] = $row['amt_type'];
        $k['total_amt'] = $row['total_amt'];
        $k['post_date'] = $row['post_date'];
        $k['load_status'] = $row['load_status'];

        // ====== FIXED DISTANCE CALCULATION ======
        $distance = calculateDistanceKM($row['pick_lat'], $row['pick_lng'], $row['drop_lat'], $row['drop_lng']);
        $k['load_distance'] = $distance . ' KM';

        // ====== VISIBLE HOURS ======
        $d1 = new DateTime($row['post_date']);
        $d2 = new DateTime(date("Y-m-d H:i:s"));
        $interval = $d1->diff($d2);
        $k['svisible_hours'] = $row['visible_hours'] - (($interval->days * 24) + $interval->h);

        $p[] = $k;
    }

    $returnArr = array("LoadHistoryData" => $p, "ResponseCode" => "200", "Result" => "true", "ResponseMsg" => "Load History Get Successfully!!");
}

echo json_encode($returnArr);
?>
