<?php
session_start();
$key = md5(date("Y-m-d").":".$_SERVER['REMOTE_ADDR']);
if (!isset($_SESSION['aW1iZXN0cmEuY29tLm15']) || $_SESSION['aW1iZXN0cmEuY29tLm15'] != $key) {
  header("Location: " . $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['SERVER_NAME']);
  exit;
}
include "_header2.php";
include "_navtop.php";
include "_navside.php";
require "conn.php";

// Fetch courier list
$couriers = mysqli_query($con, "SELECT id, courier_name FROM courier ORDER BY courier_name ASC");
?>
<style>
  #scanner { width: 320px; margin: auto; display: none; }
  #scanResultTable td, #scanResultTable th { vertical-align: middle; }
  .toast-custom { position: fixed; top: 20px; right: 20px; min-width: 250px; z-index: 9999; }
  #cameraModal .modal-content { background: rgba(0, 0, 0, 0.5); border: none; box-shadow: none; }
  #cameraModal .modal-dialog { display: flex; align-items: center; justify-content: center; height: 100%; margin: 0; }
  #reader { width: 90vw; max-width: 480px; height: 70vh; border-radius: 20px; overflow: hidden; }
  #powerOffBtn { background: #dc3545; color: #fff; border: none; padding: 10px 20px; border-radius: 8px; margin-top: 10px; cursor: pointer; }
  #powerOffBtn:hover { background: #b02a37; }
  .gap-20 { margin-bottom: 20px; }
</style>

<div id="page-wrapper">
  <div id="page-inner">
    <div class="row">
      <div class="col-md-12">
        <h2>🚚 Shipping Scan</h2>
        <hr>
      </div>
    </div>

    <div class="row mb-3">
      <div class="col-md-6 gap-20">
        <select id="courierSelect" class="form-control mt-2 col-md-12 col-xs-12 gap-20">
                        <option value="">Select Courier</option>
              <?php while($c = mysqli_fetch_assoc($couriers)): ?>
                        <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['courier_name']) ?></option>
              <?php endwhile; ?>
        </select>
        <button id="openCameraBtn" class="btn btn-primary mb-2 col-md-12 col-xs-12 gap-20">
          <i class="fa-solid fa-camera"></i> Start Camera Scanner
        </button>
        <input type="text" id="manualScan" class="form-control mt-2" placeholder="🔤 Or scan manually (Invoice / Tracking)">
        
      </div>

      <div class="col-md-6">
        <div class="alert alert-info">
          <b>Instructions:</b><br>
          ✅ Step 1: Scan <b>Invoice</b> (must be <code>packaging_status=Packed</code> & <code>shipping_status=Waiting</code>)<br>
          ✅ Step 2: Scan <b>Shipping Tag</b> (QR with Tracking Number) and select <b>Courier</b><br>
          🚫 Duplicate Tracking Numbers are blocked automatically.
        </div>
      </div>
    </div>

    <hr>

    <h4>📋 Shipping Scan Log</h4>
    <div class="table-responsive">
      <table id="scanResultTable" class="table table-bordered table-striped">
        <thead>
          <tr>
            <th>#</th>
            <th>Invoice No</th>
            <th>Tracking Number</th>
            <th>Customer</th>
            <th>Courier</th>
            <th>Packaging Status</th>
            <th>Shipping Status</th>
          </tr>
        </thead>
        <tbody id="scanBody">
          <tr><td colspan="8" class="text-center text-muted">No scans yet.</td></tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Modal for Camera -->
<div id="cameraModal" class="modal">
  <div class="modal-content text-center p-2">
    <div id="scanner"></div>
    <button id="powerOffBtn" style="margin: 10px;"><i class="fa-solid fa-power-off"></i></button>
  </div>
</div>

<!-- Toast container -->
<div id="toastContainer" class="toast-custom"></div>

<script src="https://unpkg.com/html5-qrcode"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
const beepSuccess = new Audio("sounds/success.mp3");
const beepError   = new Audio("sounds/error.mp3");

let html5QrCode = null;
let scanning = false;
let lastCode = "";
let counter = 1;
let step = 1; // 1 = invoice, 2 = shipping tag
let currentInvoice = "";

