<?php 
include 'header.php';
    
// Generate tracking number
$tnumbs = "1234567890";
$tnumbs = str_shuffle($tnumbs);
$tnumbs = substr($tnumbs, 0, $track_num);
$tnumbs = $track_prefix."-".date('m')."-".$tnumbs;

$msg = "";

// Initialize all variables
$sendersname = $senderscontact = $sendersmail = $sendersaddress = 
$receiversname = $receiverscontact = $receiversmail = $receiversaddress = 
$status = $dispatchl = $dispatch = $delivery = $desc = "";
$carrier = $carrier_ref = $weight = $payment_mode = $ship_mode = 
$quantity = $delivery_time = $err = $dest = "";
$latitude = $longitude = $destination_lat = $destination_lng = 0.000000;
$requires_permit = 0;
$permit_type = "";

if (isset($_POST['submit'])) {
    // Get form data
    $sendersname = text_input($_POST['sname']);    
    $senderscontact = text_input($_POST['scontact']);  
    $sendersmail = text_input($_POST['smail']);  
    $sendersaddress = text_input($_POST['saddress']);
    $receiversname = text_input($_POST['rname']);  
    $receiverscontact = text_input($_POST['rcontact']);  
    $receiversmail = text_input($_POST['rmail']);  
    $receiversaddress = text_input($_POST['raddress']);
    $status = text_input($_POST['status']);  
    $dispatchl = text_input($_POST['dispatchl']);  
    $dispatch = text_input($_POST['dispatch']);  
    $delivery = text_input($_POST['delivery']);  
    $desc = text_input($_POST['desc']); 
    $carrier = text_input($_POST['carrier']);  
    $carrier_ref = text_input($_POST['carrier_ref']);  
    $weight = text_input($_POST['weight']);  
    $payment_mode = text_input($_POST['payment_mode']);  
    $ship_mode = text_input($_POST['ship_mode']);  
    $quantity = text_input($_POST['quantity']);  
    $delivery_time = text_input($_POST['delivery_time']);  
    $dest = text_input($_POST['dest']);
    $requires_permit = isset($_POST['requires_permit']) ? 1 : 0;
    $permit_type = text_input($_POST['permit_type']);
    $total_f = text_input($_POST['total_f']);

    // Geocode dispatch location
    if (!empty($dispatchl)) {
        $dispatch_coords = geocodeAddress($dispatchl);
        if ($dispatch_coords && is_numeric($dispatch_coords['lat']) && is_numeric($dispatch_coords['lng'])) {
            $latitude = $dispatch_coords['lat'];
            $longitude = $dispatch_coords['lng'];
        } else {
            error_log("Geocoding failed for dispatch location: " . $dispatchl);
            $latitude = 0.000000;
            $longitude = 0.000000;
        }
    }
    
    // Geocode destination
    if (!empty($dest)) {
        $dest_coords = geocodeAddress($dest);
        if ($dest_coords && is_numeric($dest_coords['lat']) && is_numeric($dest_coords['lng'])) {
            $destination_lat = $dest_coords['lat'];
            $destination_lng = $dest_coords['lng'];
        } else {
            error_log("Geocoding failed for destination: " . $dest);
            $destination_lat = 0.000000;
            $destination_lng = 0.000000;
        }
    }

    // Handle file upload
    if (isset($_FILES['image'])) {
        $tmp = $_FILES['image']['tmp_name'];
        $filename = $_FILES['image']['name'];
        $imgname = $tnumbs.".png";
        $dir = "../uploads/".$imgname;
        $check = @getimagesize($tmp);
    }
    
    // Validate required fields
    if (empty($sendersname) || empty($senderscontact) || empty($sendersmail) || empty($sendersaddress) || 
        empty($receiversname) || empty($receiverscontact) || empty($receiversmail) || empty($receiversaddress) || 
        empty($status) || empty($dispatchl) || empty($dispatch) || empty($delivery) || empty($carrier) || 
        empty($carrier_ref) || empty($weight) || empty($payment_mode) || empty($ship_mode) || empty($quantity) || 
        empty($delivery_time) || empty($dest) || empty($total_f) ) {
       echo "<script>alert('Check !!! Some fields are empty')</script>";
    } elseif($check === false) {
       echo "<script>alert('You didnt select an image')</script>";
    } else {
        // Insert into database
        $insert = mysqli_query($link, "INSERT INTO tracking (
            tracking_number, sender_name, sender_contact, sender_email, sender_address, 
            status, dispatch_location, receiver_email, receiver_name, receiver_contact, 
            receiver_address, dispatch_date, delivery_date, pdesc, carrier, carrier_ref, 
            weight, payment_mode, ship_mode, quantity, delivery_time, image, destination, 
            latitude, longitude, destination_lat, destination_lng, requires_permit, permit_type, total_f
        ) VALUES (
            '$tnumbs', '$sendersname', '$senderscontact', '$sendersmail', '$sendersaddress', 
            '$status', '$dispatchl', '$receiversmail', '$receiversname', '$receiverscontact', 
            '$receiversaddress', '$dispatch', '$delivery', '$desc', '$carrier', '$carrier_ref', 
            '$weight', '$payment_mode', '$ship_mode', '$quantity', '$delivery_time', '$imgname', '$dest', 
            '$latitude', '$longitude', '$destination_lat', '$destination_lng', '$requires_permit', '$permit_type', '$total_f'
        )");
       
        if ($insert) {
            move_uploaded_file($tmp, $dir);

            // Send email notification
            if ($mail_track_save == "Yes") {
                $subject = "$sitename";
                $body = "<p>Dear $receiversname</p> 
                         <p>We are pleased to inform you that your shipment has been registered with us at <strong>$sitename</strong>.</p>  
                         <center>Tracking Information</center> 
                         <p><strong>Tracking Number - $tnumbs</strong></p> 
                         <p><strong>Status - $status</strong></p> 
                         <p><strong>Package - $desc</strong></p> 
                         <p><strong>Dispatch Location - $dispatchl</strong></p> 
                         <p><strong>Estimated Delivery Date - $delivery</strong></p> 
                         <p>For more information visit the <a href='$site_url/tracking.php'>Tracking Page</a></p>";
                sendMail($receiversmail,$subject,$body);
            }

            echo "<script>
                alert('New Tracking Added Successfully');
                window.location.href = 'dashboard.php';
            </script>";
        } else {
            echo "Database error: " . mysqli_error($link);
        }
    }
}

