<?php
require_once __DIR__ . '/../config/db.php';

date_default_timezone_set("Asia/Jakarta");

// 1) Folder simpan file (fisik)
$uploadDir = __DIR__ . '/../uploads/';
if (!is_dir($uploadDir)) {
  mkdir($uploadDir, 0777, true);
}

if (!isset($_FILES['foto'])) {
  die("Tidak ada file yang dikirim (name='foto').");
}

$f = $_FILES['foto'];
if ($f['error'] !== UPLOAD_ERR_OK) {
  die("Upload error: " . $f['error']);
}

$ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
$allowed = ['jpg', 'jpeg', 'png'];
if (!in_array($ext, $allowed, true)) {
  die("Format harus jpg/jpeg/png");
}

// 2) Simpan file
$filename = "scan_" . date("Ymd_His") . "_" . bin2hex(random_bytes(3)) . "." . $ext;
$targetPath = $uploadDir . $filename;

if (!move_uploaded_file($f['tmp_name'], $targetPath)) {
  die("Gagal menyimpan file.");
}

// 3) Decode pakai ZBar
$zbar = '"C:\\Program Files (x86)\\ZBar\\bin\\zbarimg.exe"';
$cmd  = $zbar . " " . escapeshellarg($targetPath) . " 2>&1";
$out  = shell_exec($cmd);

if (!$out) {
  $out = "";
}

// Ambil nomor resi: prioritas CODE-128, fallback QR-Code
$resi = null;
$lines = preg_split("/\r\n|\n|\r/", trim($out));

foreach ($lines as $line) {
  if (preg_match('/^CODE-128:(.+)$/', trim($line), $m)) {
    $resi = trim($m[1]);
    break;
  }
}
if ($resi === null) {
  foreach ($lines as $line) {
    if (preg_match('/^QR-Code:(.+)$/', trim($line), $m)) {
      $resi = trim($m[1]);
      break;
    }
  }
}

if ($resi === null || $resi === "") {
  // kalau gak kebaca, tetap simpan log gagal biar ada bukti foto
  $status = "gagal";
  $pesan  = "Barcode tidak terbaca.";
} else {
  // 4) Cek resi valid di tabel resi (sesuaikan kalau nama tabel/kolom kamu beda)
  $status = "gagal";
  $pesan  = "Resi tidak terdaftar.";

  $stmt = $conn->prepare("SELECT 1 FROM resi WHERE nomor_resi = ? LIMIT 1");
  $stmt->bind_param("s", $resi);
  $stmt->execute();
  $r = $stmt->get_result();

  if ($r && $r->num_rows > 0) {
    $status = "berhasil";
    $pesan  = "Resi valid, akses dibuka.";
  }
}

// 5) Simpan ke tabel yang DIPAKAI log.php: log_akses
// log.php kamu pakai kolom: created_at, nomor_resi, status, pesan, foto_path
$fotoPathUrl = "/smart-drop-point/uploads/" . $filename;

$stmt2 = $conn->prepare("INSERT INTO log_akses (nomor_resi, status, pesan, foto_path, created_at) VALUES (?, ?, ?, ?, NOW())");
$stmt2->bind_param("ssss", $resi, $status, $pesan, $fotoPathUrl);
$stmt2->execute();

// 6) Balik ke halaman log (biar gak kepisah)
header("Location: /smart-drop-point/public/log.php");
exit;