// Camera control
function startCamera() {
  if (scanning) return;
  scanning = true;
  $("#scanner").show();
  if (!html5QrCode) html5QrCode = new Html5Qrcode("scanner");

  html5QrCode.start(
    { facingMode: "environment" },
    { fps: 10, qrbox: 250 },
    (decodedText) => {
      const code = decodedText.trim();
      if (code && code !== lastCode) {
        lastCode = code;
        processScan(code);
        setTimeout(() => { lastCode = ""; }, 1500);
      }
    }
  ).catch(err => {
    console.error("Camera start error:", err);
    showToast("❌ Camera not accessible", "error");
    scanning = false;
  });
}

function stopCamera() {
  if (html5QrCode && scanning) {
    html5QrCode.stop().then(() => {
      scanning = false;
      $("#scanner").hide();
      $("#cameraModal").fadeOut();
    });
  } else $("#cameraModal").fadeOut();
}

$("#openCameraBtn").on("click", function() {
  $("#cameraModal").fadeIn();
  startCamera();
});

$("#powerOffBtn").on("click", function() { stopCamera(); });

$(window).on("click", function(e) {
  if ($(e.target).is("#cameraModal")) stopCamera();
});

$("#manualScan").on("keypress", function(e) {
  if (e.which === 13) {
    e.preventDefault();
    const code = $(this).val().trim();
    if (code) processScan(code);
    $(this).val('');
  }
});

function processScan(code) {
  if (step === 1) {
    verifyInvoice(code);
  } else {
    const courierId = $("#courierSelect").val();
    if (!courierId) {
      showToast("❌ Please select a courier before scanning tag!", "error");
      playBeep(false);
      return;
    }
    linkTracking(currentInvoice, code, courierId);
  }
}

// ==== VERIFY INVOICE ====
function verifyInvoice(invoice_no) {
  console.log("Step 1: Verify invoice", invoice_no); // <--- log invoice
  $.ajax({
    url: "ship_scan_action.php",
    method: "POST",
    data: { step: 1, invoice_no },
    dataType: "json",
    success: function(data) {
      console.log("Response Step 1:", data); // <--- log backend response
      if (data.success) {
        currentInvoice = data.invoice_no;
        step = 2;
        playBeep(true);
        showToast("✅ Invoice OK: " + data.invoice_no + ". Now scan Shipping Tag...", "success");
      } else {
        playBeep(false);
        showToast("❌ " + data.message, "error");
      }
    },
    error: function(xhr) {
      console.error("AJAX Step 1 error:", xhr.responseText); // <--- log error
      playBeep(false);
      showToast("❌ Server error", "error");
    }
  });
}


// Link Tracking with courier
function linkTracking(invoice_no, tracking_no, courier_id) {
  $.ajax({
    url: "ship_scan_action.php",
    method: "POST",
    data: { step: 2, invoice_no, tracking_no, courier_id },
    dataType: "json",
    success: function(data) {
      if (data.success) {
        playBeep(true);
        showToast("✅ Shipping Tag Linked: " + tracking_no, "success");
        const row = `
          <tr class="table-success">
            <td>${counter++}</td>
            <td>${data.invoice_no}</td>
            <td>${data.tracking_no}</td>
            <td>${data.customer}</td>
            <td>${data.courier_name || '-'}</td>
            <td>${data.packaging_status}</td>
            <td>${data.shipping_status}</td>
          </tr>`;
        $("#scanBody").prepend(row);
        step = 1;
        $("#courierSelect").val(""); // reset courier
      } else {
        playBeep(false);
        showToast("❌ " + data.message, "error");
      }
    },
    error: function(xhr) {
      playBeep(false);
      console.error(xhr.responseText);
      showToast("❌ Server error", "error");
    }
  });
}

function playBeep(isSuccess) {
  try { (isSuccess ? beepSuccess : beepError).play(); }
  catch (e) { console.warn("Beep failed:", e); }
}

function showToast(msg, type="info") {
  const bg = (type==="success")?"#28a745":(type==="error")?"#dc3545":"#17a2b8";
  const toast = $(`<div class="toast show" style="background-color:${bg};color:white;margin-bottom:10px;">
    <div class="toast-body">${msg}</div></div>`);
  $("#toastContainer").append(toast);
  setTimeout(() => toast.fadeOut(400, () => toast.remove()), 2500);
}
</script>

<?php include "_footer2.php"; ?>
