<?php
require_once '../includes/auth.php';
require_once 'functions.php';

if (!function_exists('order_print_badge_class')) {
    function order_print_badge_class(?string $status): string
    {
        return match (order_normalize_status($status)) {
            'delivered' => 'badge-success',
            'cancelled' => 'badge-danger',
            'postponed' => 'badge-warning',
            'ready' => 'badge-info',
            default => 'badge-neutral',
        };
    }
}

if (!function_exists('order_print_payment_badge_class')) {
    function order_print_payment_badge_class(?string $status): string
    {
        return match ((string)$status) {
            'paid' => 'badge-success',
            'pending_confirmation' => 'badge-warning',
            'failed', 'refunded' => 'badge-danger',
            default => 'badge-neutral',
        };
    }
}

$ids = [];
if (!empty($_GET['ids'])) {
    $ids = array_values(array_unique(array_filter(array_map('intval', explode(',', (string)$_GET['ids'])))));
}
if (!$ids && !empty($_GET['id'])) {
    $ids[] = (int)$_GET['id'];
}
$orders = [];
foreach ($ids as $id) {
    $order = order_get_by_id($conn, $id);
    if ($order) {
        $orders[] = $order;
    }
}
if (!$orders) { die('الطلب غير موجود'); }
$settings = order_invoice_settings($conn, 'print');
$storeName = order_setting_value($conn, 'site_name', 'Nay Store');
?><!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>طباعة الطلبات</title>
<style>
@page{size:A4 portrait;margin:9mm}
:root{
    --bg:#f3f6fa;
    --card:#ffffff;
    --line:#dfe7ef;
    --text:#183146;
    --muted:#6b7b8c;
    --primary:#183b56;
    --primary-soft:#eef4fa;
    --success:#1f8f64;
    --success-soft:#eaf8f1;
    --danger:#c74141;
    --danger-soft:#fdeeee;
    --warning:#b76a11;
    --warning-soft:#fff4e5;
    --shadow:0 10px 25px rgba(17,34,51,.07);
}
*{box-sizing:border-box}
html,body{margin:0;padding:0;background:var(--bg);color:var(--text);font-family:Tahoma,Arial,sans-serif}
body{padding:12px}
.invoice{width:192mm;min-height:278mm;margin:0 auto 16px;background:var(--card);border:1px solid var(--line);border-radius:22px;box-shadow:var(--shadow);overflow:hidden;page-break-after:always}
.invoice:last-child{page-break-after:auto}
.invoice-head{display:flex;justify-content:space-between;gap:18px;padding:14mm 12mm 10mm;background:linear-gradient(135deg,#183b56 0%,#25577c 100%);color:#fff;position:relative}
.invoice-head::after{content:"";position:absolute;left:-35px;bottom:-35px;width:140px;height:140px;border-radius:50%;background:rgba(255,255,255,.08)}
.brand{position:relative;z-index:1}
.brand h1{margin:0 0 6px;font-size:22px;font-weight:900}
.brand p{margin:0;font-size:12px;color:rgba(255,255,255,.82)}
.head-side{position:relative;z-index:1;text-align:left;min-width:180px}
.invoice-label{display:inline-flex;align-items:center;justify-content:center;padding:7px 12px;border-radius:999px;background:rgba(255,255,255,.13);font-size:12px;font-weight:800}
.order-no{margin-top:12px;font-size:28px;font-weight:900;line-height:1.2}
.order-date{margin-top:6px;font-size:12px;color:rgba(255,255,255,.86)}
.invoice-body{padding:10mm 12mm 12mm}
.section{border:1px solid var(--line);border-radius:18px;background:#fff;padding:12px 14px;margin-bottom:12px}
.section-title{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:10px}
.section-title h3{margin:0;font-size:15px;font-weight:900;color:var(--primary)}
.section-title span{font-size:12px;color:var(--muted)}
.meta-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}
.meta-box{background:#f8fbfe;border:1px solid var(--line);border-radius:14px;padding:10px 12px;min-height:68px}
.meta-label{font-size:11px;color:var(--muted);margin-bottom:6px}
.meta-value{font-size:14px;font-weight:800;line-height:1.45;word-break:break-word}
.address-box{background:#f8fbfe;border:1px solid var(--line);border-radius:14px;padding:12px 14px;line-height:1.8;font-size:13px}
.badge{display:inline-flex;align-items:center;justify-content:center;padding:6px 12px;border-radius:999px;font-size:12px;font-weight:800}
.badge-success{background:var(--success-soft);color:var(--success)}
.badge-danger{background:var(--danger-soft);color:var(--danger)}
.badge-warning{background:var(--warning-soft);color:var(--warning)}
.badge-info{background:#e8f4ff;color:#2065b0}
.badge-neutral{background:#eef3f7;color:#4d6274}
.items-table{width:100%;border-collapse:separate;border-spacing:0 8px}
.items-table thead th{font-size:12px;color:var(--muted);font-weight:800;padding:0 10px 4px;text-align:right}
.items-table tbody td{background:#fbfdff;border-top:1px solid var(--line);border-bottom:1px solid var(--line);padding:10px;text-align:right;vertical-align:middle}
.items-table tbody td:first-child{border-right:1px solid var(--line);border-radius:0 14px 14px 0}
.items-table tbody td:last-child{border-left:1px solid var(--line);border-radius:14px 0 0 14px}
.product-cell{display:flex;align-items:center;gap:10px;min-width:0}
.product-thumb,.product-thumb-placeholder{width:52px;height:52px;border-radius:14px;flex-shrink:0}
.product-thumb{object-fit:cover;border:1px solid rgba(24,59,86,.08);background:#fff}
.product-thumb-placeholder{display:flex;align-items:center;justify-content:center;background:linear-gradient(135deg,#edf4fb 0%,#dbe8f4 100%);color:#35506a;font-size:16px;font-weight:900}
.product-copy{min-width:0}
.product-name{font-size:14px;font-weight:900;color:var(--primary);line-height:1.5}
.product-sub{font-size:11px;color:var(--muted);margin-top:4px}
.money{text-align:left;font-weight:800;white-space:nowrap}
.summary-shell{display:grid;grid-template-columns:1.2fr .9fr;gap:12px;align-items:stretch}
.summary-card{border:1px solid var(--line);border-radius:18px;overflow:hidden;background:#fff}
.summary-row{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:13px 14px;border-bottom:1px solid var(--line);font-size:13px}
.summary-row:last-child{border-bottom:0}
.summary-row strong{font-size:14px}
.summary-total{background:linear-gradient(135deg,#183b56 0%,#244f70 100%);color:#fff}
.summary-total strong,.summary-total span{color:#fff}
.total-box{border:1px solid #d9e3ec;border-radius:18px;background:linear-gradient(180deg,#f8fbfe 0%,#f2f7fb 100%);padding:16px 18px;display:flex;flex-direction:column;justify-content:center}
.total-box .label{font-size:12px;color:var(--muted);margin-bottom:6px}
.total-box .value{font-size:28px;font-weight:900;color:var(--primary);line-height:1.3}
.note-box{background:#f8fbfe;border:1px dashed #cfdbe8;border-radius:14px;padding:12px 14px;line-height:1.8;font-size:13px}
.footer-text{margin-top:12px;padding-top:10px;border-top:1px solid #edf1f5;color:#334;line-height:1.8;font-size:13px}
.empty-value{color:#9aa8b6;font-weight:700}
@media screen{body{overflow-x:auto}}
@media print{
  html,body{background:#fff}
  body{padding:0}
  .invoice{width:100%;min-height:0;border:none;border-radius:0;box-shadow:none;margin:0;page-break-after:always}
  .invoice:last-child{page-break-after:auto}
}
</style>
</head>
<body onload="window.print()">
<?php foreach ($orders as $index => $order): ?>
    <section class="invoice">
        <header class="invoice-head">
            <div class="brand">
                <?php if (order_invoice_enabled($settings, 'show_store_name')): ?>
                    <h1><?= e($storeName) ?></h1>
                <?php else: ?>
                    <h1>فاتورة الطلب</h1>
                <?php endif; ?>
                <p>تنسيق طباعة احترافي وواضح لإدارة الطلبات</p>
            </div>
            <div class="head-side">
                <div class="invoice-label">Invoice<?= count($orders) > 1 ? ' #' . ($index + 1) : '' ?></div>
                <?php if (order_invoice_enabled($settings, 'show_order_number')): ?><div class="order-no"><?= e(order_display_serial($order)) ?></div><?php endif; ?>
                <?php if (order_invoice_enabled($settings, 'show_created_at')): ?><div class="order-date">تاريخ الطلب: <?= e($order['created_at']) ?></div><?php endif; ?>
            </div>
        </header>

        <div class="invoice-body">
            <section class="section">
                <div class="section-title">
                    <h3>بيانات الطلب</h3>
                    <?php if (order_invoice_enabled($settings, 'show_order_status')): ?>
                        <span class="badge <?= e(order_print_badge_class($order['order_status'])) ?>"><?= e(order_status_label($order['order_status'])) ?></span>
                    <?php endif; ?>
                </div>
                <div class="meta-grid">
                    <?php if (order_invoice_enabled($settings, 'show_customer_name')): ?><div class="meta-box"><div class="meta-label">اسم الزبون</div><div class="meta-value"><?= e($order['customer_name']) ?></div></div><?php endif; ?>
                    <?php if (order_invoice_enabled($settings, 'show_customer_phone')): ?><div class="meta-box"><div class="meta-label">رقم الهاتف</div><div class="meta-value"><?= e($order['customer_phone']) ?></div></div><?php endif; ?>
                    <?php if (order_invoice_enabled($settings, 'show_order_type')): ?><div class="meta-box"><div class="meta-label">نوع الطلب</div><div class="meta-value"><?= e(order_type_options()[$order['order_type']] ?? $order['order_type']) ?></div></div><?php endif; ?>
                    <?php if (order_invoice_enabled($settings, 'show_payment_method')): ?><div class="meta-box"><div class="meta-label">طريقة الدفع</div><div class="meta-value"><?= e($order['payment_method_name'] ?? '-') ?></div></div><?php endif; ?>
                    <?php if (order_invoice_enabled($settings, 'show_payment_status')): ?><div class="meta-box"><div class="meta-label">حالة الدفع</div><div class="meta-value"><span class="badge <?= e(order_print_payment_badge_class($order['payment_status'])) ?>"><?= e(payment_status_options()[$order['payment_status']] ?? $order['payment_status']) ?></span></div></div><?php endif; ?>
                    <?php if (($order['order_type'] ?? '') === 'pickup' && !empty($order['pickup_branch'])): ?><div class="meta-box"><div class="meta-label">الفرع</div><div class="meta-value"><?= e($order['pickup_branch']) ?></div></div><?php endif; ?>
                    <?php if (($order['order_type'] ?? '') === 'preorder' && !empty($order['preorder_expected_at'])): ?><div class="meta-box"><div class="meta-label">الموعد المطلوب</div><div class="meta-value"><?= e($order['preorder_expected_at']) ?></div></div><?php endif; ?>
                </div>
                <?php if (order_invoice_enabled($settings, 'show_address')): ?>
                    <div class="address-box" style="margin-top:12px">
                        <strong style="display:block;margin-bottom:4px;color:var(--primary)">العنوان</strong>
                        <?= !empty($order['full_address']) ? nl2br(e($order['full_address'])) : '<span class="empty-value">لا يوجد عنوان</span>' ?>
                    </div>
                <?php endif; ?>
            </section>

            <section class="section">
                <div class="section-title">
                    <h3>تفاصيل المنتجات</h3>
                    <span><?= count($order['items']) ?> عنصر</span>
                </div>
                <table class="items-table">
                    <thead>
                        <tr>
                            <th>المنتج</th>
                            <?php if (order_invoice_enabled($settings, 'show_items_sku')): ?><th>SKU</th><?php endif; ?>
                            <th>السعر</th>
                            <th>الكمية</th>
                            <th>المجموع</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($order['items'] as $item): ?>
                        <?php $thumb = order_invoice_enabled($settings, 'show_product_image') ? order_invoice_image_src($item['product_image'] ?? '') : ''; ?>
                        <tr>
                            <td>
                                <div class="product-cell">
                                    <?php if ($thumb !== ''): ?>
                                        <img class="product-thumb" src="<?= e($thumb) ?>" alt="<?= e($item['product_name']) ?>">
                                    <?php elseif (order_invoice_enabled($settings, 'show_product_image')): ?>
                                        <div class="product-thumb-placeholder">□</div>
                                    <?php endif; ?>
                                    <div class="product-copy">
                                        <div class="product-name"><?= e($item['product_name']) ?></div>
                                        <div class="product-sub"><?= (int)$item['quantity'] ?> × <?= number_format((float)$item['unit_price']) ?> د.ع</div>
                                    </div>
                                </div>
                            </td>
                            <?php if (order_invoice_enabled($settings, 'show_items_sku')): ?><td><?= e($item['product_sku']) ?></td><?php endif; ?>
                            <td class="money"><?= number_format((float)$item['unit_price']) ?> د.ع</td>
                            <td><?= (int)$item['quantity'] ?></td>
                            <td class="money"><?= number_format((float)$item['line_total']) ?> د.ع</td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </section>

            <?php if (order_invoice_enabled($settings, 'show_totals')): ?>
                <section class="summary-shell">
                    <div class="summary-card">
                        <div class="summary-row"><span>المجموع الفرعي</span><strong><?= number_format((float)$order['subtotal']) ?> د.ع</strong></div>
                        <div class="summary-row"><span>البروموكود</span><strong><?= !empty($order['promo_code_text']) ? e($order['promo_code_text']) : '-' ?></strong></div>
                        <div class="summary-row"><span>الخصم</span><strong><?= number_format((float)$order['discount_value']) ?> د.ع</strong></div>
                        <div class="summary-row"><span>التوصيل</span><strong><?= number_format((float)$order['delivery_fee']) ?> د.ع</strong></div>
                        <div class="summary-row summary-total"><span>الإجمالي النهائي</span><strong><?= number_format((float)$order['total_amount']) ?> د.ع</strong></div>
                    </div>
                    <div class="total-box">
                        <div class="label">صافي الفاتورة</div>
                        <div class="value"><?= number_format((float)$order['total_amount']) ?> د.ع</div>
                    </div>
                </section>
            <?php endif; ?>

            <?php if (order_invoice_enabled($settings, 'show_notes') && !empty($order['notes'])): ?>
                <section class="section"><div class="section-title"><h3>ملاحظات الزبون</h3></div><div class="note-box"><?= nl2br(e($order['notes'])) ?></div></section>
            <?php endif; ?>
            <?php if (order_invoice_enabled($settings, 'show_admin_notes') && !empty($order['admin_notes'])): ?>
                <section class="section"><div class="section-title"><h3>ملاحظات الإدارة</h3></div><div class="note-box"><?= nl2br(e($order['admin_notes'])) ?></div></section>
            <?php endif; ?>
            <?php if (!empty($settings['footer_text'])): ?>
                <div class="footer-text"><?= nl2br(e($settings['footer_text'])) ?></div>
            <?php endif; ?>
        </div>
    </section>
<?php endforeach; ?>
</body>
</html>
