<?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.*, sc.name as company_name
              FROM shipping_manifests sm
              LEFT JOIN shipping_companies sc ON sm.shipping_company_id = sc.id
              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 formatPhoneNumber($phone) {
    if (!$phone || trim(strval($phone)) === 'N/A') return '';
    $phoneStr = strval($phone);
    return substr($phoneStr, 0, 1) === '0' ? $phoneStr : '0' . $phoneStr;
}
?>
<!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@400;500;700;800&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"></script>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        
        body {
            font-family: 'Tajawal', sans-serif;
            background-color: #f4f6f9;
            direction: rtl;
            color: #212529;
            padding: 20px;
        }
        
        .no-print {
            text-align: center;
            margin-bottom: 20px;
        }
        
        .print-btn {
            background-color: #007aff;
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 12px;
            font-family: 'Tajawal', sans-serif;
            font-size: 1.1rem;
            font-weight: 700;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);
        }
        
        .print-btn:hover {
            background-color: #005bb5;
        }
        
        /* Policy Print Styles (4-Up A4) */
        @media print {
            @page { size: A4; margin: 5mm; }
            
            body { 
                background: #fff !important; 
                margin: 0; 
                padding: 0; 
            }
            
            .no-print { display: none !important; }
            
            * {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
        }
        
        .policy-print-mode {
            width: 200mm;
            min-height: 287mm;
            margin: 0 auto;
            padding: 0;
            background: white;
        }
        
        /* تثبيت المقاسات بالمليمتر (100mm عرض * 143.5mm طول) */
        .policy-wrapper {
            width: 100mm;
            height: 143.5mm;
            float: right;
            padding: 2mm;
            box-sizing: border-box;
            page-break-inside: avoid;
            /* خطوط القطع المتقطعة */
            border-bottom: 1px dotted #888;
            border-left: 1px dotted #888;
        }
        
        /* إزالة خطوط القطع من الأطراف الخارجية للصفحة */
        .policy-wrapper:nth-child(2n) { border-left: none; }
        .policy-wrapper:nth-child(n+3) { border-bottom: none; }
        
        .policy-card {
            border: 1px solid #333;
            height: 100%;
            border-radius: 4px;
            padding: 5mm;
            font-family: 'Tajawal', sans-serif;
            font-size: 8pt;
            color: #212529;
            display: flex;
            flex-direction: column;
        }
        
        /* تحسين الهيدر */
        .policy-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 2px solid #1a2b48;
            padding-bottom: 3px;
            margin-bottom: 8px;
        }
        
        .policy-header h3 {
            font-size: 11pt;
            margin: 0;
            color: #1a2b48;
            font-weight: 800;
        }
        
        .policy-header p {
            font-size: 7pt;
            margin: 0;
            color: #6c757d;
        }
        
        .policy-content {
            flex-grow: 1;
            display: flex;
            flex-direction: column;
            gap: 5px;
        }
        
        /* تحسين الأقسام وتخفيف الفواصل */
        .policy-section {
            margin-bottom: 5px;
            padding-bottom: 3px;
            border-bottom: 1px solid #e0e0e0;
            line-height: 1.4;
        }
        
        .policy-section:last-of-type {
            border-bottom: none;
            margin-bottom: 0;
        }
        
        .policy-section strong {
            font-weight: 700;
            color: #333;
            font-size: 7.5pt;
            display: block;
            margin-bottom: 1px;
        }
        
        .policy-section span {
            font-size: 7.5pt;
            display: block;
            white-space: normal;
            font-weight: 500;
        }
        
        /* إبراز اسم المستلم */
        .policy-section:nth-child(2) span:first-child {
            font-weight: 800;
            font-size: 8.5pt;
            color: #000;
        }
        
        .policy-section .address-line {
            font-weight: 500;
        }
        
        /* ستايل قسم الملاحظات الجديد */
        .delivery-notes-section {
            flex-grow: 1;
            padding-top: 5px;
            margin-bottom: 5px;
            border-bottom: none;
        }
        
        .note-options {
            display: flex;
            justify-content: space-between;
            font-size: 7pt;
            color: #555;
            margin-bottom: 5px;
        }
        
        .note-options input[type="checkbox"] {
            margin-left: 5px;
            vertical-align: middle;
        }
        
        .handwriting-lines hr {
            border: none;
            border-top: 1px dashed #ccc;
            margin: 5px 0;
        }
        
        .policy-footer {
            margin-top: 0;
            padding-top: 5px;
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            border-top: 1px solid #1a2b48;
        }
        
        /* تحسين منطقة COD */
        .cod-info {
            text-align: right;
        }
        
        .cod-info span {
            font-size: 7pt;
            color: #555;
            font-weight: 500;
            display: block;
            margin-bottom: 2px;
        }
        
        .policy-footer .cod-amount {
            font-size: 14pt;
            font-weight: 800;
            background-color: #28a745;
            color: white;
            direction: ltr;
            margin-top: 2px;
            padding: 3px 7px;
            border: none;
            border-radius: 4px;
            display: inline-block;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .barcode-area {
            text-align: center;
        }
        
        .barcode-area canvas {
            height: 25px !important;
            width: auto !important;
            margin: 0 auto;
            display: block;
        }
        
        .barcode-area p {
            line-height: 1;
            margin: 2px 0 0;
            font-size: 7pt;
            font-weight: 700;
            color: #1a2b48;
            direction: ltr;
        }
        
        @media screen {
            .policy-print-mode {
                box-shadow: 0 4px 12px rgba(48, 48, 51, 0.1);
                margin-bottom: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="no-print">
        <button onclick="window.print()" class="print-btn">
            🖨️ طباعة البوالص (<?php echo count($orders); ?>)
        </button>
    </div>

    <div class="policy-print-mode">
        <?php foreach ($orders as $index => $order): 
            $policyBarcodeId = "barcode-" . $order['order_number'] . "-" . $index;
            $amount = number_format($order['total'], 2, '.', '');
            $phone = formatPhoneNumber($order['phone']);
        ?>
            <div class="policy-wrapper">
                <div class="policy-card">
                    <div class="policy-header">
                        <h3>بوليصة شحن #<?php echo htmlspecialchars($order['order_number']); ?></h3>
                        <p><?php echo htmlspecialchars($manifest['company_name'] ?? 'شركة الشحن'); ?></p>
                    </div>
                    
                    <div class="policy-content">
                        <div class="policy-section">
                            <strong>الراسل:</strong>
                            <span>المتجر</span>
                        </div>
                        
                        <div class="policy-section">
                            <strong>المستلم:</strong>
                            <span><?php echo htmlspecialchars($order['customer_name']); ?></span>
                            <span>هاتف: <span dir="ltr" style="font-weight: 700; font-size: 7.5pt;"><?php echo htmlspecialchars($phone); ?></span></span>
                        </div>
                        
                        <div class="policy-section">
                            <strong>العنوان والتسليم:</strong>
                            <span class="address-line">المحافظة: <?php echo htmlspecialchars($order['city']); ?></span>
                            <span class="address-line">العنوان المفصل: <?php echo htmlspecialchars($order['address']); ?></span>
                        </div>
                        
                        <div class="policy-section" style="border-bottom: none;">
                            <strong>الوصف:</strong>
                            <span>طرد واحد (الكمية: 1)</span>
                        </div>
                    </div>
                    
                    <div class="policy-section delivery-notes-section">
                        <strong>ملاحظات التسليم والمتابعة:</strong>
                        <div class="note-options">
                            <span><input type="checkbox"> لم يرد / مغلق</span>
                            <span><input type="checkbox"> مؤجل / خارج المنطقة</span>
                            <span><input type="checkbox"> إلغاء</span>
                        </div>
                        <div class="handwriting-lines">
                            <hr>
                            <hr>
                        </div>
                    </div>
                    
                    <div class="policy-footer">
                        <div class="cod-info">
                            <span>مبلغ التحصيل (COD):</span>
                            <div class="cod-amount"><?php echo $amount; ?> ج.م</div>
                        </div>
                        <div class="barcode-area">
                            <canvas id="<?php echo $policyBarcodeId; ?>"></canvas>
                            <p><?php echo htmlspecialchars($order['order_number']); ?></p>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <script>
        // Generate Barcodes after page load
        window.addEventListener('load', function() {
            <?php foreach ($orders as $index => $order): 
                $policyBarcodeId = "barcode-" . $order['order_number'] . "-" . $index;
            ?>
                try {
                    const barcodeElement = document.getElementById('<?php echo $policyBarcodeId; ?>');
                    if (barcodeElement) {
                        JsBarcode(barcodeElement, '<?php echo $order['order_number']; ?>', {
                            format: "CODE128",
                            width: 1.2,
                            height: 25,
                            displayValue: false,
                            background: 'transparent',
                            margin: 1,
                            lineColor: '#1a2b48'
                        });
                    }
                } catch(e) {
                    console.error('Failed to generate barcode:', e);
                }
            <?php endforeach; ?>
        });
        
        // Keyboard shortcut
        document.addEventListener('keydown', function(e) {
            if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
                e.preventDefault();
                window.print();
            }
        });
    </script>
</body>
</html>
