<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once '../../config/database.php';

$manifest_id = $_GET['id'] ?? 0;

if (!$manifest_id) {
    die('رقم المانيفست غير صحيح');
}

try {
    $database = new Database();
    $db = $database->getConnection();

    $query = "SELECT sm.*
              FROM shipping_manifests sm
              WHERE sm.id = ?";
    $stmt = $db->prepare($query);
    $stmt->execute([$manifest_id]);
    $manifest = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$manifest) {
        die('المانيفست غير موجود');
    }

    $query = "SELECT o.*, CONCAT(o.first_name, ' ', o.last_name) as customer_name
              FROM manifest_orders mo
              JOIN orders o ON mo.order_id = o.id
              WHERE mo.manifest_id = ?
              ORDER BY o.id";
    $stmt = $db->prepare($query);
    $stmt->execute([$manifest_id]);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    die('خطأ: ' . $e->getMessage());
}

function generateBarcode($text) {
    return "https://barcode.tec-it.com/barcode.ashx?data=" . urlencode($text) . "&code=Code128&translate-esc=on&unit=Fit&dpi=96&imagetype=Gif&rotation=0&color=%23000000&bgcolor=%23ffffff&qunit=Mm&quiet=0";
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>باركود الطلبات - <?php echo htmlspecialchars($manifest['manifest_number']); ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@700;900&display=swap" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Tajawal', Arial, sans-serif;
            background: #fff;
            padding: 0;
            margin: 0;
        }
        
        /* صفحة A4 - 6 باركود في الصفحة */
        .page {
            width: 210mm;
            height: 297mm;
            padding: 10mm;
            margin: 0 auto;
            background: white;
            page-break-after: always;
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            grid-template-rows: repeat(3, 1fr);
            gap: 8mm;
        }
        
        .page:last-child {
            page-break-after: auto;
        }
        
        /* باركود واحد */
        .barcode-item {
            border: 3px solid #000;
            padding: 8mm;
            background: white;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            page-break-inside: avoid;
            text-align: center;
        }
        
        .order-number {
            font-size: 20pt;
            font-weight: 900;
            color: #000;
            margin-bottom: 5mm;
            letter-spacing: 2px;
        }
        
        .barcode-img {
            width: 90%;
            height: 50px;
            margin: 5mm 0;
        }
        
        .customer-name {
            font-size: 14pt;
            font-weight: 700;
            color: #000;
            margin-top: 3mm;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 100%;
        }
        
        .amount {
            font-size: 18pt;
            font-weight: 900;
            color: #000;
            margin-top: 3mm;
            background: #000;
            color: #fff;
            padding: 3mm 8mm;
            border-radius: 3px;
        }
        
        /* أزرار التحكم */
        .controls {
            position: fixed;
            top: 20px;
            left: 20px;
            z-index: 1000;
            background: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
        }
        
        .control-btn {
            display: block;
            width: 100%;
            background: #000;
            color: #fff;
            border: none;
            padding: 12px 20px;
            font-size: 12pt;
            font-weight: 700;
            font-family: 'Tajawal', Arial;
            cursor: pointer;
            border-radius: 5px;
            margin-bottom: 10px;
        }
        
        .control-btn:hover {
            background: #333;
        }
        
        .control-btn.secondary {
            background: #666;
        }
        
        .control-btn.secondary:hover {
            background: #888;
        }
        
        .layout-selector {
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 2px solid #ddd;
        }
        
        .layout-selector label {
            display: block;
            font-size: 11pt;
            font-weight: 700;
            margin-bottom: 8px;
            color: #000;
        }
        
        .layout-selector select {
            width: 100%;
            padding: 8px;
            font-size: 11pt;
            font-family: 'Tajawal', Arial;
            border: 2px solid #000;
            border-radius: 5px;
        }
        
        @media print {
            @page {
                size: A4 portrait;
                margin: 0;
            }
            
            body {
                margin: 0;
                padding: 0;
            }
            
            .page {
                margin: 0;
                page-break-after: always;
            }
            
            .page:last-child {
                page-break-after: auto;
            }
            
            .controls {
                display: none;
            }
            
            .barcode-item {
                page-break-inside: avoid;
            }
        }
        
        @media screen {
            body {
                background: #e0e0e0;
                padding: 20px;
            }
            
            .page {
                box-shadow: 0 0 10px rgba(0,0,0,0.3);
                margin-bottom: 20px;
            }
        }
        
        /* تخطيط 2×3 (6 باركود) */
        .layout-2x3 {
            grid-template-columns: repeat(2, 1fr);
            grid-template-rows: repeat(3, 1fr);
        }
        
        /* تخطيط 3×4 (12 باركود) */
        .layout-3x4 {
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(4, 1fr);
            gap: 5mm;
        }
        
        .layout-3x4 .barcode-item {
            padding: 5mm;
        }
        
        .layout-3x4 .order-number {
            font-size: 14pt;
            margin-bottom: 3mm;
        }
        
        .layout-3x4 .barcode-img {
            height: 35px;
            margin: 3mm 0;
        }
        
        .layout-3x4 .customer-name {
            font-size: 10pt;
            margin-top: 2mm;
        }
        
        .layout-3x4 .amount {
            font-size: 14pt;
            padding: 2mm 5mm;
            margin-top: 2mm;
        }
        
        /* تخطيط 1×2 (2 باركود كبير) */
        .layout-1x2 {
            grid-template-columns: 1fr;
            grid-template-rows: repeat(2, 1fr);
            gap: 10mm;
        }
        
        .layout-1x2 .barcode-item {
            padding: 15mm;
        }
        
        .layout-1x2 .order-number {
            font-size: 28pt;
            margin-bottom: 8mm;
        }
        
        .layout-1x2 .barcode-img {
            height: 70px;
            margin: 8mm 0;
        }
        
        .layout-1x2 .customer-name {
            font-size: 18pt;
            margin-top: 5mm;
        }
        
        .layout-1x2 .amount {
            font-size: 24pt;
            padding: 5mm 15mm;
            margin-top: 5mm;
        }
    </style>
