<?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, sc.op_phone as company_phone
              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());
}
?>
<!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>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;900&display=swap');
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Tajawal', Arial, sans-serif;
            font-size: 12pt;
            line-height: 1.5;
            color: #000;
            background: #fff;
        }
        
        .page {
            width: 210mm;
            min-height: 297mm;
            padding: 15mm;
            margin: 0 auto;
            background: white;
            position: relative;
        }
        
        /* Header - Simple & Clean */
        .header {
            border-bottom: 3px solid #000;
            padding-bottom: 15px;
            margin-bottom: 20px;
        }
        
        .company-info {
            display: flex;
            justify-content: space-between;
            align-items: start;
            margin-bottom: 10px;
        }
        
        .company-name {
            font-size: 24pt;
            font-weight: 700;
            color: #000;
        }
        
        .manifest-number {
            font-size: 18pt;
            font-weight: 700;
            color: #000;
            text-align: left;
        }
        
        .document-title {
            font-size: 14pt;
            font-weight: 600;
            color: #666;
            margin-top: 5px;
        }
        
        /* Info Section */
        .info-section {
            margin: 20px 0;
            border: 2px solid #000;
            padding: 15px;
        }
        
        .info-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
        }
        
        .info-item {
            border-bottom: 1px solid #ddd;
            padding-bottom: 8px;
        }
        
        .info-label {
            font-size: 9pt;
            color: #666;
            font-weight: 600;
            text-transform: uppercase;
            margin-bottom: 3px;
        }
        
        .info-value {
            font-size: 11pt;
            color: #000;
            font-weight: 600;
        }
        
        /* Table */
        .table-section {
            margin: 20px 0;
        }
        
        .section-title {
            font-size: 14pt;
            font-weight: 700;
            color: #000;
            margin-bottom: 10px;
            padding-bottom: 5px;
            border-bottom: 2px solid #000;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 10px 0;
            font-size: 10pt;
        }
        
        thead {
            background: #000;
            color: #fff;
        }
        
        th {
            padding: 10px 8px;
            text-align: right;
            font-weight: 700;
            font-size: 9pt;
            border: 1px solid #000;
        }
        
        td {
            padding: 8px;
            border: 1px solid #ddd;
            color: #000;
        }
        
        tbody tr:nth-child(even) {
            background: #f9f9f9;
        }
        
        .amount {
            font-weight: 700;
            text-align: left;
        }
        
        .signature-box {
            width: 70px;
            height: 35px;
            border: 1px solid #000;
            background: #fff;
        }
        
        /* Summary */
        .summary-section {
            margin: 20px 0;
            page-break-inside: avoid;
        }
        
        .summary-box {
            border: 2px solid #000;
            padding: 15px;
            margin-bottom: 15px;
        }
        
        .summary-row {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #ddd;
            font-size: 11pt;
        }
        
        .summary-row:last-child {
            border-bottom: none;
        }
        
        .summary-row.total {
            background: #000;
            color: #fff;
            padding: 12px;
            margin: 10px -15px -15px;
            font-size: 14pt;
            font-weight: 700;
        }
        
        /* Signatures */
        .signatures {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            margin-top: 30px;
            page-break-inside: avoid;
        }
        
        .signature-item {
            text-align: center;
            border: 2px solid #000;
            padding: 15px;
        }
        
        .signature-line {
            height: 50px;
            border-bottom: 2px solid #000;
            margin-bottom: 10px;
        }
        
        .signature-label {
            font-size: 10pt;
            font-weight: 700;
            color: #000;
        }
        
        /* Footer */
        .footer {
            position: absolute;
            bottom: 10mm;
            left: 15mm;
            right: 15mm;
            text-align: center;
            font-size: 8pt;
            color: #666;
            border-top: 1px solid #ddd;
            padding-top: 10px;
        }
        
        /* Print Buttons */
        .print-controls {
            position: fixed;
            top: 20px;
            left: 20px;
            z-index: 1000;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        
        .print-btn {
            background: #000;
            color: #fff;
            border: none;
            padding: 12px 24px;
            font-size: 12pt;
            font-weight: 700;
            font-family: 'Tajawal', Arial;
            cursor: pointer;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.3);
            white-space: nowrap;
        }
        
        .print-btn:hover {
            background: #333;
        }
        
        .print-btn.secondary {
            background: #666;
        }
        
        .print-btn.secondary:hover {
            background: #888;
        }
        
        @media print {
            @page {
                size: A4 portrait;
                margin: 0;
            }
            
            body {
                margin: 0;
                padding: 0;
            }
            
            .page {
                margin: 0;
                box-shadow: none;
                page-break-after: always;
            }
            
            .page:last-child {
                page-break-after: auto;
            }
            
            .print-controls,
            .print-btn {
                display: none;
            }
            
            thead {
                display: table-header-group;
            }
            
            tr {
                page-break-inside: avoid;
            }
            
            .info-section,
            .summary-box,
            .signatures {
                page-break-inside: avoid;
            }
        }
        
        @media screen {
            body {
                background: #e0e0e0;
                padding: 20px;
            }
            
            .page {
                box-shadow: 0 0 10px rgba(0,0,0,0.3);
            }
        }
    </style>
