<?php
include 'header.php';
include '../koneksi/koneksi.php'; // pastikan path sesuai

// Validasi parameter invoice
if (!isset($_GET['inv']) || empty($_GET['inv'])) {
    echo "<div style='padding:20px; color:red; font-weight:bold;'>
            Invoice tidak ditemukan. <a href='produksi.php'>Kembali</a>
          </div>";
    exit;
}

$invoices = mysqli_real_escape_string($conn, $_GET['inv']);

// Ambil data order
$d_order = mysqli_query($conn, "SELECT * FROM produksi WHERE invoice = '$invoices' LIMIT 1");
$t_order = mysqli_fetch_assoc($d_order);

if (!$t_order) {
    echo "<div style='padding:20px; color:red; font-weight:bold;'>
            Data order tidak ditemukan. <a href='produksi.php'>Kembali</a>
          </div>";
    exit;
}

// Ambil data customer
$cs = mysqli_query($conn, "SELECT * FROM customer WHERE kode_customer='".$t_order['kode_customer']."' LIMIT 1");
$t_cs = mysqli_fetch_assoc($cs);

// Hitung total
$total = 0;
$items = [];
$order_items = mysqli_query($conn, "SELECT * FROM produksi WHERE invoice='$invoices'");
while($row = mysqli_fetch_assoc($order_items)){
    $row['subtotal'] = $row['harga'] * $row['qty'];
    $total += $row['subtotal'];
    $items[] = $row;
}

function centerText($text, $width = 32) {
    $len = strlen($text);
    if ($len >= $width) return substr($text, 0, $width);
    $pad = floor(($width - $len) / 2);
    return str_repeat(' ', $pad) . $text;
}

function wrapText($text, $width = 32) {
    // Bungkus teks panjang agar tidak melewati batas lebar
    return wordwrap(trim($text), $width, "\n", true);
}

$resi_text  = "";
$resi_text .= centerText("*** RESI PENGIRIMAN ***")."\n";
$resi_text .= "================================\n";
$resi_text .= "No. Resi : ".$t_order['invoice']."\n";
$resi_text .= "Tanggal  : ".date("d-m-Y H:i")."\n";
$resi_text .= "--------------------------------\n";
$resi_text .= "PENERIMA:\n";
$resi_text .= wrapText(strtoupper($t_cs['nama']))."\n";
$resi_text .= wrapText(strtoupper($t_order['alamat'])." ".$t_order['kota']." ".$t_order['kode_pos'])."\n";
$resi_text .= "Telp: ".$t_cs['telp']."\n";
$resi_text .= "--------------------------------\n";
$resi_text .= "PENGIRIM:\n";
$resi_text .= wrapText("UMKM GALERI 3D")."\n";
$resi_text .= wrapText("Jl. Jend. Sudirman No 60 RT.08 RW.01\nKec. Sumberpucung Kab. Malang")."\n";
$resi_text .= "Telp: 0831-7495-6776\n";
$resi_text .= "--------------------------------\n";
$resi_text .= "DETAIL PESANAN:\n";
foreach ($items as $it) {
    $nama = strtoupper($it['nama_produk']);
    $nama_wrapped = wrapText($nama);
    $resi_text .= $nama_wrapped."\n";
    $resi_text .= sprintf("   %d x Rp %s\n", $it['qty'], number_format($it['harga'], 0, ',', '.'));
}
$resi_text .= "--------------------------------\n";

$left = "TOTAL";
$right = "Rp ".number_format($total, 0, ',', '.');
$max_width = 32;
$line_length = strlen($left) + strlen($right);

if ($line_length > $max_width) {
    // Jika terlalu panjang, pindah ke baris baru agar tetap rapi
    $resi_text .= sprintf("%s\n%32s\n", $left, $right);
} else {
    $space = $max_width - $line_length;
    $resi_text .= $left . str_repeat(' ', $space) . $right . "\n";
}
$resi_text .= "--------------------------------\n";
$barcode_data = $t_order['invoice'];

// ESC/POS Commands:
// \x1B\x61\x01 => center align
// \x1D\x77\x03 => width (besar sedang, 1–6 biasanya; makin besar makin tebal)
// \x1D\x68\x50 => height (tinggi 80px)
// \x1D\x6B\x49 => print CODE128
// \x1B\x61\x00 => reset align left
$barcode_cmd  = "\x1B\x61\x01"; // center
$barcode_cmd .= "\x1D\x77\x03"; // lebar garis barcode (sedikit besar)
$barcode_cmd .= "\x1D\x68\x50"; // tinggi barcode (lebih tinggi)
$barcode_cmd .= "\x1D\x6B\x49" . chr(strlen($barcode_data)) . $barcode_data; // cetak barcode
$barcode_cmd .= "\x1B\x61\x00"; // reset align kiri

$resi_text .= "\n";
$resi_text .= $barcode_cmd;
$resi_text .= "\n";

