<?php 
include 'config.php'; 

// 🏛️ 1. تضمين ملف التماثيل الفرعونية (statues.php) وجلب المسارات من جدول statues
if (file_exists('statues.php')) {
    include_once 'statues.php';
}

// المسارات الافتراضية للتماثيل بناءً على مجلد statues والصور المتاحة
if (!isset($statues) || !is_array($statues)) {
    $statues = [
        'total_invoices' => 'statues/anubis.png',  // أنوبيس
        'usd_income'     => 'statues/obelisk.png', // المسلة
        'egp_income'     => 'statues/horus.png',   // حورس
        'jpy_income'     => 'statues/obelisk.png'  // المسلة
    ];
}

// جلب التماثيل من قاعدة البيانات
try {
    $statues_stmt = $pdo->query("SELECT card_key, statue_image_path FROM statues");
    $db_statues = $statues_stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    if (!empty($db_statues)) {
        $statues = array_merge($statues, $db_statues);
    }
} catch (Exception $e) {
    try {
        $statues_stmt = $pdo->query("SELECT card_key, statue_image_path FROM dashboard_statues");
        $db_statues = $statues_stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        if (!empty($db_statues)) {
            $statues = array_merge($statues, $db_statues);
        }
    } catch (Exception $ex) {
        // الاعتماد على التماثيل الافتراضية
    }
}

// دالة لحساب وعرض الإجمالي المدفوع بالعملة الفعلية
function format_calculated_total($amount_in_usd, $paid_currency, $egp_rate, $jpy_rate) {
    $paid_currency = strtoupper(trim($paid_currency ?? 'USD'));
    $egp_rate = floatval($egp_rate ?? 1.0);
    $jpy_rate = floatval($jpy_rate ?? 1.0);
    
    switch ($paid_currency) {
        case 'EGP':
        case 'ج.م':
            $calculated_amount = $amount_in_usd * $egp_rate;
            return number_format($calculated_amount, 2) . ' EGP';
        case 'JPY':
            $calculated_amount = $amount_in_usd * $jpy_rate;
            return '¥' . number_format($calculated_amount, 0);
        case 'USD':
        default:
            return '$' . number_format($amount_in_usd, 2);
    }
}

// 📊 2. استعلام حركة الأصناف والمنتجات اليوم اعتماداً على العمود free_qty
$today_date = date('Y-m-d');

$query_today_products = "
    SELECT 
        p.id as product_id,
        p.product_name,
        p.unit,
        SUM(oi.quantity) as total_qty,
        SUM(COALESCE(oi.free_qty, 0)) as free_qty,
        SUM(GREATEST(0, oi.quantity - COALESCE(oi.free_qty, 0))) as paid_qty,
        COUNT(DISTINCT oi.order_id) as orders_count,
        SUM(oi.total) as total_sales_usd
    FROM order_items oi
    JOIN orders o ON oi.order_id = o.id
    JOIN products p ON oi.product_id = p.id
    WHERE DATE(o.order_date) = :today
    GROUP BY oi.product_id, p.product_name, p.unit
    ORDER BY total_qty DESC
";

$stmt_today_prod = $pdo->prepare($query_today_products);
$stmt_today_prod->execute([':today' => $today_date]);
$today_products = $stmt_today_prod->fetchAll();

// 📈 إحصائيات عامة لليوم الحالي
$total_today_free_items = 0;
$total_today_paid_items = 0;
foreach ($today_products as $tp) {
    $total_today_free_items += $tp['free_qty'];
    $total_today_paid_items += $tp['paid_qty'];
}

