<?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";
?>
<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;
  }

  /* Modal styling */
  #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;
  }
  #notice {
    margin-top: 20px;
    display: none;
  }
  #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>📦 Packaging Scan</h2>
        <hr>
      </div>
    </div>

    <div class="row mb-3">
      <div class="col-md-6 gap-20">
        <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 use QRCode scanner here...">
      </div>

      <div class="col-md-6">
        <div class="alert alert-info">
          Auto camera scan for packaging, or enter manually.
          <b>Instructions:</b><br>
          ✅ <b>Processing</b> → Will mark as Packed<br>
          ⚠️ <b>Pending</b> → Payment not cleared<br>
          🚫 <b>Packed</b> → Already packed
        </div>
      </div>
    </div>

    <hr>

    <h4>📋 Scanned Packaging List</h4>
    <div class="table-responsive">
      <table id="scanResultTable" class="table table-bordered table-striped">
        <thead>
          <tr>
            <th>#</th>
            <th>Invoice No</th>
            <th>Customer</th>
            <th>Package</th>
            <th>Packaging Status</th>
            <th>Shipping Method</th>
            <th>Shipping Status</th>
          </tr>
        </thead>
        <tbody id="scanBody">
          <tr><td colspan="7" 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-bottom: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>
// ==== AUDIO SETUP ====
const beepSuccess = new Audio("sounds/success.mp3");
const beepError   = new Audio("sounds/error.mp3");

// ==== CAMERA CONTROL ====
let html5QrCode = null;
let scanning = false;
let lastCode = "";
let counter = 1;

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;
        handleScan(code);
        // wait 2 seconds before accepting next scan
        setTimeout(() => { lastCode = ""; }, 2000);
      }
    },
    (err) => {}
  ).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();
    }).catch(err => console.error("Camera stop error:", err));
  } else {
    $("#cameraModal").fadeOut();
  }
}

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

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

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

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

// ==== SCAN HANDLER ====
function handleScan(code) {
  if (!code) return;

  $.ajax({
    url: "pack_scan_action.php",
    method: "POST",
    data: { invoice_no: code },
    dataType: "json",
    success: function(data) {
      if (data.success) {
        playBeep(true);
        showToast("✅ Scanned: " + data.invoice_no, "success");
        const row = `
          <tr class="table-success">
            <td>${counter++}</td>
            <td>${data.invoice_no}</td>
            <td>${data.customer}</td>
            <td>${data.package}</td>
            <td>${data.packaging_status}</td>
            <td>${data.shipping_method}</td>
            <td>${data.shipping_status}</td>
          </tr>`;
        $("#scanBody").prepend(row);
      } else {
        playBeep(false);
        showToast("❌ " + data.message, "error");
      }
    },
    error: function(xhr) {
      playBeep(false);
      console.error("Server error:", xhr.responseText);
      showToast("❌ Invalid server response", "error");
    }
  });
}

// ==== BEEP SOUND ====
function playBeep(isSuccess) {
  try {
    if (isSuccess) beepSuccess.play();
    else beepError.play();
  } catch (e) {
    console.warn("Beep play failed:", e);
  }
}

// ==== TOAST ====
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"; ?>
