<?php
/**
 * ================================================================
 * CETAK LABEL SINGLE - OPTIMIZED VERSION
 * ================================================================
 * File untuk cetak 1 label per item (akses via GET id)
 * Kombinasi terbaik dari kedua versi dengan fitur:
 * - Flexible Database Path
 * - Professional Error Handling
 * - Enhanced UX with Print Tracking
 * - Clean & Efficient Code
 * - Responsive Design
 * - Fixed Null Value Warnings
 * ================================================================
 */

session_start();

/* =================================================================
   1. SECURITY CHECK - Login Session
================================================================= */
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    header("Location: ../../index.html?error=session");
    exit;
}

/* =================================================================
   2. DATABASE CONNECTION - Flexible Path Detection
================================================================= */
$koneksiPath = '';
$possiblePaths = [
    __DIR__ . '/../../DataBase/koneksi.php',
    __DIR__ . '/../../database/koneksi.php',
    __DIR__ . '/../../db/koneksi.php',
    __DIR__ . '/../DataBase/koneksi.php',
    __DIR__ . '/../database/koneksi.php',
    __DIR__ . '/../config/koneksi.php'
];

foreach ($possiblePaths as $path) {
    if (file_exists($path)) {
        $koneksiPath = $path;
        break;
    }
}

if (empty($koneksiPath)) {
    showError(
        'Database Connection Error',
        'File koneksi.php tidak ditemukan.',
        'Hubungi administrator sistem.',
        'database'
    );
}

require_once $koneksiPath;

if (!$conn) {
    showError(
        'Database Connection Failed',
        'Koneksi ke database gagal.',
        'Periksa konfigurasi database.',
        'database'
    );
}

/* =================================================================
   3. INPUT VALIDATION - Get ID from URL
================================================================= */
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($id <= 0) {
    showError(
        'ID Tidak Valid',
        'Parameter ID tidak ditemukan atau tidak valid.',
        'Pastikan Anda mengakses halaman dengan ID yang benar.',
        'exclamation-triangle'
    );
}

/* =================================================================
   4. DATABASE QUERY
================================================================= */
$sql = "SELECT * FROM inventory WHERE id = ?";
$stmt = $conn->prepare($sql);

if (!$stmt) {
    showError(
        'Database Error',
        'Gagal mempersiapkan query database.',
        'Error: ' . $conn->error,
        'database'
    );
}

$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    showError(
        'Data Tidak Ditemukan',
        'Item dengan ID ' . $id . ' tidak ditemukan di database.',
        'Mungkin data sudah dihapus atau ID salah.',
        'search'
    );
}

$row = $result->fetch_assoc();

/* =================================================================
   5. PREPARE DATA - FIXED NULL VALUE HANDLING
================================================================= */
$username = $_SESSION['username'] ?? 'Staff';
$printDate = date('d F Y');
$printTime = date('H:i');

// Prioritas kode: kode_aset > kode_aset_auto > N/A
$kodeAset = 'N/A';
if (!empty($row['kode_aset'])) {
    $kodeAset = $row['kode_aset'];
} elseif (!empty($row['kode_aset_auto'])) {
    $kodeAset = $row['kode_aset_auto'];
}

// Safe handling untuk null values - FIXED
$merk = !empty($row['merk']) ? trim($row['merk']) : 'N/A';
$kantor = !empty($row['kantor']) ? trim($row['kantor']) : 'N/A';
$jenisBarang = !empty($row['jenis_barang']) ? trim($row['jenis_barang']) : 'Tanpa Nama';