function geocodeAddress($address) {
    if (empty($address)) return false;
    
    // Encode the address
    $address = urlencode($address);
    
    // Nominatim (OpenStreetMap) API endpoint
    $url = "https://nominatim.openstreetmap.org/search?format=json&q={$address}&limit=1";
    
    // Set user agent as required by Nominatim's usage policy
    $options = [
        'http' => [
            'header' => "User-Agent: MyTrackingApp\r\n",
            'timeout' => 5 // 5 second timeout
        ]
    ];
    $context = stream_context_create($options);
    
    try {
        // Make the request
        $response = @file_get_contents($url, false, $context);
        
        if ($response === FALSE) {
            error_log("Geocoding request failed for address: " . $address);
            return false;
        }
        
        $data = json_decode($response, true);
        
        if (empty($data) || !isset($data[0]['lat']) || !isset($data[0]['lon'])) {
            error_log("No geocoding results for address: " . $address);
            return false;
        }
        
        // Return coordinates as floats
        return [
            'lat' => (float)$data[0]['lat'],
            'lng' => (float)$data[0]['lon']
        ];
    } catch (Exception $e) {
        error_log("Geocoding error: " . $e->getMessage());
        return false;
    }
}

function text_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>
			
		<!-- BEGIN mobile-sidebar-backdrop -->
		<button class="app-sidebar-mobile-backdrop" data-toggle-target=".app" data-toggle-class="app-sidebar-mobile-toggled"></button>
		<!-- END mobile-sidebar-backdrop -->
		
		<!-- BEGIN #content -->
		<div id="content" class="app-content">
			<!-- BEGIN container -->
			<div class="container">
				<!-- BEGIN row -->
				<div class="row justify-content-center">
					<!-- BEGIN col-10 -->
					<div class="col-xl-10">
						<!-- BEGIN row -->
						<div class="row">
							<!-- BEGIN col-9 -->
							<div class="col-xl-9">
							
								
							
								<hr class="mb-4">
								
								<!-- BEGIN #formControls -->
								<div id="formControls" class="mb-5">
									<h4>Add Tracking</h4>
									
							        <div class="card">
            <div class="card-body">
                <label style="font-weight: bold;font-size: 25px;">TRACKING NUMBER</label>
                <input type="text" readonly="" value="<?php echo $tnumbs ?>" name="tracking_number" class="form-control" id="exampleInputUsername1" placeholder="Username">
            </div>
        </div>

        <form action="" method="POST" enctype="multipart/form-data">
        <div class="personal-informations-from">
            <!-- Sender Information -->
            <div class="personal-informations-from-item">
                <h5>Sender Information</h5>
                <div class="personal-informations-from-item-inner">
                    <div class="row">
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="sname" class="form-label">Sender's Name</label>
                            <input type="text" name="sname" id="sname" class="form-control" aria-label="Sender's Name">
                        </div>
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="scontact" class="form-label">Sender's Contact</label>
                            <input type="text" name="scontact" id="scontact" class="form-control" aria-label="Sender's Contact">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="smail" class="form-label">Sender's Email</label>
                            <input type="email" name="smail" id="smail" class="form-control" aria-label="Sender's Email">
                        </div>
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="saddress" class="form-label">Sender's Address</label>
                            <input type="text" name="saddress" id="saddress" class="form-control" aria-label="Sender's Address">
                        </div>
                    </div>
                </div>
            </div>

            <!-- Receiver Information -->
            <div class="personal-informations-from-item">
                <h5>Receiver Information</h5>
                <div class="personal-informations-from-item-inner">
                    <div class="row">
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="rname" class="form-label">Receiver's Name</label>
                            <input type="text" name="rname" id="rname" class="form-control" aria-label="Receiver's Name">
                        </div>
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="rcontact" class="form-label">Receiver's Contact</label>
                            <input type="text" name="rcontact" id="rcontact" class="form-control" aria-label="Receiver's Contact">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="rmail" class="form-label">Receiver's Email</label>
                            <input type="email" name="rmail" id="rmail" class="form-control" aria-label="Receiver's Email">
                        </div>
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="raddress" class="form-label">Receiver's Address</label>
                            <input type="text" name="raddress" id="raddress" class="form-control" aria-label="Receiver's Address">
                        </div>
                    </div>
                </div>
            </div>

            <!-- Package Information -->
            <div class="personal-informations-from-item">
                <h5>Package Information</h5>
                <div class="personal-informations-from-item-inner">
                    <div class="row">
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="status" class="form-label">Status</label>
                            <select class="form-control" name="status">
                                <option value="Pending">Pending</option>
                                <option value="Active">Active</option>
                                <option value="Inactive">Inactive</option>
                                <option value="Picked Up">Picked Up</option>
                                <option value="Arrived">Arrived</option>
                                <option value="Delivered">Delivered</option>
                                <option value="On hold">On hold</option>
                            </select>
                        </div>
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="dispatchl" class="form-label">Dispatch Location</label>
                            <input type="text" name="dispatchl" id="dispatchl" class="form-control" aria-label="Dispatch Location">
                            <small class="text-muted">Enter full address for accurate geocoding</small>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="dispatch" class="form-label">Dispatch Date</label>
                            <input type="date" name="dispatch" id="dispatch" class="form-control" aria-label="Dispatch Date">
                        </div>
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="delivery" class="form-label">Delivery Date</label>
                            <input type="date" name="delivery" id="delivery" class="form-control" aria-label="Delivery Date">
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="dispatch" class="form-label">Description</label>
                            <input type="text" name="desc" id="dispatch" class="form-control" aria-label="Dispatch Date">
                        </div>
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="delivery" class="form-label">Ship mode</label>
                            <input type="text" name="ship_mode" id="delivery" class="form-control" aria-label="Delivery Date">
                        </div>
                        
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="Total Freight Cost" class="form-label">Total Freight Cost($)</label>
                            <input type="text" name="total_f" id="Total Freight Cost" class="form-control" aria-label="Total Freight Cost">
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="dispatch" class="form-label">Quantity</label>
                            <input type="text" name="quantity" id="dispatch" class="form-control" aria-label="Dispatch Date">
                        </div>
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="delivery" class="form-label">Delivery Time</label>
                            <input type="time" name="delivery_time" id="delivery" class="form-control" aria-label="Delivery Date">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="dest" class="form-label">Destination</label>
                            <input type="text" name="dest" id="dest" class="form-control" aria-label="Destination">
                            <small class="text-muted">Enter full address for accurate geocoding</small>
                        </div>
                        <div class="col-12 col-md-12 col-lg-6">
                            <div class="form-check mt-4 pt-2">
                                <input class="form-check-input" type="checkbox" name="requires_permit" id="requires_permit">
                                <label class="form-check-label" for="requires_permit">
                                    Requires Customs Permit
                                </label>
                            </div>
                        </div>
                        
                        
                    </div>
                    
                    <div class="row" id="permit_type_row" style="display: none;">
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="permit_type" class="form-label">Permit Type</label>
                            <input type="text" name="permit_type" id="permit_type" class="form-control" aria-label="Permit Type">
                        </div>
                    </div>
                </div>
            </div>

            <!-- Additional Details -->
            <div class="personal-informations-from-item">
                <h5>Additional Details</h5>
                <div class="personal-informations-from-item-inner">
                    <div class="row">
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="carrier" class="form-label">Carrier</label>
                            <input type="text" name="carrier" id="carrier" class="form-control" aria-label="Carrier">
                        </div>
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="carrier_ref" class="form-label">Carrier Reference</label>
                            <input type="text" name="carrier_ref" id="carrier_ref" class="form-control" aria-label="Carrier Reference">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="weight" class="form-label">Weight</label>
                            <input type="number" step="0.01" name="weight" id="weight" class="form-control" aria-label="Weight">
                        </div>
                        <div class="col-12 col-md-12 col-lg-6">
                            <label for="payment_mode" class="form-label">Payment Mode</label>
                            <input type="text" name="payment_mode" id="payment_mode" class="form-control" aria-label="Payment Mode">
                        </div>
                    </div>
                </div>
            </div>

            <!-- Upload Image -->
            <div class="personal-informations-from-item">
                <div class="personal-informations-from-item-inner">
                    <div class="row">
                        <div class="col-12">
                            <label for="image" class="form-label">Upload Image</label>
                            <input type="file" name="image" id="image" class="form-control" aria-label="Upload Image">
                        </div>
                    </div>
                </div>
            </div>

                <br><br>
            <!-- Submit Button -->
            <div class="personal-informations-from-btn">
                    <button style='margin-top: 2px; background-color: blue; padding: 2px; border: none; border-radius: 2px ' type="submit" name="submit" class="btn-one">Add Tracking</button>
            </div>
        </form>
        </div>
								</div>
								<!-- END #formControls -->
								
							
								
							
								
								
					
							</div>
							<!-- END col-9-->
							
							
						</div>
						<!-- END row -->
					</div>
					<!-- END col-10 -->
				</div>
				<!-- END row -->
			</div>
			<!-- END container -->
		</div>
		<!-- END #content -->
		
	<?php include 'footer.php'; ?>