<?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'];
  } else {
    echo "<script>window.location.href = 'dashboard.php'; </script>";
  }
} else {
  echo "<script>window.location.href = 'dashboard.php'; </script>";
}



if (isset($_POST['update'])) {
    // Get values from form
    $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']);
    $delivery_charge = text_input($_POST['delivery_charge']);
    $total_charge = text_input($_POST['total_charge']);

    // Fetch existing tracking details so we can keep old values if fields are empty
    $tracking_data = mysqli_fetch_assoc(mysqli_query($link, "SELECT * FROM tracking WHERE tracking_number = '$tnumbs'"));

    // Keep old values if fields are blank
    if (empty($current_lo)) { $current_lo = $tracking_data['current_location']; }
    if (empty($status)) { $status = $tracking_data['status']; }
    if (empty($note)) { $note = $tracking_data['note']; }
    if (empty($delivery_charge)) { $delivery_charge = $tracking_data['delivery_charge']; }
    if (empty($total_charge)) { $total_charge = $tracking_data['total_charge']; }

    // Make sure date & time have values (use today if empty)
    if (empty($date)) { $date = date("Y-m-d"); }
    if (empty($time)) { $time = date("H:i:s"); }

    // Insert into track_update (history)
    $update = mysqli_query($link, "INSERT INTO track_update 
        (`track_num`, `status`, `date`, `time`, `note`, `current_location`, `delivery_charge`, `total_charge`, `is_current_location`) 
        VALUES 
        ('$tnumbs', '$status', '$date', '$time', '$note', '$current_lo', '$delivery_charge', '$total_charge', 'no')");

    if ($update) {
        // Update main tracking record with the latest details
        mysqli_query($link, "UPDATE tracking SET 
            current_location = '$current_lo',
            status = '$status',
            note = '$note',
            delivery_charge = '$delivery_charge',
            total_charge = '$total_charge'
            WHERE tracking_number = '$tnumbs'");

        // Send email if enabled
        if ($mail_track_update == "Yes") {
            $subject = "$sitename";
            $body = "<p>Dear $receivers_name</p>
                    <p>We are pleased to inform you that your shipment has been updated to $status </p>
                    <center>Tracking Information</center>
                    <p><strong>Tracking Number - $tnumbs </strong></p>
                    <p><strong>Status - $status </strong></p>
                    <p><strong>Current Location - $current_lo </strong></p>
                    <p><strong>Note - $note </strong></p>
                    <p>We hope this meets with your approval. Please do not hesitate to get in touch with us if you need further assistance.</p>
                    <p>For more information visit the <a href='$site_url/track.php'>Tracking Page</a></p>";
            sendMail($receivers_mail, $subject, $body);
        }

        echo "<script>
                alert('Updated Successfully');
                window.location.href = 'edit-tracking.php?num=$tnumbs';
              </script>";
        exit();
    } else {
        echo "<script>alert('Error updating shipment. Please try again.');</script>";
    }
}


function text_input($data)
{
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>



<div class="row">
  <div class="col-12 grid-margin stretch-card">
    <div class="card">
      <div class="card-body">
        <label style="font-weight: bold;font-size: 25px;">TRACKING NUMBER - <?php echo $tnumbs ?></label>

      </div>
    </div>
  </div>
  <div class="col-md-12 grid-margin stretch-card">
    <div class="card">
      <div class="card-body">
        <form method="post" action="edit-tracking.php?num=<?php echo $tnumbs ?>" class="forms-sample">
          <div class="form-group">
            <label for="exampleInputUsername1">Status</label>
            <select class="form-control" name="status">
              <option value="CREATED">CREATED</option>
              <option value="IN PROCESS">IN PROCESS</option>
              <option value="SHIPPED">SHIPPED</option>
              <option value="IN TRANSIT">IN TRANSIT</option>
              <option value="ON HOLD">ON HOLD</option>
              <option value="DELAYED">DELAYED</option>
              <option value="CANCELLED">CANCELLED</option>
              <option value="DELIVERED">DELIVERED</option>
            </select>
          </div>
          <div class="form-group">
            <label for="exampleInputPassword1">Current Location</label>
            <input type="text" class="form-control" value="" name="current_loc" id="exampleInputPassword1" placeholder="Current Location ">
          </div>

          <div class="form-group">
            <label for="exampleInputPassword1">Date</label>
            <input type="date" class="form-control" value="" name="date" id="" placeholder="Date">
          </div>

          <div class="form-group">
            <label for="exampleInputPassword1">Time</label>
            <input type="time" class="form-control" value="" name="time" id="" placeholder="">
          </div>

          <div class="form-group">
            <label for="exampleInputPassword1">Shipping Cost</label>
            <input type="text" class="form-control" value="" name="delivery_charge" id="exampleInputPassword1" placeholder="Shipping Cost">
          </div>

          <div class="form-group">
            <label for="exampleInputPassword1">Clerance Cost:</label>
            <input type="text" class="form-control" value="" name="total_charge" id="exampleInputPassword1" placeholder="total charge">
          </div>

          <div class="form-group">
            <label for="exampleInputPassword1">Note</label>
            <textarea name="note" class="form-control"></textarea>
          </div>
      </div>
    </div>
  </div>

</div>
<div class="col-12 grid-margin stretch-card">
  <div class="card">
    <div class="card-body">
      <button class="btn btn-lg btn-success btn-block" name="update">Update</button>
    </div>
  </div>
  </form>
</div>


<?php
include 'footer.php';
?>