/* =================================================================
   6. HELPER FUNCTION - Error Page Display
================================================================= */
function showError($title, $message, $detail, $icon) {
    ?>
    <!DOCTYPE html>
    <html lang="id">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Error - <?= htmlspecialchars($title) ?></title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
        <style>
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { 
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                display: flex; align-items: center; justify-content: center;
                min-height: 100vh; padding: 20px;
            }
            .error-container {
                background: white; padding: 50px 40px; border-radius: 16px;
                box-shadow: 0 20px 60px rgba(0,0,0,0.3); text-align: center; 
                max-width: 500px; width: 100%;
            }
            .error-icon { 
                font-size: 80px; margin-bottom: 20px; color: #dc2626;
            }
            h2 { 
                color: #1e293b; margin-bottom: 15px; font-size: 24px; 
            }
            p { 
                color: #64748b; margin-bottom: 10px; line-height: 1.6; 
            }
            .detail {
                background: #fef3c7; color: #854d0e; padding: 10px;
                border-radius: 8px; font-size: 13px; margin: 15px 0;
                font-family: 'Courier New', monospace;
            }
            .btn { 
                background: #7AB2B2; color: white; border: none; 
                padding: 14px 30px; border-radius: 8px; cursor: pointer; 
                font-size: 16px; font-weight: 600; margin-top: 20px;
                display: inline-flex; align-items: center; gap: 8px; 
                transition: all 0.3s;
            }
            .btn:hover { 
                background: #4D869C; transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(77, 134, 156, 0.3);
            }
        </style>
    </head>
    <body>
        <div class='error-container'>
            <div class='error-icon'>
                <i class="fas fa-<?= $icon ?>"></i>
            </div>
            <h2><?= htmlspecialchars($title) ?></h2>
            <p><?= htmlspecialchars($message) ?></p>
            <?php if (!empty($detail)): ?>
                <div class="detail"><?= htmlspecialchars($detail) ?></div>
            <?php endif; ?>
            <button class='btn' onclick='window.close()'>
                <i class="fas fa-arrow-left"></i> Tutup Halaman
            </button>
        </div>
    </body>
    </html>
    <?php
    exit;
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cetak Label - <?= htmlspecialchars($jenisBarang) ?></title>
    
    <!-- External Libraries -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"></script>
    
    <style>
        /* ============================================================
           GLOBAL RESET & BASE STYLES
        ============================================================ */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Arial, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            padding: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
        }

        /* ============================================================
           PRINT PAGE SETTINGS
        ============================================================ */
        @page {
            size: 90mm 50mm;
            margin: 0;
        }

        /* ============================================================
           HEADER INFO (NO PRINT)
        ============================================================ */
        .header-info {
            background: white;
            padding: 25px;
            border-radius: 12px;
            margin-bottom: 20px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            border-left: 6px solid #7AB2B2;
            position: fixed;
            top: 20px;
            left: 20px;
            right: 20px;
            z-index: 999;
        }

        .header-info h2 {
            color: #1e293b;
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 20px;
            margin-bottom: 8px;
        }

        .print-info {
            color: #64748b;
            font-size: 13px;
        }

        /* ============================================================
           ACTION BUTTONS (NO PRINT)
        ============================================================ */
        .action-buttons {
            position: fixed;
            top: 30px;
            right: 30px;
            display: flex;
            gap: 12px;
            z-index: 9999;
        }

        .btn {
            padding: 13px 26px;
            border-radius: 10px;
            font-weight: 600;
            font-size: 14px;
            border: none;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }

        .btn-print {
            background: linear-gradient(135deg, #7AB2B2 0%, #4D869C 100%);
            color: white;
        }

        .btn-print:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(122, 178, 178, 0.4);
        }

        .btn-close {
            background: #64748b;
            color: white;
        }

        .btn-close:hover {
            background: #475569;
            transform: translateY(-3px);
        }

        /* ============================================================
           INFO BOX (NO PRINT)
        ============================================================ */
        .info-box {
            background: #f0f9ff;
            border: 2px solid #0ea5e9;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .info-box i {
            font-size: 32px;
            color: #0ea5e9;
        }

        .info-box-content h3 {
            color: #0c4a6e;
            font-size: 16px;
            margin-bottom: 5px;
        }

        .info-box-content p {
            color: #475569;
            font-size: 13px;
            line-height: 1.5;
        }

        /* ============================================================
           PRINT CONTAINER
        ============================================================ */
        .print-container {
            background: white;
            padding: 40px;
            border-radius: 16px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.15);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 120px;
        }

        /* ============================================================
           LABEL BOX DESIGN
        ============================================================ */
        .label-box {
            width: 90mm;
            height: 50mm;
            border: 2.5px solid #1e293b;
            padding: 9px;
            box-sizing: border-box;
            background: white;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            border-radius: 7px;
            page-break-inside: avoid;
            break-inside: avoid;
        }

        /* Header Label */
        .header-label {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 3px solid #7AB2B2;
            padding-bottom: 6px;
            margin-bottom: 7px;
        }

        .brand {
            font-size: 13px;
            font-weight: 900;
            color: #7AB2B2;
            letter-spacing: 1.2px;
        }

        .label-title {
            font-size: 9px;
            color: #64748b;
            font-weight: 700;
            background: #f1f5f9;
            padding: 3px 10px;
            border-radius: 5px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        /* Content Area */
        .content {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            gap: 5px;
        }

        /* Barcode Container */
        .barcode-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            width: 100%;
            padding: 4px;
        }

        .barcode-container svg {
            max-width: 100%;
            height: auto;
        }

        .nama-barang {
            font-size: 12px;
            font-weight: 700;
            color: #334155;
            text-align: center;
            text-transform: uppercase;
            line-height: 1.2;
            max-height: 30px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            width: 100%;
            padding: 0 5px;
        }

        /* Footer Label */
        .footer-label {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 9px;
            color: #475569;
            border-top: 2px solid #e2e8f0;
            padding-top: 6px;
            gap: 10px;
        }

        .kantor-info {
            display: flex;
            align-items: center;
            gap: 5px;
            font-weight: 700;
            color: #1e293b;
        }

        .kantor-info i {
            color: #7AB2B2;
        }

        .merk-badge {
            background: #fef3c7;
            color: #854d0e;
            padding: 3px 9px;
            border-radius: 12px;
            font-size: 8px;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            max-width: 120px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        /* ============================================================
           PRINT MEDIA QUERY
        ============================================================ */
        @media print {
            body {
                background: white;
                padding: 0;
                display: block;
            }
            
            .no-print,
            .header-info,
            .action-buttons,
            .info-box { 
                display: none !important; 
            }
            
            .print-container {
                padding: 0;
                margin: 0;
                box-shadow: none;
                border-radius: 0;
                display: block;
            }
            
            .label-box {
                page-break-inside: avoid;
                break-inside: avoid;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
                margin: 0;
            }

            .header-label {
                border-bottom: 3px solid #7AB2B2 !important;
            }

            .merk-badge {
                background: #fef3c7 !important;
                color: #854d0e !important;
            }
        }

        /* ============================================================
           RESPONSIVE DESIGN
        ============================================================ */
        @media screen and (max-width: 768px) {
            .print-container {
                padding: 20px;
                margin-top: 140px;
            }
            
            .label-box {
                width: 100%;
                max-width: 90mm;
            }
            
            .action-buttons {
                flex-direction: column;
                top: 15px;
                right: 15px;
            }

            .header-info {
                position: relative;
                top: auto;
                left: auto;
                right: auto;
            }
        }
    </style>
</head>
<body>

    <!-- ============================================================
         ACTION BUTTONS (NO PRINT)
    ============================================================ -->
    <div class="action-buttons no-print">
        <button class="btn btn-print" onclick="window.print()">
            <i class="fas fa-print"></i> CETAK LABEL
        </button>
        <button class="btn btn-close" onclick="confirmClose()">
            <i class="fas fa-times"></i> TUTUP
        </button>
    </div>

    <!-- ============================================================
         PRINT CONTAINER
    ============================================================ -->
    <div class="print-container">
        <div>
            <!-- Header Info (No Print) -->
            <div class="header-info no-print">
                <h2>
                    <i class="fas fa-barcode"></i>
                    Preview Label Siap Cetak
                </h2>
                <p class="print-info">
                    <i class="fas fa-calendar-alt"></i> <?= $printDate ?> • 
                    <i class="fas fa-clock"></i> <?= $printTime ?> • 
                    <i class="fas fa-user"></i> <?= htmlspecialchars($username) ?>
                </p>
            </div>

            <!-- Info Box (No Print) -->
            <div class="info-box no-print">
                <i class="fas fa-info-circle"></i>
                <div class="info-box-content">
                    <h3>Tips Cetak Label</h3>
                    <p>
                        Pastikan printer sudah siap dengan kertas label ukuran <strong>90mm x 50mm</strong>. 
                        Tekan <strong>Ctrl+P</strong> atau klik tombol "CETAK LABEL" di atas.
                    </p>
                </div>
            </div>

            <!-- LABEL BOX -->
            <div class="label-box">
                <!-- Header -->
                <div class="header-label">
                    <span class="brand">ACF EDU HUB</span>
                    <span class="label-title">Asset Label</span>
                </div>
                
                <!-- Content with Barcode -->
                <div class="content">
                    <div class="barcode-container">
                        <svg id="barcode"></svg>
                    </div>
                    <div class="nama-barang">
                        <?= htmlspecialchars($jenisBarang) ?>
                    </div>
                </div>

                <!-- Footer -->
                <div class="footer-label">
                    <div class="kantor-info">
                        <i class="fas fa-map-marker-alt"></i>
                        <?= htmlspecialchars($kantor) ?>
                    </div>
                    <span class="merk-badge" title="<?= htmlspecialchars($merk) ?>">
                        <?= htmlspecialchars($merk) ?>
                    </span>
                </div>
            </div>
        </div>
    </div>

    <!-- ============================================================
         JAVASCRIPT - Barcode Generation & Print Tracking
    ============================================================ -->
    <script>
        // Generate Barcode
        (function() {
            try {
                JsBarcode("#barcode", "<?= htmlspecialchars($kodeAset, ENT_QUOTES, 'UTF-8') ?>", {
                    format: "CODE128",
                    width: 1.5,
                    height: 35,
                    displayValue: true,
                    fontSize: 10,
                    fontOptions: "bold",
                    textMargin: 2,
                    margin: 2
                });
            } catch(e) {
                console.error("Error generating barcode:", e);
                document.getElementById('barcode').innerHTML = 
                    '<text x="50%" y="50%" text-anchor="middle" style="fill:#dc2626; font-size:12px;">ERROR: Barcode generation failed</text>';
            }
        })();

        // Track print status
        let printed = false;
        
        window.onbeforeprint = function() {
            printed = true;
            console.log('🖨️ Printing started...');
        };

        window.onafterprint = function() {
            console.log('✅ Printing completed');
        };
        
        // Confirm before closing if not printed
        function confirmClose() {
            if (!printed) {
                if (confirm('⚠️ Label belum dicetak. Yakin ingin menutup halaman?')) {
                    window.close();
                }
            } else {
                window.close();
            }
        }
        
        // Warn before closing page
        window.onbeforeunload = function(e) {
            if (!printed) {
                const message = "Label belum dicetak. Yakin ingin meninggalkan halaman?";
                e.returnValue = message;
                return message;
            }
        };

        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            // Ctrl+P or Cmd+P for print
            if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
                e.preventDefault();
                window.print();
            }
            
            // ESC to close (only if already printed)
            if (e.key === 'Escape' && printed) {
                window.close();
            }
        });

        // Console logging for debugging
        console.log('✅ Label preview loaded successfully');
        console.log('📦 Asset:', '<?= htmlspecialchars($jenisBarang) ?>');
        console.log('🏢 Location:', '<?= htmlspecialchars($kantor) ?>');
        console.log('🔢 Code:', '<?= htmlspecialchars($kodeAset) ?>');
        console.log('🏷️ Brand:', '<?= htmlspecialchars($merk) ?>');
        console.log('👤 Printed by:', '<?= htmlspecialchars($username) ?>');
        console.log('📅 Date:', '<?= $printDate ?> <?= $printTime ?>');
        console.log('💡 Press Ctrl+P to print or click the button');
    </script>

</body>
</html>

<?php
// Clean up
$stmt->close();
$conn->close();
?>