<?php
require_once('includes/load.php'); // Memuat file load.php
page_require_level(3); // Pastikan level pengguna yang diperlukan

$upload_message = '';

set_time_limit(300); // Atur batas waktu eksekusi menjadi 5 menit
ini_set('memory_limit', '512M'); // Atur batas memori menjadi 512MB

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['pdf_file'])) {
    $upload_dir = "uploads/resi/";
    $convert_dir = "uploads/resiconvert/";

    $pdf_name = pathinfo($_FILES["pdf_file"]["name"], PATHINFO_FILENAME); // Ambil nama PDF tanpa ekstensi
    $target_file = $upload_dir . basename($_FILES["pdf_file"]["name"]);

    // Buat direktori jika belum ada
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    if (!file_exists($convert_dir)) {
        mkdir($convert_dir, 0777, true);
    }

    // Coba upload file PDF
    if (move_uploaded_file($_FILES["pdf_file"]["tmp_name"], $target_file)) {
        $upload_message = "<h1>File " . basename($_FILES["pdf_file"]["name"]) . " berhasil diupload.</h1>";

        // Mendapatkan info halaman PDF
        $pdf_info = shell_exec("pdfinfo '{$target_file}'");
        $upload_message .= "<pre>$pdf_info</pre>";

        if (preg_match('/Pages:\s+(\d+)/', $pdf_info, $matches)) {
            $page_count = (int)$matches[1];
        } else {
            $upload_message .= "<p>Gagal mendapatkan jumlah halaman dari PDF. Output: $pdf_info</p>";
            $page_count = 0;
        }

        $upload_message .= "<h2>Memproses PDF dengan {$page_count} halaman...</h2>";

        // Jumlah batch konversi
        $batch_size = 10; // Batasi 10 halaman per batch
        $batches = ceil($page_count / $batch_size);

        for ($batch = 0; $batch < $batches; $batch++) {
            $start_page = $batch * $batch_size + 1;
            $end_page = min(($batch + 1) * $batch_size, $page_count);

            // Konversi PDF ke JPG dengan resolusi 200 DPI
            $convert_cmd = "pdftocairo -jpeg -r 200 -f $start_page -l $end_page '{$target_file}' '{$convert_dir}/page'";
            exec($convert_cmd . ' 2>&1', $output, $return_var);

            // Retry jika konversi gagal
            $retry_limit = 3;
            $retry_count = 0;

            while ($return_var !== 0 && $retry_count < $retry_limit) {
                $retry_count++;
                exec($convert_cmd . ' 2>&1', $output, $return_var);
            }

            if ($return_var === 0) {
                for ($page = $start_page; $page <= $end_page; $page++) {
                    $output_img = "{$convert_dir}/page-{$page}.jpg";

                    if (file_exists($output_img)) {
                        // Scan barcode menggunakan zbarimg
                        $zbar_cmd = "zbarimg --quiet '{$output_img}'";
                        $barcode_result = shell_exec($zbar_cmd);

                        // Pisahkan hasil scan barcode
                        if ($barcode_result) {
                            $barcodes = explode("\n", trim($barcode_result));

                            // Penamaan file gambar berdasarkan PDF + timestamp + halaman
                            $timestamp = date('Ymd_His');
                            $unique_filename = "{$pdf_name}_{$timestamp}_page{$page}.jpg";
                            $new_output_img = "{$convert_dir}/{$unique_filename}";

                            // Rename gambar
                            rename($output_img, $new_output_img);

                            // Masukkan barcode ke dalam database
                            foreach ($barcodes as $barcode) {
                                if (preg_match('/^(.+?):(.+)$/', $barcode, $matches)) {
                                    $barcode_text = trim($matches[2]);

                                    // Simpan barcode ke database
                                    $stmt = $db->prepare("INSERT INTO barcode_results (barcode_text, file_name) VALUES (?, ?)");
                                    $stmt->execute([$barcode_text, $unique_filename]);

                                    $upload_message .= "<p>Page {$page}: Barcode <strong>{$barcode_text}</strong> berhasil disimpan.</p>";
                                }
                            }
                        } else {
                            $upload_message .= "<p>Page {$page}: Tidak ada barcode yang terdeteksi.</p>";
                        }
                    } else {
                        $upload_message .= "<p>Gagal mengkonversi page {$page} menjadi gambar.</p>";
                    }
                }
            } else {
                $upload_message .= "<p>Gagal mengkonversi batch $batch ke gambar setelah $retry_limit percobaan.</p>";
                $upload_message .= "<pre>" . implode("\n", $output) . "</pre>";
                break; // Berhenti jika batch gagal
            }
        }
    } else {
        $upload_message .= "<p>Maaf, terjadi kesalahan saat mengunggah file Anda.</p>";
    }
}

include_once('layouts/header.php'); // Memuat header.php
?>
<div class="container">
    <h1>Upload PDF dan Konversi ke Gambar</h1>
    <form action="" method="post" enctype="multipart/form-data" class="form-horizontal">
        <div class="form-group">
            <label for="pdf_file" class="col-sm-2 control-label">Pilih File PDF:</label>
            <div class="col-sm-10">
                <input type="file" name="pdf_file" id="pdf_file" accept=".pdf" class="form-control" required>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-primary">Upload dan Konversi</button>
            </div>
        </div>
    </form>
    <!-- Tampilkan hasil disini -->
    <div class="result">
        <?php echo $upload_message; ?>
    </div>
</div>
<?php
include_once('layouts/footer.php'); // Memuat footer.php
?>
