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

if (!function_exists('order_compact_badge_class')) {
    function order_compact_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_compact_payment_badge_class')) {
    function order_compact_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, 'mobile');
$storeName = order_setting_value($conn, 'site_name', 'Nay Store');
?><!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>فاتورة الموبايل</title>
<style>
:root{
    --bg:#eef3f8;
    --card:#ffffff;
    --text:#183146;
    --muted:#6b7b8c;
    --line:#e3eaf2;
    --primary:#183b56;
    --primary-soft:#edf4fb;
    --success:#1f8f64;
    --success-soft:#eaf8f1;
    --danger:#c74141;
    --danger-soft:#fdeeee;
    --warning:#b76a11;
    --warning-soft:#fff4e5;
    --shadow:0 18px 40px rgba(17,34,51,.08);
    --radius-xl:24px;
    --radius-lg:18px;
    --radius-md:14px;
}
*{box-sizing:border-box}
html,body{margin:0;padding:0;background:linear-gradient(180deg,#f7fbff 0%,var(--bg) 100%);color:var(--text);font-family:Tahoma,Arial,sans-serif}
body{padding:16px}
.wrap{max-width:760px;margin:0 auto}
.invoice{background:var(--card);border:1px solid rgba(24,59,86,.08);border-radius:var(--radius-xl);box-shadow:var(--shadow);overflow:hidden;margin-bottom:18px}
.invoice-head{position:relative;padding:18px 18px 16px;background:linear-gradient(135deg,#183b56 0%,#25577c 100%);color:#fff}
.invoice-head::after{content:"";position:absolute;inset:auto -40px -40px auto;width:130px;height:130px;border-radius:50%;background:rgba(255,255,255,.08)}
.brand-row{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;position:relative;z-index:1}
.brand-block{display:flex;align-items:center;gap:12px;min-width:0}
.brand-mark{width:46px;height:46px;border-radius:16px;background:rgba(255,255,255,.14);display:flex;align-items:center;justify-content:center;font-size:18px;font-weight:800;flex-shrink:0}
.brand-copy{min-width:0}
.brand-copy h1{margin:0;font-size:18px;line-height:1.3;font-weight:800}
.brand-copy p{margin:4px 0 0;font-size:12px;color:rgba(255,255,255,.8)}
.invoice-chip{display:inline-flex;align-items:center;justify-content:center;padding:8px 12px;border-radius:999px;background:rgba(255,255,255,.12);font-size:12px;font-weight:800;white-space:nowrap}
.order-number{margin-top:14px;font-size:24px;font-weight:900;letter-spacing:.3px;position:relative;z-index:1}
.order-date{margin-top:6px;font-size:12px;color:rgba(255,255,255,.85);position:relative;z-index:1}
.invoice-body{padding:16px}
.section{background:#fff;border:1px solid var(--line);border-radius:var(--radius-lg);padding:14px;margin-bottom:12px}
.section:last-child{margin-bottom:0}
.section-title{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:12px}
.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:var(--radius-md);padding:10px 12px;min-height:66px}
.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}
.meta-value.small{font-size:13px;font-weight:700}
.address-box{background:#f8fbfe;border:1px solid var(--line);border-radius:var(--radius-md);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-list{display:flex;flex-direction:column;gap:10px}
.item-card{display:flex;gap:12px;align-items:flex-start;padding:12px;border:1px solid var(--line);border-radius:var(--radius-md);background:#fbfdff}
.item-thumb,.item-thumb-placeholder{width:60px;height:60px;border-radius:16px;flex-shrink:0}
.item-thumb{object-fit:cover;border:1px solid rgba(24,59,86,.08);background:#fff}
.item-thumb-placeholder{display:flex;align-items:center;justify-content:center;background:linear-gradient(135deg,#edf4fb 0%,#dbe8f4 100%);color:#35506a;font-size:18px;font-weight:900}
.item-main{flex:1;min-width:0}
.item-name{margin:0 0 6px;font-size:14px;font-weight:900;line-height:1.5;color:var(--primary)}
.item-sub{font-size:12px;color:var(--muted);line-height:1.6}
.item-meta{display:flex;flex-wrap:wrap;gap:8px 10px;margin-top:8px}
.item-pill{display:inline-flex;align-items:center;padding:5px 10px;border-radius:999px;background:var(--primary-soft);color:var(--primary);font-size:11px;font-weight:800}
.item-total{text-align:left;min-width:72px}
.item-total .label{display:block;font-size:11px;color:var(--muted);margin-bottom:6px}
.item-total .value{font-size:15px;font-weight:900;color:var(--primary);line-height:1.4}
.summary-card{padding:0;overflow:hidden}
.summary-row{display:flex;align-items:center;justify-content:space-between;gap:10px;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}
.notes-box{background:#f8fbfe;border:1px dashed #cfdbe8;border-radius:var(--radius-md);padding:12px 14px;line-height:1.8;font-size:13px;color:var(--text)}
.footer-box{background:linear-gradient(180deg,#f8fbfe 0%,#f2f7fb 100%);border:1px solid var(--line);border-radius:var(--radius-md);padding:13px 14px;line-height:1.8;font-size:13px;color:#314759}
.empty-value{color:#9aa8b6;font-weight:700}
@media (max-width:560px){
    body{padding:12px}
    .invoice-head{padding:16px 14px}
    .invoice-body{padding:12px}
    .brand-row{flex-direction:column;align-items:flex-start}
    .meta-grid{grid-template-columns:1fr}
    .item-card{padding:10px;gap:10px}
    .item-total{min-width:64px}
    .order-number{font-size:22px}
}
</style>
</head>
<body>
<div class="wrap">
<?php foreach ($orders as $orderIndex => $order): ?>
    <article class="invoice">
        <header class="invoice-head">
            <div class="brand-row">
                <div class="brand-block">
                    <div class="brand-mark"><?= e(mb_substr($storeName !== '' ? $storeName : 'N', 0, 1, 'UTF-8')) ?></div>
                    <div class="brand-copy">
                        <?php if (order_invoice_enabled($settings, 'show_store_name')): ?>
                            <h1><?= e($storeName) ?></h1>
                        <?php else: ?>
                            <h1>فاتورة الطلب</h1>
                        <?php endif; ?>
                        <p>عرض مناسب للموبايل بشكل مرتب وواضح</p>
                    </div>
                </div>
                <div class="invoice-chip">Invoice<?= count($orders) > 1 ? ' #' . ($orderIndex + 1) : '' ?></div>
            </div>
            <?php if (order_invoice_enabled($settings, 'show_order_number')): ?>
                <div class="order-number"><?= 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; ?>
        </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_compact_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 small"><?= 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 small"><?= 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 small"><span class="badge <?= e(order_compact_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 small"><?= 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 small"><?= 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>

                <div class="items-list">
                    <?php foreach ($order['items'] as $item): ?>
                        <?php $thumb = order_invoice_enabled($settings, 'show_product_image') ? order_invoice_image_src($item['product_image'] ?? '') : ''; ?>
                        <div class="item-card">
                            <?php if ($thumb !== ''): ?>
                                <img class="item-thumb" src="<?= e($thumb) ?>" alt="<?= e($item['product_name']) ?>">
                            <?php else: ?>
                                <div class="item-thumb-placeholder">□</div>
                            <?php endif; ?>

                            <div class="item-main">
                                <h4 class="item-name"><?= e($item['product_name']) ?></h4>
                                <div class="item-sub">
                                    <?= (int)$item['quantity'] ?> × <?= number_format((float)$item['unit_price']) ?> د.ع
                                </div>
                                <div class="item-meta">
                                    <span class="item-pill">الكمية: <?= (int)$item['quantity'] ?></span>
                                    <span class="item-pill">سعر الوحدة: <?= number_format((float)$item['unit_price']) ?></span>
                                    <?php if (order_invoice_enabled($settings, 'show_items_sku') && !empty($item['product_sku'])): ?>
                                        <span class="item-pill">SKU: <?= e($item['product_sku']) ?></span>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <div class="item-total">
                                <span class="label">المجموع</span>
                                <span class="value"><?= number_format((float)$item['line_total']) ?></span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </section>

            <?php if (order_invoice_enabled($settings, 'show_totals')): ?>
                <section class="section summary-card">
                    <div class="section-title" style="padding:14px 14px 0;margin-bottom:8px">
                        <h3>الملخص المالي</h3>
                        <span>Invoice Summary</span>
                    </div>
                    <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>
                </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="notes-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="notes-box"><?= nl2br(e($order['admin_notes'])) ?></div>
                </section>
            <?php endif; ?>

            <?php if (!empty($settings['footer_text'])): ?>
                <section class="section">
                    <div class="footer-box"><?= nl2br(e($settings['footer_text'])) ?></div>
                </section>
            <?php endif; ?>
        </div>
    </article>
<?php endforeach; ?>
</div>
</body>
</html>
