<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

include "../config/db.php";

header("Content-Type: text/plain");

// =======================
// CEK FOTO
// =======================
if (!isset($_FILES['foto'])) {

    echo "INVALID";
    exit;
}

// =======================
// FOLDER UPLOAD
// =======================
$uploadDir = "uploads/";

if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

// =======================
// SIMPAN FILE
// =======================
$filename = "cam_" . date("Ymd_His") . ".jpg";

$targetFile = $uploadDir . $filename;

if (!move_uploaded_file($_FILES['foto']['tmp_name'], $targetFile)) {

    echo "UPLOAD GAGAL";
    exit;
}

// =======================
// HASIL RESI
// =======================
$nomor_resi = "";

// =======================
// ZBAR BARCODE
// =======================
$zbar = shell_exec("\"C:\\ZBar\\bin\\zbarimg.exe\" --raw " . $targetFile);

$zbar = trim($zbar ?? "");

echo "ZBAR:\n";
echo $zbar;
echo "\n";

// =======================
// JIKA ZBAR BERHASIL
// =======================
if (!empty($zbar)) {

    $nomor_resi = $zbar;
}

// =======================
// OCR FALLBACK
// =======================
if (empty($nomor_resi)) {

    shell_exec("\"C:\\Program Files\\Tesseract-OCR\\tesseract.exe\" " . $targetFile . " uploads/hasil");

    $ocrTxt = "uploads/hasil.txt";

    if (file_exists($ocrTxt)) {

        $ocr = file_get_contents($ocrTxt);

        echo "\nOCR:\n";
        echo $ocr;
        echo "\n";

        // regex khusus resi
        preg_match('/JX[0-9A-Z]+/', $ocr, $match);

        if (isset($match[0])) {

            $nomor_resi = trim($match[0]);
        }
    }
}

// =======================
// DEBUG HASIL
// =======================
echo "\nHASIL FINAL:\n";
echo $nomor_resi;
echo "\n";

// =======================
// DEFAULT STATUS
// =======================
$status = "gagal";
$pesan = "Barcode / OCR tidak terbaca";

// =======================
// CEK DATABASE
// =======================
if (!empty($nomor_resi)) {

    $stmt = $conn->prepare("SELECT * FROM resi WHERE nomor_resi=?");

    $stmt->bind_param("s", $nomor_resi);

    $stmt->execute();

    $result = $stmt->get_result();

    if ($result->num_rows > 0) {

        $status = "berhasil";
        $pesan = "Resi valid, akses dibuka";

        echo "\nVALID";

    } else {

        $status = "gagal";
        $pesan = "Nomor resi tidak ditemukan";

        echo "\nINVALID DATABASE";
    }

} else {

    echo "\nBARCODE / OCR GAGAL";
}

// =======================
// SIMPAN LOG
// =======================
$fotoWeb = "/smart-drop-point/public/" . $targetFile;

$stmtLog = $conn->prepare("
INSERT INTO log_akses
(
    nomor_resi,
    status,
    pesan,
    foto_path
)
VALUES
(
    ?, ?, ?, ?
)
");

$stmtLog->bind_param(
    "ssss",
    $nomor_resi,
    $status,
    $pesan,
    $fotoWeb
);

$stmtLog->execute();

echo "\nLOG TERSIMPAN";

?>