</head>
<body>
    <div class="controls">
        <div class="layout-selector">
            <label>تخطيط الصفحة:</label>
            <select id="layoutSelect" onchange="changeLayout(this.value)">
                <option value="2x3">2×3 (6 باركود/صفحة) - قياسي</option>
                <option value="3x4">3×4 (12 باركود/صفحة) - مضغوط</option>
                <option value="1x2">1×2 (2 باركود/صفحة) - كبير</option>
            </select>
        </div>
        
        <button onclick="window.print()" class="control-btn">
            🖨️ طباعة الباركود
        </button>
        
        <button onclick="window.close()" class="control-btn secondary">
            ✖️ إغلاق
        </button>
    </div>

    <div id="pages-container">
        <?php
        // التخطيط الافتراضي: 6 باركود في الصفحة
        $items_per_page = 6;
        $chunks = array_chunk($orders, $items_per_page);
        
        foreach ($chunks as $page_orders):
        ?>
            <div class="page layout-2x3">
                <?php foreach ($page_orders as $order): ?>
                    <div class="barcode-item">
                        <div class="order-number"><?php echo htmlspecialchars($order['order_number']); ?></div>
                        
                        <img src="<?php echo generateBarcode($order['order_number']); ?>" 
                             alt="Barcode" 
                             class="barcode-img">
                        
                        <div class="customer-name">
                            <?php echo htmlspecialchars($order['customer_name']); ?>
                        </div>
                        
                        <div class="amount">
                            <?php echo number_format($order['total'], 0); ?> ج.م
                        </div>
                    </div>
                <?php endforeach; ?>
                
                <?php
                // ملء الفراغات
                $remaining = $items_per_page - count($page_orders);
                for ($i = 0; $i < $remaining; $i++):
                ?>
                    <div class="barcode-item" style="border-style: dashed; opacity: 0.2;"></div>
                <?php endfor; ?>
            </div>
        <?php endforeach; ?>
    </div>

    <script>
        const orders = <?php echo json_encode($orders); ?>;
        
        function changeLayout(layout) {
            const container = document.getElementById('pages-container');
            let itemsPerPage = 6;
            let layoutClass = 'layout-2x3';
            
            switch(layout) {
                case '3x4':
                    itemsPerPage = 12;
                    layoutClass = 'layout-3x4';
                    break;
                case '1x2':
                    itemsPerPage = 2;
                    layoutClass = 'layout-1x2';
                    break;
                default:
                    itemsPerPage = 6;
                    layoutClass = 'layout-2x3';
            }
            
            // إعادة بناء الصفحات
            container.innerHTML = '';
            
            for (let i = 0; i < orders.length; i += itemsPerPage) {
                const pageOrders = orders.slice(i, i + itemsPerPage);
                const page = document.createElement('div');
                page.className = 'page ' + layoutClass;
                
                pageOrders.forEach(order => {
                    const item = document.createElement('div');
                    item.className = 'barcode-item';
                    item.innerHTML = `
                        <div class="order-number">${order.order_number}</div>
                        <img src="https://barcode.tec-it.com/barcode.ashx?data=${encodeURIComponent(order.order_number)}&code=Code128&translate-esc=on&unit=Fit&dpi=96&imagetype=Gif&rotation=0&color=%23000000&bgcolor=%23ffffff&qunit=Mm&quiet=0" 
                             alt="Barcode" 
                             class="barcode-img">
                        <div class="customer-name">${order.customer_name}</div>
                        <div class="amount">${parseFloat(order.total).toLocaleString('en-US', {minimumFractionDigits: 0})} ج.م</div>
                    `;
                    page.appendChild(item);
                });
                
                // ملء الفراغات
                const remaining = itemsPerPage - pageOrders.length;
                for (let j = 0; j < remaining; j++) {
                    const empty = document.createElement('div');
                    empty.className = 'barcode-item';
                    empty.style.borderStyle = 'dashed';
                    empty.style.opacity = '0.2';
                    page.appendChild(empty);
                }
                
                container.appendChild(page);
            }
        }
        
        // اختصار لوحة المفاتيح
        document.addEventListener('keydown', function(e) {
            if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
                e.preventDefault();
                window.print();
            }
        });
    </script>
</body>
</html>
