<?php 
include 'header.php';

if (isset($_GET['num'])) {
    $tnumbs = $_GET['num'];
    $select = mysqli_query($link, "SELECT * FROM tracking WHERE tracking_number = '$tnumbs' ");
    if (mysqli_num_rows($select) > 0) {
        $row = mysqli_fetch_assoc($select);
        $senders_name = $row['sender_name'];  
        $senders_contact = $row['sender_contact'];  
        $senders_mail = $row['sender_email'];  
        $senders_address = $row['sender_address'];
        $receivers_name = $row['receiver_name'];  
        $receivers_contact = $row['receiver_contact'];  
        $receivers_mail = $row['receiver_email'];  
        $receivers_address = $row['receiver_address'];
        $statuss = $row['status'];  
        $dispatch_l = $row['dispatch_location'];  
        $dispatchh = $row['dispatch_date'];  
        $deliveryy = $row['delivery_date'];
        $current_loc = $row['current_location'];
        $desc = $row['pdesc'];
        $latitude = $row['latitude'];
        $longitude = $row['longitude'];
    } else {
        echo "<script>window.location.href = 'dashboard.php'; </script>";
    }
} else {
    echo "<script>window.location.href = 'dashboard.php'; </script>";
}

if (isset($_POST['update'])) {
    $current_lo = text_input($_POST['current_loc']);
    $date = text_input($_POST['date']);
    $time = text_input($_POST['time']);
    $status = text_input($_POST['status']);
    $note = text_input($_POST['note']);
    $shiping_cost = text_input($_POST['shiping_cost']);
    $clearance_cost = text_input($_POST['clearance_cost']);

    $new_latitude = 0.000000;
    $new_longitude = 0.000000;

    if (!empty($current_lo)) {
        $coords = geocodeAddress($current_lo);

        if ($coords && isset($coords['lat']) && isset($coords['lng'])) {
            $new_latitude = (float)$coords['lat'];
            $new_longitude = (float)$coords['lng'];
        } else {
            error_log("Geocoding failed or returned empty for location: $current_lo");
            echo "<script>alert('Geocoding failed. Please check address format.');</script>";
        }
    }

    if (empty($current_lo) || empty($date) || empty($time) || empty($status)) {
        echo "<script>alert('Check !!! Required fields are empty');</script>";
    } else {
        $update = mysqli_query($link, "INSERT INTO track_update 
            (`track_num`, `status`, `date`, `time`, `note`, `current_location`) 
            VALUES ('$tnumbs', '$status', '$date', '$time', '$note', '$current_lo')");

        if ($update) {
            $update_main = mysqli_query($link, "UPDATE tracking 
                SET current_location = '$current_lo', 
                    status = '$status', 
                    latitude = '$new_latitude', 
                    longitude = '$new_longitude' 
                WHERE tracking_number = '$tnumbs'");

            if (!$update_main) {
                error_log("Main update failed: " . mysqli_error($link));
                echo "<script>alert('Failed to update main tracking record');</script>";
            } else {
                if ($mail_track_update == "Yes") {
                    $subject = "$sitename - Shipment Update";
                    $body = "<html>...your existing HTML email template here...</html>";
                    sendMail($receivers_mail, $subject, $body);
                }

                echo "<script>
                    alert('Updated Successfully');
                    window.location.href = 'edit-tracking.php?num=$tnumbs';
                </script>";
                exit();
            }
        } else {
            error_log("Insert into track_update failed: " . mysqli_error($link));
            echo "<script>alert('Failed to insert update');</script>";
        }
    }
}

function geocodeAddress($address) {
    if (empty($address)) return false;

    $address = urlencode($address);
    $url = "https://nominatim.openstreetmap.org/search?format=json&q={$address}&limit=1";
    
    $options = [
        'http' => [
            'header' => "User-Agent: MyTrackingApp/1.0\r\n",
            'timeout' => 10
        ]
    ];
    $context = stream_context_create($options);
    
    try {
        $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 [
            '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>Admin Details</h4>
									
							        <div class="card">
            <div class="card-body">
                
        

   
                                    <div class="personal-informations-head">
                                        <div class="card-body">
                                            <label style="font-weight: bold;font-size: 25px;">TRACKING NUMBER  - <?php echo $tnumbs ?></label>
                                        </div>
                                    </div>

                                    <form action="" method="POST">
                                        <div class="personal-informations-from">
                                            <!-- Package Information -->
                                            <div class="personal-informations-from-item">
                                                <div class="personal-informations-from-item-inner">
                                                    <div class="row">
                                                        <div class="col-12 col-md-12 col-lg-12">
                                                            <label for="status" class="form-label">Status</label>
                                                            <select class="form-control" name="status">
                                                                <option value="Pending" <?php echo ($statuss == 'Pending') ? 'selected' : ''; ?>>Pending</option>
                                                                <option value="Active" <?php echo ($statuss == 'Active') ? 'selected' : ''; ?>>Active</option>
                                                                <option value="Inactive" <?php echo ($statuss == 'Inactive') ? 'selected' : ''; ?>>Inactive</option>
                                                                <option value="Picked Up" <?php echo ($statuss == 'Picked Up') ? 'selected' : ''; ?>>Picked Up</option>
                                                                <option value="Arrived" <?php echo ($statuss == 'Arrived') ? 'selected' : ''; ?>>Arrived</option>
                                                                <option value="Delivered" <?php echo ($statuss == 'Delivered') ? 'selected' : ''; ?>>Delivered</option>
                                                                <option value="Departed" <?php echo ($statuss == 'Departed') ? 'selected' : ''; ?>>Departed</option>
                                                                <option value="On hold" <?php echo ($statuss == 'On hold') ? 'selected' : ''; ?>>On hold</option>
                                                            </select>
                                                        </div>
                                                     
                                                        <div class="col-12 col-md-12 col-lg-12">
                                                            <label for="current_loc" class="form-label">Current Location</label>
                                                            <input type="text" class="form-control" value="<?php echo $current_loc ?>" name="current_loc" id="current_loc" placeholder="Current Location">
                                                            <small class="text-muted">Enter full address for accurate geocoding</small>
                                                           
                                                        </div>

                                                        <div class="col-12 col-md-12 col-lg-12">
                                                            <label for="date" class="form-label">Date</label>
                                                            <input type="date" class="form-control" value="<?php echo date('Y-m-d') ?>" name="date" id="date" placeholder="Date">
                                                        </div>

                                                        <div class="col-12 col-md-12 col-lg-12">
                                                            <label for="time" class="form-label">Time</label>
                                                            <input type="time" class="form-control" value="<?php echo date('H:i') ?>" name="time" id="time" placeholder="Time">
                                                        </div>

                                                        <div class="col-12 col-md-12 col-lg-12">
                                                            <label for="note" class="form-label">Note</label>
                                                            <textarea name="note" class="form-control"></textarea>
                                                        </div>

                                                        <!--<div class="col-12 col-md-12 col-lg-12">-->
                                                        <!--    <label for="shiping_cost" class="form-label">Shipping Cost</label>-->
                                                        <!--    <input type="text" class="form-control" value="" name="shiping_cost" id="shiping_cost" placeholder="">-->
                                                        <!--</div>-->
                                                        <!--<div class="col-12 col-md-12 col-lg-12">-->
                                                        <!--    <label for="clearance_cost" class="form-label">Clearance Cost</label>-->
                                                        <!--    <input type="text" class="form-control" value="" name="clearance_cost" id="clearance_cost" placeholder="">-->
                                                        <!--</div>-->
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Submit Button -->
                                            <div class="personal-informations-from-btn">
                                                <button style='margin-top: 2px; background-color: blue; padding: 10px; border: none; border-radius: 5px' type="submit" name="update" class="btn-one">Update</button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
        
        </div>
            </div>
        </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'; ?>