// === KIRIM KE PRINTER RAWBT ===
$encoded = urlencode($resi_text);
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Label Pengiriman - <?= htmlspecialchars($t_order['invoice']) ?></title>
<style>
    body {
        background: #f3f4f6;
        font-family: 'Poppins', sans-serif;
        margin: 0;
        padding: 0;
    }
    .container {
  	max-width: 1200px;
    margin: 5px auto;
    padding: 0 30px;
    }

    .label-resi {
        width: 80mm;
        max-width: 100%;
        border: 2px dashed #000;
        background: #fff;
        padding: 10px;
        margin: 20px auto;
        box-sizing: border-box;
        border-radius: 5px;
    }

    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 2px solid #000;
        padding-bottom: 4px;
        margin-bottom: 8px;
    }

    .resi-no {
        font-size: 14px;
        font-weight: bold;
    }

    .section {
        margin-bottom: 10px;
    }

    .section .title {
        font-weight: bold;
        font-size: 12px;
        border-bottom: 1px dashed #aaa;
        margin-bottom: 4px;
    }

    .penerima {
        font-size: 13px;
        font-weight: bold;
    }

    .alamat {
        font-size: 11px;
        line-height: 1.4;
    }

    table {
        border-collapse: collapse;
        font-size: 11px;
        width: 100%;
        margin-top: 5px;
    }

    table th, table td {
        border: 1px solid #000;
        padding: 3px;
        text-align: left;
    }

    table th {
        background: #eee;
    }

    .barcode {
        text-align: center;
        margin-top: 10px;
    }

    .barcode svg {
        width: 150px;
        height: 60px;
    }

    /* Tombol area */
    .btn-area {
        display: flex;
        justify-content: center;
        gap: 12px;
        margin-top: 25px;
        flex-wrap: wrap;
    }

    /* Style dasar tombol */
    .btn-rawbt, .btn-back {
        display: inline-block;
        border: none;
        outline: none;
        cursor: pointer;
        padding: 14px 25px;
        border-radius: 10px;
        font-size: 15px;
        font-weight: bold;
        text-decoration: none; /* hilangkan garis bawah */
        color: white;
        box-shadow: 0 3px 6px rgba(0,0,0,0.15);
        user-select: none;
        transition: background 0.2s ease;
    }

    /* Warna tombol */
    .btn-rawbt {
        background: linear-gradient(90deg,#6c5ce7,#4834d4);
    }
    .btn-back {
        background: #b2bec3;
        color: #2d3436;
    }

    /* Hover (opsional, tidak wajib ubah warna) */
    .btn-rawbt:hover {
        background: linear-gradient(90deg,#5b4ce0,#3b2fb3);
    }
    .btn-back:hover {
        background: #a4b0be;
    }

    /* Hilangkan efek active / fokus */
    .btn-rawbt:active,
    .btn-back:active,
    .btn-rawbt:focus,
    .btn-back:focus {
        outline: none;
        box-shadow: none;
        transform: none;
        opacity: 1;
        background: inherit; /* warna tetap sama */
    }

    /* Cetak thermal */
    @page {
        size: 80mm auto;
        margin: 0;
    }

    @media print {
        body {
            background: #fff;
            margin: 0;
        }

        .btn-print {
            display: none;
        }

        .label-resi {
            border: none;
            width: 80mm;
            margin: 0;
            padding: 5px;
            box-shadow: none;
        }

        table th, table td {
            font-size: 10px;
            padding: 2px;
        }
    }

    /* Responsif di HP */
    @media (max-width: 600px) {
        .label-resi {
            width: 95%;
            border: 1px solid #aaa;
        }
        .resi-no { font-size: 13px; }
        .section .title { font-size: 11px; }
        .alamat { font-size: 10px; }
    }
</style>
</head>
<body>
<div class="container">
<div class="label-resi">
    <div class="header">
        <div class="resi-no">No. Resi: <?= htmlspecialchars($t_order['invoice']) ?></div>
        <div style="font-size:12px;">Tanggal: <?= date("d-m-Y") ?></div>
    </div>

    <div class="section">
        <div class="title">Penerima</div>
        <div class="penerima"><?= htmlspecialchars($t_cs['nama']) ?></div>
        <div class="alamat"><?= htmlspecialchars($t_order['alamat']).", ".htmlspecialchars($t_order['kota'])." ".htmlspecialchars($t_order['provinsi']).", ".htmlspecialchars($t_order['kode_pos']) ?></div>
        <div style="font-size:11px;">Telp: <?= htmlspecialchars($t_cs['telp']) ?></div>
    </div>

    <div class="section">
        <div class="title">Pengirim</div>
        <div style="font-size:13px;"><b>UMKM Galeri 3D</b></div>
        <div class="alamat">Jl. Jend. Sudirman No 60 RT.08 RW.01<br>Kec. Sumberpucung Kab. Malang</div>
        <div style="font-size:11px;">Telp: +62 831-7495-6776</div>
    </div>

    <div class="section">
        <div class="title">Detail Pesanan</div>
        <table>
            <tr>
                <th>Kode</th>
                <th>Produk</th>
                <th>Qty</th>
                <th>Subtotal</th>
            </tr>
            <?php foreach($items as $it): ?>
            <tr>
                <td><?= htmlspecialchars($it['kode_produk']) ?></td>
                <td><?= htmlspecialchars($it['nama_produk']) ?></td>
                <td style="text-align:center"><?= $it['qty'] ?></td>
                <td style="text-align:right">Rp <?= number_format($it['subtotal'],0,',','.') ?></td>
            </tr>
            <?php endforeach; ?>
            <tr>
                <td colspan="3" style="text-align:right"><b>Total</b></td>
                <td style="text-align:right"><b>Rp <?= number_format($total,0,',','.') ?></b></td>
            </tr>
        </table>
    </div>

    <div class="barcode">
        <svg id="barcode"></svg>
    </div>
</div>

    <div class="btn-area">
        <a href="rawbt:<?= urlencode($resi_text) ?>" class="btn-rawbt">🖨 Cetak Struk</a>
        <a href="produksi.php" class="btn-back">⬅ Kembali</a>
    </div>
</div>

<!-- JsBarcode -->
<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function(){
    JsBarcode("#barcode", <?= json_encode($t_order['invoice']) ?>, {
        format: "CODE128",
        displayValue: false,
        width: 2,
        height: 60,
        margin: 0,
        lineColor: "#000"
    });
});
</script>

</body>
</html>