</head>
<body>
    <div class="print-controls">
        <button onclick="window.print()" class="print-btn">
            🖨️ طباعة المانيفست
        </button>
        <button onclick="window.open('print-labels.php?id=<?php echo $manifest_id; ?>', '_blank')" class="print-btn secondary">
            📦 بوالص (4/صفحة)
        </button>
        <button onclick="window.open('print-thermal-labels.php?id=<?php echo $manifest_id; ?>', '_blank')" class="print-btn secondary">
            🏷️ ملصقات حرارية
        </button>
    </div>

    <div class="page">
        <!-- Header -->
        <div class="header">
            <div class="company-info">
                <div>
                    <div class="company-name">نظام إدارة الشحن</div>
                    <div class="document-title">محضر تسليم شحنة</div>
                </div>
                <div class="manifest-number">
                    <?php echo htmlspecialchars($manifest['manifest_number']); ?>
                </div>
            </div>
        </div>

        <!-- Info Section -->
        <div class="info-section">
            <div class="info-grid">
                <div class="info-item">
                    <div class="info-label">التاريخ</div>
                    <div class="info-value">
                        <?php echo date('Y/m/d - h:i A', strtotime($manifest['created_at'])); ?>
                    </div>
                </div>
                
                <div class="info-item">
                    <div class="info-label">شركة الشحن</div>
                    <div class="info-value">
                        <?php echo htmlspecialchars($manifest['company_name'] ?? 'غير محدد'); ?>
                    </div>
                </div>
                
                <div class="info-item">
                    <div class="info-label">اسم المندوب</div>
                    <div class="info-value">
                        <?php echo htmlspecialchars($manifest['delegate_name'] ?? 'غير محدد'); ?>
                    </div>
                </div>
                
                <div class="info-item">
                    <div class="info-label">عدد الطلبات</div>
                    <div class="info-value">
                        <?php echo $manifest['total_orders']; ?> طلب
                    </div>
                </div>
            </div>
            
            <?php if ($manifest['notes']): ?>
                <div class="info-item" style="margin-top: 15px; grid-column: 1 / -1;">
                    <div class="info-label">ملاحظات</div>
                    <div class="info-value" style="font-weight: 400;">
                        <?php echo nl2br(htmlspecialchars($manifest['notes'])); ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <!-- Orders Table -->
        <div class="table-section">
            <div class="section-title">تفاصيل الطلبات</div>
            
            <table>
                <thead>
                    <tr>
                        <th style="width: 30px;">#</th>
                        <th style="width: 100px;">رقم الطلب</th>
                        <th>اسم العميل</th>
                        <th style="width: 100px;">الهاتف</th>
                        <th>العنوان</th>
                        <th style="width: 80px;">المدينة</th>
                        <th style="width: 80px;">المبلغ</th>
                        <th style="width: 70px;">التوقيع</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $counter = 1;
                    foreach ($orders as $order): 
                    ?>
                        <tr>
                            <td style="text-align: center; font-weight: 700;"><?php echo $counter++; ?></td>
                            <td style="font-weight: 700;">
                                <?php echo htmlspecialchars($order['order_number']); ?>
                            </td>
                            <td><?php echo htmlspecialchars($order['customer_name']); ?></td>
                            <td style="direction: ltr; text-align: right;">
                                <?php echo htmlspecialchars($order['phone']); ?>
                            </td>
                            <td style="font-size: 9pt;">
                                <?php 
                                $address = htmlspecialchars($order['address']);
                                echo mb_strlen($address) > 30 ? mb_substr($address, 0, 30) . '...' : $address;
                                ?>
                            </td>
                            <td><?php echo htmlspecialchars($order['city']); ?></td>
                            <td class="amount">
                                <?php echo number_format($order['total'], 2); ?> ج.م
                            </td>
                            <td style="text-align: center;">
                                <div class="signature-box"></div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Summary -->
        <div class="summary-section">
            <div class="summary-box">
                <div class="section-title" style="margin-bottom: 15px;">الملخص المالي</div>
                
                <div class="summary-row">
                    <span>إجمالي عدد الطلبات</span>
                    <strong><?php echo $manifest['total_orders']; ?> طلب</strong>
                </div>
                
                <div class="summary-row">
                    <span>إجمالي المبالغ المحصلة</span>
                    <strong><?php echo number_format($manifest['total_amount'], 2); ?> ج.م</strong>
                </div>
                
                <div class="summary-row">
                    <span>تكلفة الشحن (<?php echo $manifest['total_orders']; ?> × 30)</span>
                    <strong>-<?php echo number_format($manifest['shipping_cost'], 2); ?> ج.م</strong>
                </div>
                
                <div class="summary-row total">
                    <span>الصافي المستحق</span>
                    <span><?php echo number_format($manifest['net_amount'], 2); ?> ج.م</span>
                </div>
            </div>
            
            <!-- Signatures -->
            <div class="signatures">
                <div class="signature-item">
                    <div class="signature-line"></div>
                    <div class="signature-label">المندوب</div>
                </div>
                
                <div class="signature-item">
                    <div class="signature-line"></div>
                    <div class="signature-label">المحاسب</div>
                </div>
                
                <div class="signature-item">
                    <div class="signature-line"></div>
                    <div class="signature-label">المدير</div>
                </div>
            </div>
        </div>

        <!-- Footer -->
        <div class="footer">
            تم الإنشاء بواسطة نظام إدارة الشحن • <?php echo date('Y-m-d H:i:s'); ?>
        </div>
    </div>

    <script>
        // Keyboard shortcut
        document.addEventListener('keydown', function(e) {
            if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
                e.preventDefault();
                window.print();
            }
        });
    </script>
</body>
</html>
