```php
<?php

ob_clean();
ob_start();

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

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

date_default_timezone_set("Asia/Jakarta");

header("Content-Type: application/json; charset=utf-8");
http_response_code(200);

// =======================
// DEBUG FILE
// =======================
$debugFile = __DIR__ . "/debug.txt";

function debugLog($text) {

    global $debugFile;

    file_put_contents(
        $debugFile,
        date("H:i:s") . " - " . $text . PHP_EOL,
        FILE_APPEND
    );
}

debugLog("REQUEST MASUK");

// =======================
// FOLDER UPLOAD
// =======================
$uploadDir = __DIR__ . '/../../uploads/';

if (!is_dir($uploadDir)) {

    mkdir($uploadDir, 0777, true);

    debugLog("FOLDER UPLOAD DIBUAT");
}

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

    debugLog("FILE FOTO TIDAK ADA");

    echo json_encode([
        "ok" => false,
        "message" => "File foto tidak ada"
    ], JSON_UNESCAPED_SLASHES);

    ob_end_flush();

    exit;
}

$f = $_FILES['foto'];

debugLog("FILE FOTO TERDETEKSI");

// =======================
// ERROR UPLOAD
// =======================
if ($f['error'] !== UPLOAD_ERR_OK) {

    debugLog("UPLOAD ERROR: " . $f['error']);

    echo json_encode([
        "ok" => false,
        "message" => "Upload error"
    ], JSON_UNESCAPED_SLASHES);

    ob_end_flush();

    exit;
}

// =======================
// VALIDASI EXTENSION
// =======================
$ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));

if ($ext == '') {
    $ext = 'jpg';
}

$allowed = ['jpg', 'jpeg', 'png'];

if (!in_array($ext, $allowed)) {

    debugLog("FORMAT FILE TIDAK VALID");

    echo json_encode([
        "ok" => false,
        "message" => "Format file tidak valid"
    ], JSON_UNESCAPED_SLASHES);

    ob_end_flush();

    exit;
}

// =======================
// SIMPAN FILE
// =======================
$filename =
    "cam_" .
    date("Ymd_His") .
    "_" .
    rand(100,999) .
    "." .
    $ext;

$targetPath = $uploadDir . $filename;

if (!move_uploaded_file($f['tmp_name'], $targetPath)) {

    debugLog("GAGAL SIMPAN FILE");

    echo json_encode([
        "ok" => false,
        "message" => "Gagal menyimpan file"
    ], JSON_UNESCAPED_SLASHES);

    ob_end_flush();

    exit;
}

debugLog("FILE BERHASIL DISIMPAN");

// =======================
// ZBAR
// =======================
$resi = null;
$out = "";

$zbarPath =
    'C:\\Program Files (x86)\\ZBar\\bin\\zbarimg.exe';

if (file_exists($zbarPath)) {

    debugLog("ZBAR DITEMUKAN");

    $cmd =
        '"' . $zbarPath . '" ' .
        escapeshellarg($targetPath) .
        ' 2>&1';

    debugLog("JALANKAN ZBAR");

    $out = shell_exec($cmd);

    debugLog("HASIL ZBAR: " . $out);

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

    $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]);

            debugLog(
                "BARCODE CODE128 TERBACA: " . $resi
            );

            break;
        }
    }

} else {

    debugLog("ZBAR TIDAK DITEMUKAN");
}

// =======================
// OCR FALLBACK
// =======================
if ($resi === null || $resi === "") {

    debugLog("ZBAR GAGAL -> COBA OCR");

    $ocrPath =
        'C:\\Program Files\\Tesseract-OCR\\tesseract.exe';

    if (file_exists($ocrPath)) {

        $cmdOCR =
            '"' . $ocrPath . '" ' .
            escapeshellarg($targetPath) .
            ' stdout 2>&1';

        debugLog("JALANKAN OCR");

        $ocrText = shell_exec($cmdOCR);

        debugLog("HASIL OCR ASLI: " . $ocrText);

        if ($ocrText !== null) {

            // =======================
            // BERSIHKAN OCR
            // =======================
            $ocrText = strtoupper($ocrText);

            $ocrText = preg_replace(
                '/[^A-Z0-9]/',
                ' ',
                $ocrText
            );

            debugLog(
                "HASIL OCR BERSIH: " . $ocrText
            );

            // =======================
            // CARI FORMAT RESI
            // =======================
            if (
                preg_match(
                    '/([A-Z]{1,5}[0-9]{6,}|[0-9]{10,})/',
                    $ocrText,
                    $m
                )
            ) {

                $resi = trim($m[0]);

                debugLog(
                    "OCR BERHASIL BACA RESI: " .
                    $resi
                );

            } else {

                debugLog(
                    "OCR TIDAK MENEMUKAN RESI"
                );
            }
        }

    } else {

        debugLog(
            "TESSERACT OCR TIDAK DITEMUKAN"
        );
    }
}

// =======================
// VALIDASI RESI
// =======================
$status = "gagal";
$pesan = "Barcode / OCR tidak terbaca.";
$openLock = false;

if ($resi !== null && $resi !== "") {

    debugLog("CEK RESI DATABASE");

    $pesan = "Resi tidak terdaftar.";

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

    if ($stmt) {

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

        $stmt->execute();

        $result = $stmt->get_result();

        if (
            $result &&
            $result->num_rows > 0
        ) {

            $status = "berhasil";

            $pesan =
                "Resi valid, akses dibuka.";

            $openLock = true;

            debugLog("RESI VALID");

        } else {

            debugLog(
                "RESI TIDAK TERDAFTAR"
            );
        }

    } else {

        debugLog("QUERY RESI GAGAL");
    }
}

// =======================
// SIMPAN LOG
// =======================
$fotoPathUrl =
    "/smart-drop-point/uploads/" .
    $filename;

$nomorResiForLog = $resi ?? "-";

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

if ($stmt2) {

    $stmt2->bind_param(
        "ssss",
        $nomorResiForLog,
        $status,
        $pesan,
        $fotoPathUrl
    );

    $stmt2->execute();

    debugLog("LOG BERHASIL DISIMPAN");

} else {

    debugLog("GAGAL SIMPAN LOG");
}

// =======================
// RESPONSE FINAL
// =======================
$response = [

    "ok" => true,
    "resi" => $resi,
    "status" => $status,
    "pesan" => $pesan,
    "open_lock" => $openLock,
    "foto_path" => $fotoPathUrl
];

debugLog("KIRIM RESPONSE JSON");

echo json_encode(
    $response,
    JSON_UNESCAPED_SLASHES
);

flush();

ob_end_flush();

debugLog("SELESAI");

exit;
?>
```
