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

// ----------- REQUIRED FIELDS CHECK ------------
$required = [
    'uid', 'pickup_point', 'drop_point', 'material_name', 'weight',
    'vehicle_id', 'amount', 'amt_type', 'visible_hours', 'total_amt',
    'pick_lat', 'pick_lng', 'drop_lat', 'drop_lng',
    'pick_state_id', 'drop_state_id',
    'lorry_id', 'lorry_owner_id',
    'pick_name', 'pick_mobile', 'drop_name', 'drop_mobile'
];

foreach ($required as $key) {
    if (!isset($data[$key]) || $data[$key] === '') {
        echo json_encode([
            "ResponseCode" => "401",
            "Result" => "false",
            "ResponseMsg" => "Missing Required Field: $key"
        ]);
        exit;
    }
}

// ------------ SANITIZE INPUTS -----------------
$uid = mysqli_real_escape_string($service, $data['uid']);
$pickup_point = mysqli_real_escape_string($service, $data['pickup_point']);
$drop_point = mysqli_real_escape_string($service, $data['drop_point']);
$material_name = mysqli_real_escape_string($service, $data['material_name']);
$weight = floatval($data['weight']);
$description = mysqli_real_escape_string($service, $data['description'] ?? '');

$vehicle_id = intval($data['vehicle_id']);
$amount = floatval($data['amount']);
$amt_type = mysqli_real_escape_string($service, $data['amt_type']);
$visible_hours = intval($data['visible_hours']);
$total_amt = floatval($data['total_amt']);

$pick_lat = mysqli_real_escape_string($service, $data['pick_lat']);
$pick_lng = mysqli_real_escape_string($service, $data['pick_lng']);
$drop_lat = mysqli_real_escape_string($service, $data['drop_lat']);
$drop_lng = mysqli_real_escape_string($service, $data['drop_lng']);

$pick_state_id = intval($data['pick_state_id']);
$drop_state_id = intval($data['drop_state_id']);

$lorry_id = intval($data['lorry_id']);
$lorry_owner_id = intval($data['lorry_owner_id']);

$pick_name = mysqli_real_escape_string($service, $data['pick_name']);
$pick_mobile = mysqli_real_escape_string($service, $data['pick_mobile']);
$drop_name = mysqli_real_escape_string($service, $data['drop_name']);
$drop_mobile = mysqli_real_escape_string($service, $data['drop_mobile']);

$timestamp = date("Y-m-d H:i:s");


// ------------ FETCH LORRY CAPACITY ---------------
$lorry = $service->query("SELECT weight FROM tbl_lorry WHERE id = $lorry_id")->fetch_assoc();

if (!$lorry) {
    echo json_encode([
        "ResponseCode" => "401",
        "Result" => "false",
        "ResponseMsg" => "Invalid Lorry ID!"
    ]);
    exit;
}

$lorry_capacity = floatval($lorry['weight']);

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

$booked_load = floatval($lorry_book['total_load_book'] ?? 0);
$available_capacity = $lorry_capacity - $booked_load;

// ------------ CHECK AVAILABLE CAPACITY ------------
if ($available_capacity <= 0) {
    echo json_encode([
        "ResponseCode" => "401",
        "Result" => "false",
        "ResponseMsg" => "Lorry Fully Booked!"
    ]);
    exit;
}

if ($weight > $available_capacity) {
    echo json_encode([
        "ResponseCode" => "401",
        "Result" => "false",
        "ResponseMsg" => "Available capacity is only $available_capacity. Please adjust load weight."
    ]);
    exit;
}


// ------------ INSERT LOAD DATA ---------------------
$table = "tbl_load";
$field_values = [
    "uid","pickup_point","drop_point","material_name","weight","description",
    "vehicle_id","amount","amt_type","visible_hours","total_amt",
    "pick_lat","pick_lng","drop_lat","drop_lng",
    "pick_state_id","drop_state_id",
    "pick_name","pick_mobile","drop_name","drop_mobile",
    "post_date","load_type","lorry_id","lorry_owner_id"
];

$data_values = [
    "$uid","$pickup_point","$drop_point","$material_name","$weight","$description",
    "$vehicle_id","$amount","$amt_type","$visible_hours","$total_amt",
    "$pick_lat","$pick_lng","$drop_lat","$drop_lng",
    "$pick_state_id","$drop_state_id",
    "$pick_name","$pick_mobile","$drop_name","$drop_mobile",
    "$timestamp",'FIND_LORRY',"$lorry_id","$lorry_owner_id"
];

$h = new FunctionQuery($service);
$load_id = $h->serviceinsertdata_Api_Id($field_values, $data_values, $table);


// ------------ SEND NOTIFICATION TO LORRY OWNER ------------
$content = ["en" => "New load request received."];
$heading = ["en" => "New Direct Load Request!"];

$fields = [
    'app_id' => $set['d_key'],
    'included_segments' => ["Active Users"],
    'filters' => [
        ['field' => 'tag', 'key' => 'owner_id', 'relation' => '=', 'value' => $lorry_owner_id]
    ],
    'contents' => $content,
    'headings' => $heading,
    'android_channel_id' => $set['d_cust']
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json; charset=utf-8',
    'Authorization: Basic ' . $set['d_hash']
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_exec($ch);
curl_close($ch);

// ------------ SAVE INTERNAL NOTIFICATION ------------
$desc = "New Direct Load Request #$load_id !!";
$h->serviceinsertdata_Api(
    ["rid","date","msg"],
    ["$lorry_owner_id","$timestamp","$desc"],
    "tbl_rnoti"
);


// ------------ SUCCESS RESPONSE ------------
echo json_encode([
    "ResponseCode" => "200",
    "Result" => "true",
    "ResponseMsg" => "Booking Request sent successfully!"
]);
?>