// منطق حذف الفاتورة وإرجاع البضاعة للمخزن
if (isset($_POST['delete_order'])) {
    $del_order_id = intval($_POST['order_id']);
    
    if ($del_order_id > 0) {
        try {
            $pdo->beginTransaction();
            
            $stmt_get_items = $pdo->prepare("
                SELECT oi.product_id, oi.quantity, p.is_composite, p.raw_product_id, p.consumption_qty, s.branch_id
                FROM order_items oi
                JOIN products p ON oi.product_id = p.id
                JOIN orders o ON oi.order_id = o.id
                JOIN shifts s ON o.shift_id = s.id
                WHERE oi.order_id = :order_id
            ");
            $stmt_get_items->execute([':order_id' => $del_order_id]);
            $items_to_restore = $stmt_get_items->fetchAll();
            
            $stmt_update_inv = $pdo->prepare("
                UPDATE inventory 
                SET quantity = quantity + :qty 
                WHERE branch_id = :branch_id AND product_id = :product_id
            ");
            
            foreach ($items_to_restore as $item) {
                $branch_id = $item['branch_id'];
                
                if ($item['is_composite'] == 1) {
                    $total_grams = $item['quantity'] * $item['consumption_qty'];
                    $qty_to_restore = $total_grams / 1000; 
                    $target_product_id = $item['raw_product_id'];
                } else {
                    $qty_to_restore = $item['quantity'];
                    $target_product_id = $item['product_id'];
                }
                
                if (!empty($target_product_id)) {
                    $stmt_update_inv->execute([
                        ':qty'        => $qty_to_restore,
                        ':branch_id'  => $branch_id,
                        ':product_id' => $target_product_id
                    ]);
                }
            }
            
            $stmt_del_items = $pdo->prepare("DELETE FROM order_items WHERE order_id = :order_id");
            $stmt_del_items->execute([':order_id' => $del_order_id]);
            
            $stmt_del_order = $pdo->prepare("DELETE FROM orders WHERE id = :id");
            $stmt_del_order->execute([':id' => $del_order_id]);
            
            $pdo->commit();
            echo "<script>window.location='reports.php';</script>"; 
            exit;
        } catch (Exception $e) {
            $pdo->rollBack();
            echo "<script>alert('خطأ أثناء الحذف: " . addslashes($e->getMessage()) . "');</script>";
        }
    }
}

include 'header.php'; 

$products_stmt = $pdo->query("SELECT id, product_name FROM products ORDER BY product_name ASC");
$all_products = $products_stmt->fetchAll();

$where_clauses = [];
$params = [];

if (!empty($_GET['start_date'])) {
    $where_clauses[] = "o.order_date >= :start_date";
    $params[':start_date'] = $_GET['start_date'] . ' 00:00:00';
}
if (!empty($_GET['end_date'])) {
    $where_clauses[] = "o.order_date <= :end_date";
    $params[':end_date'] = $_GET['end_date'] . ' 23:59:59';
}
if (!empty($_GET['product_id'])) {
    $where_clauses[] = "o.id IN (SELECT order_id FROM order_items WHERE product_id = :product_id)";
    $params[':product_id'] = intval($_GET['product_id']);
}

$where_sql = "";
if (count($where_clauses) > 0) {
    $where_sql = " WHERE " . implode(" AND ", $where_clauses);
}

$query = "SELECT o.id, o.total_amount, o.order_date, o.currency, b.branch_name, u.full_name as cashier,
                 s.egp_rate, s.jpy_rate
          FROM orders o 
          JOIN shifts s ON o.shift_id = s.id 
          JOIN branches b ON s.branch_id = b.id 
          JOIN users u ON s.user_id = u.id" 
          . $where_sql . 
          " ORDER BY o.order_date DESC";

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$orders = $stmt->fetchAll();

$summary_usd = 0;
$summary_egp = 0;
$summary_jpy = 0;

$items_by_order = [];
if (!empty($orders)) {
    $order_ids = array_column($orders, 'id');
    $in_clause = implode(',', array_fill(0, count($order_ids), '?'));
    
    $items_query = "SELECT oi.*, p.product_name, p.unit 
                    FROM order_items oi 
                    JOIN products p ON oi.product_id = p.id 
                    WHERE oi.order_id IN ($in_clause)";
                    
    $stmt_items = $pdo->prepare($items_query);
    $stmt_items->execute($order_ids);
    
    foreach ($stmt_items->fetchAll() as $item) {
        $items_by_order[$item['order_id']][] = $item;
    }

    foreach ($orders as $row) {
        $curr = strtoupper(trim($row['currency'] ?? 'USD'));
        $amt = floatval($row['total_amount']);
        if ($curr == 'EGP' || $curr == 'ج.م') {
            $summary_egp += $amt * floatval($row['egp_rate'] ?? 1.0);
        } elseif ($curr == 'JPY') {
            $summary_jpy += $amt * floatval($row['jpy_rate'] ?? 1.0);
        } else {
            $summary_usd += $amt;
        }
    }
}
?>

<style>
    body { background-color: #f4f5f7; font-family: 'Cairo', sans-serif; }
    
    .pharaonic-card {
        background: linear-gradient(135deg, #141923 0%, #0b0e14 100%);
        border: 2px solid #dfb76c;
        border-radius: 12px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        color: #ffffff;
        position: relative;
        overflow: hidden;
        min-height: 120px;
        transition: transform 0.3s ease, box-shadow 0.3s ease;
    }
    .pharaonic-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 30px rgba(223, 183, 108, 0.3);
    }
    .pharaonic-card .card-label {
        color: #a0aab5;
        font-size: 0.85rem;
        font-weight: bold;
        display: block;
        margin-bottom: 5px;
    }
    .pharaonic-card .card-value {
        color: #dfb76c;
        font-size: 1.75rem;
        font-weight: 800;
    }
    
    .pharaonic-card .statue-asset {
        position: absolute;
        left: 10px;
        bottom: 0px;
        height: 95px;
        width: auto;
        z-index: 1;
        opacity: 0.9;
        filter: drop-shadow(-5px 5px 10px rgba(0, 0, 0, 0.8));
        transition: transform 0.3s ease;
    }
    .pharaonic-card:hover .statue-asset {
        transform: scale(1.08) rotate(-3deg);
    }

    .filter-card { background: white; border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,0.04); border: 1px solid #e2e8f0; }
    .report-card { background: white; border-radius: 10px; box-shadow: 0 4px 25px rgba(0,0,0,0.06); border: 1px solid #dfb76c; }
    
    .btn-pharaonic { background: linear-gradient(90deg, #141923 0%, #232d3f 100%); color: #dfb76c; border: 1px solid #dfb76c; }
    .btn-pharaonic:hover { background: #dfb76c; color: #141923; border-color: #dfb76c; }
    
    .table thead { background-color: #141923; color: #dfb76c; }
    .order-row { cursor: pointer; transition: background 0.2s; }
    .order-row:hover { background-color: #fdfaf4 !important; }
    
    .badge-gold { background-color: rgba(223, 183, 108, 0.15); color: #c59b4c; border: 1px solid #dfb76c; font-weight: bold; }
    .badge-free { background-color: #28a74520; color: #28a745; border: 1px solid #28a745; font-weight: bold; }
</style>

<div class="container py-4" dir="rtl">
    
    <!-- 🏛️ قسم كروت الإحصائيات بالتماثيل الفرعونية -->
    <div class="row g-3 mb-4">
        <!-- كارت إجمالي الفواتير (أنوبيس) -->
        <div class="col-md-3">
            <div class="pharaonic-card p-3 d-flex flex-column justify-content-between">
                <div>
                    <span class="card-label"><i class="fa fa-folder-open me-1"></i> حصر الفواتير الحالية</span>
                    <span class="card-value"><?= count($orders) ?> <small class="fs-6 text-white">سجلات</small></span>
                </div>
                <img src="<?= htmlspecialchars($statues['total_invoices'] ?? 'statues/anubis.png') ?>" class="statue-asset" alt="Anubis">
            </div>
        </div>
        
        <!-- كارت مبيعات الدولار (المسلة) -->
        <div class="col-md-3">
            <div class="pharaonic-card p-3 d-flex flex-column justify-content-between" style="border-color: #28a745;">
                <div>
                    <span class="card-label text-success"><i class="fa fa-dollar-sign me-1"></i> خزينة الدولار الأمريكي</span>
                    <span class="card-value text-success" dir="ltr">$<?= number_format($summary_usd, 2) ?></span>
                </div>
                <img src="<?= htmlspecialchars($statues['usd_income'] ?? 'statues/obelisk.png') ?>" class="statue-asset" alt="Obelisk">
            </div>
        </div>
        
        <!-- كارت مبيعات الجنيه (حورس) -->
        <div class="col-md-3">
            <div class="pharaonic-card p-3 d-flex flex-column justify-content-between" style="border-color: #007bff;">
                <div>
                    <span class="card-label text-primary"><i class="fa fa-money-bill-wave me-1"></i> إيرادات الجنيه المصري</span>
                    <span class="card-value text-primary" dir="ltr"><?= number_format($summary_egp, 2) ?> <small class="fs-6">EGP</small></span>
                </div>
                <img src="<?= htmlspecialchars($statues['egp_income'] ?? 'statues/horus.png') ?>" class="statue-asset" alt="Horus">
            </div>
        </div>
        
        <!-- كارت مبيعات الين (المسلة) -->
        <div class="col-md-3">
            <div class="pharaonic-card p-3 d-flex flex-column justify-content-between" style="border-color: #ffc107;">
                <div>
                    <span class="card-label text-warning"><i class="fa fa-coins me-1"></i> مقبوضات الين الياباني</span>
                    <span class="card-value text-warning" dir="ltr">¥<?= number_format($summary_jpy, 0) ?></span>
                </div>
                <img src="<?= htmlspecialchars($statues['jpy_income'] ?? 'statues/obelisk.png') ?>" class="statue-asset" alt="Obelisk">
            </div>
        </div>
    </div>

    <!-- 🔥 قسم تحليلات مبيعات اليوم حسب الأصناف 🔥 -->
    <div class="report-card p-4 mb-4" style="border-color: #28a745;">
        <div class="d-flex justify-content-between align-items-center mb-3 border-bottom pb-3">
            <div>
                <h4 class="fw-bold mb-1" style="color: #141923;">
                    <i class="fa fa-chart-pie me-2 text-success"></i> حركة الأصناف والمنتجات اليوم (<?= date('Y-m-d') ?>)
                </h4>
                <small class="text-muted">متابعة دقيقة لكل أصناف المحمصة: الكميات المباعة، الأصناف المدفوعة، والهدايا الفري 🎁</small>
            </div>
            <div class="d-flex gap-2">
                <span class="badge bg-success p-2 fs-6">
                    <i class="fa fa-gift me-1"></i> هدايا اليوم: <?= ($total_today_free_items > 0) ? number_format($total_today_free_items, 2) : 0 ?>
                </span>
                <span class="badge badge-gold p-2 fs-6">
                    <i class="fa fa-boxes me-1"></i> أصناف نشطة: <?= count($today_products) ?>
                </span>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead>
                    <tr style="background-color: #1a2332; color: #28a745;">
                        <th>#</th>
                        <th class="text-start">اسم المنتج / التوليفة</th>
                        <th class="text-center">إجمالي الكمية المباعة</th>
                        <th class="text-center">الكمية المدفوعة 💵</th>
                        <th class="text-center">القطع/الكمية الفري (هدايا 🎁)</th>
                        <th class="text-center">عدد الفواتير</th>
                        <th class="text-center">إجمالي المبيعات المقدرة</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($today_products)): ?>
                        <tr>
                            <td colspan="7" class="text-center py-3 text-muted fw-bold">
                                <i class="fa fa-info-circle me-1"></i> لم يتم تسجيل أي حركة بيع لأي صنف حتى الآن اليوم.
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php 
                        $p_rank = 1;
                        foreach ($today_products as $tp): 
                            $is_kg = ($tp['unit'] === 'kg' || $tp['unit'] === 'كيلو');
                            $format_dec = $is_kg ? 3 : 0;
                        ?>
                            <tr>
                                <td class="fw-bold text-muted"><?= $p_rank++ ?></td>
                                <td class="text-start fw-bold text-dark">
                                    <i class="fa fa-coffee me-1 text-warning"></i> <?= htmlspecialchars($tp['product_name']) ?>
                                </td>
                                <td class="text-center fw-bold fs-6 text-primary">
                                    <?= number_format($tp['total_qty'], $format_dec) ?>
                                    <small class="text-muted fs-7">(<?= $tp['unit'] ?>)</small>
                                </td>
                                <td class="text-center fw-bold text-success">
                                    <?= number_format($tp['paid_qty'], $format_dec) ?>
                                </td>
                                <td class="text-center">
                                    <?php if ($tp['free_qty'] > 0): ?>
                                        <span class="badge badge-free p-2">
                                            🎁 <?= number_format($tp['free_qty'], $format_dec) ?> <?= $tp['unit'] ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <span class="badge bg-light text-dark border"><?= $tp['orders_count'] ?> فاتورة</span>
                                </td>
                                <td class="text-center fw-bold text-dark" dir="ltr">
                                    $<?= number_format($tp['total_sales_usd'], 2) ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- قسم فلاتر البحث -->
    <div class="filter-card p-4 mb-4">
        <h5 class="fw-bold mb-3" style="color: #141923;"><i class="fa fa-search-plus me-1" style="color: #dfb76c;"></i> تحديد النطاق الزمني والسلعي</h5>
        <form method="GET" action="">
            <div class="row g-3 align-items-end">
                <div class="col-md-3">
                    <label class="form-label small fw-bold text-muted">بداية الفترة الزمنية</label>
                    <input type="date" name="start_date" class="form-control" value="<?= htmlspecialchars($_GET['start_date'] ?? '') ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label small fw-bold text-muted">نهاية الفترة الزمنية</label>
                    <input type="date" name="end_date" class="form-control" value="<?= htmlspecialchars($_GET['end_date'] ?? '') ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label small fw-bold text-muted">فلترة بمنتج معين</label>
                    <select name="product_id" class="form-select">
                        <option value="">-- عرض كل منتجات المحمصة --</option>
                        <?php foreach($all_products as $prod): ?>
                            <option value="<?= $prod['id'] ?>" <?= (isset($_GET['product_id']) && $_GET['product_id'] == $prod['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($prod['product_name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3 d-flex gap-2">
                    <button type="submit" class="btn btn-pharaonic w-100 fw-bold"><i class="fa fa-filter me-1"></i> تطبيق الفلترة</button>
                    <a href="?" class="btn btn-outline-secondary w-50">إلغاء</a>
                </div>
            </div>
        </form>
    </div>

    <!-- جدول عرض الفواتير -->
    <div class="report-card p-4">
        <div class="d-flex justify-content-between align-items-center mb-4 border-bottom pb-3">
            <h4 class="fw-bold mb-0" style="color: #141923;"><i class="fa fa-scroll me-2" style="color: #dfb76c;"></i> مضبطة سجلات البيع والمبيعات التفصيلية</h4>
            <span class="badge badge-gold p-2 fs-6">العدد المرصود: <?= count($orders) ?> فاتورة</span>
        </div>
        
        <div class="table-responsive">
            <table class="table align-middle mb-0">
                <thead>
                    <tr>
                        <th style="width: 4%;"></th>
                        <th>رقم الأثر (الكود)</th>
                        <th>الفرع</th>
                        <th>الكاشير المسؤول</th>
                        <th>التاريخ والوقت</th>
                        <th>المبلغ المسدد بالعملة</th>
                        <th class="text-center">الإجراءات والتحكم</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(empty($orders)): ?>
                        <tr>
                            <td colspan="7" class="text-center py-4 text-muted fw-bold">لم يتم العثور على أي فواتير تطابق معايير البحث الحالية في الداتا بيز.</td>
                        </tr>
                    <?php endif; ?>

                    <?php foreach($orders as $row): 
                        $order_items = $items_by_order[$row['id']] ?? [];
                        $paid_currency = $row['currency'] ?? 'USD';
                        $egp_rate = floatval($row['egp_rate'] ?? 1.0);
                        $jpy_rate = floatval($row['jpy_rate'] ?? 1.0);
                        
                        $has_any_promo = false;
                        foreach ($order_items as $itm) {
                            $free_q = floatval($itm['free_qty'] ?? 0);
                            $has_itm_discount = isset($itm['discount_percent']) && floatval($itm['discount_percent']) > 0;
                            
                            if ($free_q > 0 || $has_itm_discount) {
                                $has_any_promo = true;
                                break;
                            }
                        }
                    ?>
                        <tr class="order-row <?= $has_any_promo ? 'table-warning table-opacity-10' : '' ?>" data-bs-toggle="collapse" data-bs-target="#details_<?= $row['id'] ?>">
                            <td><i class="fa fa-chevron-down text-muted small"></i></td>
                            <td class="fw-bold text-dark">#<?= $row['id'] ?></td>
                            <td><?= htmlspecialchars($row['branch_name']) ?></td>
                            <td><span class="badge bg-light text-dark border"><i class="fa fa-user me-1 text-muted"></i><?= htmlspecialchars($row['cashier']) ?></span></td>
                            <td class="text-muted"><?= date('Y-m-d h:i A', strtotime($row['order_date'])) ?></td>
                            
                            <td class="fw-bold text-primary" dir="ltr">
                                <?= format_calculated_total($row['total_amount'], $paid_currency, $egp_rate, $jpy_rate) ?>
                            </td>
                            
                            <td class="text-center" onclick="event.stopPropagation();">
                                <div class="d-flex justify-content-center gap-2">
                                    <button onclick="openPrintWindow(<?= $row['id'] ?>)" class="btn btn-outline-dark btn-sm fw-bold">
                                        <i class="fa fa-print me-1"></i> طباعة الوصل
                                    </button>
                                    
                                    <form method="POST" onsubmit="return confirm('تنبيه المخازن: تأكيد حذف الفاتورة وإعادة كميات البن والمواد الخام تلقائياً إلى الجرد؟');" style="margin:0;">
                                        <input type="hidden" name="order_id" value="<?= $row['id'] ?>">
                                        <button type="submit" name="delete_order" class="btn btn-outline-danger btn-sm fw-bold">
                                            <i class="fa fa-trash-alt me-1"></i> إعدام وحذف
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>

                        <!-- تفاصيل المكونات والمنتجات المركبة داخل الأكورديون -->
                        <tr class="collapse bg-light bg-opacity-50" id="details_<?= $row['id'] ?>">
                            <td colspan="7" class="p-3">
                                <div class="p-3 border rounded bg-white shadow-sm">
                                    <h6 class="fw-bold mb-3 text-dark"><i class="fa fa-box-open me-2 text-warning"></i> بيان الأصناف والكميات المصروفة بالفاتورة:</h6>
                                    <table class="table table-sm table-bordered text-center mb-0">
                                        <thead class="table-secondary text-dark">
                                            <tr>
                                                <th style="width: 5%;">#</th>
                                                <th class="text-start">اسم المنتج / التوليفة</th>
                                                <th>إجمالي الكمية</th>
                                                <th>سعر الوحدة</th>
                                                <th>القطع/الكمية الهدايا (الفري 🎁)</th>
                                                <th>الخصم المطبق</th>
                                                <th>الصافي النهائي</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $counter = 1;
                                            foreach($order_items as $item): 
                                                $item_discount = floatval($item['discount_percent'] ?? 0);
                                                $item_free_qty = floatval($item['free_qty'] ?? 0);
                                                $is_kg = ($item['unit'] === 'kg' || $item['unit'] === 'كيلو');
                                                $dec_f = $is_kg ? 3 : 0;
                                            ?>
                                            <tr class="<?= ($item_free_qty > 0 || $item_discount > 0) ? 'table-success bg-opacity-10' : '' ?>">
                                                <td><?= $counter++ ?></td>
                                                <td class="text-start fw-bold"><?= htmlspecialchars($item['product_name']) ?></td>
                                                <td>
                                                    <?= number_format($item['quantity'], $dec_f) ?>
                                                    <span class="text-muted small">(<?= $item['unit'] ?>)</span>
                                                </td>
                                                <td dir="ltr">$<?= number_format($item['price'], 2) ?></td>
                                                <td>
                                                    <?php if ($item_free_qty > 0): ?>
                                                        <span class="badge bg-success p-1">🎁 <?= number_format($item_free_qty, $dec_f) ?> <?= $item['unit'] ?> فري</span>
                                                    <?php else: ?>
                                                        <span class="text-muted small">-</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if ($item_discount > 0): ?>
                                                        <span class="badge bg-warning text-dark p-1">خصم <?= $item_discount ?>%</span>
                                                    <?php else: ?>
                                                        <span class="text-muted small">-</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="fw-bold text-success" dir="ltr">
                                                    <?= format_calculated_total($item['total'], $paid_currency, $egp_rate, $jpy_rate) ?>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
function openPrintWindow(orderId) {
    var width = 450;
    var height = 650;
    var left = (screen.width - width) / 2;
    var top = (screen.height - height) / 2;
    window.open('print_receipt.php?id=' + orderId, 'PrintInvoice', 'width='+width+',height='+height+',top='+top+',left='+left+',toolbar=no,menubar=no,scrollbars=yes,resizable=yes');
}
</script>

<?php include 'footer.php'; ?>