<?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 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>ملصقات حرارية - Thermal Labels</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;
            margin: 0;
            padding: 0;
        }
        
        /* أزرار التحكم */
        .controls {
            position: fixed;
            top: 20px;
            left: 20px;
            z-index: 1000;
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.3);
            max-width: 300px;
        }
        
        .controls h3 {
            font-size: 14pt;
            font-weight: 900;
            margin-bottom: 15px;
            color: #000;
        }
        
        .size-selector {
            margin-bottom: 20px;
        }
        
        .size-selector label {
            display: block;
            font-size: 11pt;
            font-weight: 700;
            margin-bottom: 10px;
            color: #000;
        }
        
        .size-option {
            display: block;
            padding: 10px;
            margin-bottom: 8px;
            border: 2px solid #ddd;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.2s;
            background: white;
        }
        
        .size-option:hover {
            border-color: #000;
            background: #f5f5f5;
        }
        
        .size-option input {
            margin-left: 10px;
        }
        
        .size-option.active {
            border-color: #000;
            background: #000;
            color: #fff;
        }
        
        .size-info {
            font-size: 9pt;
            color: #666;
            display: block;
            margin-top: 3px;
        }
        
        .size-option.active .size-info {
            color: #ddd;
        }
        
        .control-btn {
            display: block;
            width: 100%;
            background: #000;
            color: #fff;
            border: none;
            padding: 12px;
            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;
        }
        
        /* ملصق واحد - كل ملصق في صفحة منفصلة */
        .label {
            background: white;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            text-align: center;
            page-break-after: always;
            border: 2px solid #000;
            padding: 5mm;
        }
        
        .label:last-child {
            page-break-after: auto;
        }
        
        /* مقاس 100×150mm (4×6 inch) - الأكثر شيوعاً */
        .size-100x150 {
            width: 100mm;
            height: 150mm;
            margin: 0 auto;
        }
        
        /* مقاس 100×100mm (4×4 inch) */
        .size-100x100 {
            width: 100mm;
            height: 100mm;
            margin: 0 auto;
        }
        
        /* مقاس 100×50mm (4×2 inch) - صغير */
        .size-100x50 {
            width: 100mm;
            height: 50mm;
            margin: 0 auto;
        }
        
        /* مقاس 80×80mm - للطابعات الصغيرة */
        .size-80x80 {
            width: 80mm;
            height: 80mm;
            margin: 0 auto;
        }
        
        .order-number {
            font-size: 18pt;
            font-weight: 900;
            color: #000;
            margin-bottom: 3mm;
            letter-spacing: 1px;
        }
        
        .barcode-img {
            width: 90%;
            height: auto;
            max-height: 40mm;
            margin: 3mm 0;
        }
        
        .customer-name {
            font-size: 12pt;
            font-weight: 700;
            color: #000;
            margin: 2mm 0;
            max-width: 90%;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .customer-phone {
            font-size: 11pt;
            font-weight: 700;
            color: #000;
            margin: 2mm 0;
            direction: ltr;
        }
        
        .amount {
            font-size: 16pt;
            font-weight: 900;
            color: #fff;
            background: #000;
            padding: 3mm 8mm;
            border-radius: 3px;
            margin-top: 3mm;
        }
        
        /* تعديلات للمقاسات الصغيرة */
        .size-100x50 .order-number {
            font-size: 14pt;
            margin-bottom: 2mm;
        }
        
        .size-100x50 .barcode-img {
            max-height: 20mm;
            margin: 2mm 0;
        }
        
        .size-100x50 .customer-name {
            font-size: 10pt;
            margin: 1mm 0;
        }
        
        .size-100x50 .customer-phone {
            font-size: 9pt;
        }
        
        .size-100x50 .amount {
            font-size: 12pt;
            padding: 2mm 5mm;
            margin-top: 2mm;
        }
        
        .size-80x80 .order-number {
            font-size: 12pt;
        }
        
        .size-80x80 .barcode-img {
            max-height: 25mm;
        }
        
        .size-80x80 .customer-name {
            font-size: 9pt;
        }
        
        .size-80x80 .amount {
            font-size: 11pt;
            padding: 2mm 4mm;
        }
        
        @media print {
            @page {
                margin: 0;
            }
            
            body {
                margin: 0;
                padding: 0;
            }
            
            .controls {
                display: none;
            }
            
            .label {
                page-break-after: always;
                margin: 0;
                border: none;
            }
            
            .label:last-child {
                page-break-after: auto;
            }
        }
        
        @media screen {
            body {
                background: #e0e0e0;
                padding: 20px;
            }
            
            .label {
                margin-bottom: 20px;
                box-shadow: 0 2px 8px rgba(0,0,0,0.2);
            }
        }
    </style>
</head>
<body>
    <div class="controls">
        <h3>⚙️ إعدادات الطباعة</h3>
        
        <div class="size-selector">
            <label>اختر مقاس الملصق:</label>
            
            <label class="size-option active" onclick="changeSize('100x150', this)">
                <input type="radio" name="size" value="100x150" checked>
                <strong>100×150mm</strong>
                <span class="size-info">4×6 inch - قياسي (موصى به)</span>
            </label>
            
            <label class="size-option" onclick="changeSize('100x100', this)">
                <input type="radio" name="size" value="100x100">
                <strong>100×100mm</strong>
                <span class="size-info">4×4 inch - مربع</span>
            </label>
            
            <label class="size-option" onclick="changeSize('100x50', this)">
                <input type="radio" name="size" value="100x50">
                <strong>100×50mm</strong>
                <span class="size-info">4×2 inch - صغير</span>
            </label>
            
            <label class="size-option" onclick="changeSize('80x80', this)">
                <input type="radio" name="size" value="80x80">
                <strong>80×80mm</strong>
                <span class="size-info">للطابعات الصغيرة</span>
            </label>
        </div>
        
        <button onclick="window.print()" class="control-btn">
            🖨️ طباعة الملصقات
        </button>
        
        <button onclick="window.close()" class="control-btn secondary">
            ✖️ إغلاق
        </button>
        
        <div style="margin-top: 15px; padding-top: 15px; border-top: 2px solid #ddd; font-size: 9pt; color: #666;">
            <strong>عدد الملصقات:</strong> <?php echo count($orders); ?><br>
            <strong>ملاحظة:</strong> كل ملصق في صفحة منفصلة
        </div>
    </div>

    <div id="labels-container">
        <?php foreach ($orders as $order): ?>
            <div class="label size-100x150">
                <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="customer-phone">
                    <?php echo htmlspecialchars($order['phone']); ?>
                </div>
                
                <div class="amount">
                    <?php echo number_format($order['total'], 0); ?> ج.م
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <script>
        function changeSize(size, element) {
            // تحديث الأزرار
            document.querySelectorAll('.size-option').forEach(opt => {
                opt.classList.remove('active');
            });
            element.classList.add('active');
            
            // تحديث المقاس
            document.querySelectorAll('.label').forEach(label => {
                label.className = 'label size-' + size;
            });
            
            // تحديث @page size للطباعة
            const style = document.createElement('style');
            style.id = 'page-size-style';
            
            let pageSize = '';
            switch(size) {
                case '100x150':
                    pageSize = '100mm 150mm';
                    break;
                case '100x100':
                    pageSize = '100mm 100mm';
                    break;
                case '100x50':
                    pageSize = '100mm 50mm';
                    break;
                case '80x80':
                    pageSize = '80mm 80mm';
                    break;
            }
            
            style.textContent = `@media print { @page { size: ${pageSize}; } }`;
            
            const oldStyle = document.getElementById('page-size-style');
            if (oldStyle) {
                oldStyle.remove();
            }
            document.head.appendChild(style);
        }
        
        // تعيين المقاس الافتراضي
        changeSize('100x150', document.querySelector('.size-option.active'));
        
        // اختصار لوحة المفاتيح
        document.addEventListener('keydown', function(e) {
            if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
                e.preventDefault();
                window.print();
            }
        });
    </script>
</body>
</html>
