<?php
require_once __DIR__ . '/../app/csrf.php';
require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/helpers.php';

require_role(['ADMIN','WAREHOUSE']);

$pdo = db();

$rows = $pdo->query("
    SELECT
        i.id AS issue_id,
        CONCAT(p.name,' - ',LPAD(i.issue_month,2,'0'),'/',i.issue_year) AS issue_label,
        i.cover_price,

        COALESCE((
            SELECT SUM(wri.qty)
            FROM warehouse_receipt_items wri
            JOIN warehouse_receipts wr ON wr.id = wri.receipt_id
            WHERE wri.issue_id = i.id AND wr.status = 'APPROVED'
        ),0) AS qty_in,

        COALESCE((
            SELECT SUM(ddi.qty)
            FROM distributor_dispatch_items ddi
            JOIN distributor_dispatches dd ON dd.id = ddi.dispatch_id
            WHERE ddi.issue_id = i.id AND dd.status = 'APPROVED'
        ),0) AS qty_out,

        COALESCE((
            SELECT SUM(wrti.qty)
            FROM warehouse_return_items wrti
            JOIN warehouse_returns wrt ON wrt.id = wrti.return_id
            WHERE wrti.issue_id = i.id AND wrt.status = 'APPROVED'
        ),0) AS qty_returned,

        (
            COALESCE((
                SELECT SUM(wri.qty)
                FROM warehouse_receipt_items wri
                JOIN warehouse_receipts wr ON wr.id = wri.receipt_id
                WHERE wri.issue_id = i.id AND wr.status = 'APPROVED'
            ),0)
            -
            COALESCE((
                SELECT SUM(ddi.qty)
                FROM distributor_dispatch_items ddi
                JOIN distributor_dispatches dd ON dd.id = ddi.dispatch_id
                WHERE ddi.issue_id = i.id AND dd.status = 'APPROVED'
            ),0)
            +
            COALESCE((
                SELECT SUM(wrti.qty)
                FROM warehouse_return_items wrti
                JOIN warehouse_returns wrt ON wrt.id = wrti.return_id
                WHERE wrti.issue_id = i.id AND wrt.status = 'APPROVED'
            ),0)
        ) AS warehouse_balance

    FROM issues i
    JOIN products p ON p.id = i.product_id
    ORDER BY i.issue_year DESC, i.issue_month DESC, p.name
")->fetchAll();

/* إجماليات */
$totalIn       = array_sum(array_column($rows, 'qty_in'));
$totalOut      = array_sum(array_column($rows, 'qty_out'));
$totalReturned = array_sum(array_column($rows, 'qty_returned'));
$totalBalance  = array_sum(array_column($rows, 'warehouse_balance'));
$totalValue    = array_sum(array_map(fn($r) => (int)$r['warehouse_balance'] * (float)$r['cover_price'], $rows));
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>تقرير مخزون الإصدارات — MGZ</title>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
    font-family: 'Segoe UI', Tahoma, Arial, sans-serif;
    background: #f4f7f6;
    color: #333;
    direction: rtl;
    padding: 20px;
    font-size: 14px;
}
a { color: #1a73e8; text-decoration: none; }
a:hover { text-decoration: underline; }
.back-link { margin-bottom: 14px; display: inline-block; font-size: .9rem; }

.page-header {
    background: linear-gradient(135deg, #1a73e8, #0d47a1);
    color: #fff;
    padding: 18px 24px;
    border-radius: 10px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}
.page-header h2 { font-size: 1.3rem; font-weight: 700; margin-bottom: 2px; }
.page-header small { opacity: .85; font-size: .85rem; }

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px,1fr));
    gap: 14px;
    margin-bottom: 20px;
}
.stat-card {
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0,0,0,.08);
    text-align: center;
    padding: 16px 10px;
    border-top: 4px solid transparent;
}
.stat-card.blue   { border-color: #1a73e8; }
.stat-card.green  { border-color: #34a853; }
.stat-card.orange { border-color: #fbbc04; }
.stat-card.purple { border-color: #6f42c1; }
.stat-card.red    { border-color: #ea4335; }
.stat-card .num   { font-size: 1.6rem; font-weight: 700; }
.stat-card .lbl   { color: #888; font-size: .82rem; margin-top: 4px; }
.stat-card.blue   .num { color: #1a73e8; }
.stat-card.green  .num { color: #34a853; }
.stat-card.orange .num { color: #f57c00; }
.stat-card.purple .num { color: #6f42c1; }
.stat-card.red    .num { color: #ea4335; }

.card {
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0,0,0,.08);
    margin-bottom: 20px;
    overflow: hidden;
}
.card-header {
    padding: 14px 20px;
    border-bottom: 1px solid #eee;
    font-weight: 700;
    font-size: .95rem;
    background: #fafafa;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 10px 14px; border-bottom: 1px solid #eee; text-align: right; white-space: nowrap; }
th { background: #f8f9fa; font-weight: 600; color: #555; font-size: .85rem; }
tr:last-child td { border-bottom: none; }
tbody tr:hover td { background: #fafbff; }

.total-row td { font-weight: 700; background: #f0f4ff; }

.badge-ok  { background: #e6f4ea; color: #1e7e34; padding: 2px 10px; border-radius: 12px; font-size: .78rem; font-weight: 700; }
.badge-low { background: #fff8e1; color: #f57c00; padding: 2px 10px; border-radius: 12px; font-size: .78rem; font-weight: 700; }
.badge-zero{ background: #fce8e6; color: #c62828; padding: 2px 10px; border-radius: 12px; font-size: .78rem; font-weight: 700; }

.btn {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 7px 16px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: .88rem;
    font-family: inherit;
    font-weight: 600;
    text-decoration: none;
    transition: opacity .15s;
}
.btn:hover { opacity: .88; }
.btn-outline { background: transparent; border: 1px solid #ccc; color: #555; }
.btn-sm { padding: 4px 10px; font-size: .8rem; }

.empty-state { text-align: center; padding: 50px 20px; color: #aaa; }
.empty-state .icon { font-size: 3rem; margin-bottom: 10px; }

/* فلتر البحث */
.search-bar {
    padding: 14px 20px;
    border-bottom: 1px solid #eee;
    background: #fafafa;
}
.search-bar input {
    width: 100%;
    max-width: 380px;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: .9rem;
    font-family: inherit;
}
.search-bar input:focus {
    outline: none;
    border-color: #1a73e8;
    box-shadow: 0 0 0 3px rgba(26,115,232,.1);
}

@media print {
    .no-print { display: none !important; }
    body { background: #fff; padding: 0; }
    .card { box-shadow: none; border: 1px solid #ddd; }
}
@media (max-width: 768px) {
    body { padding: 12px; }
    .stats-grid { grid-template-columns: repeat(2,1fr); }
    th, td { padding: 8px; font-size: .82rem; }
}
</style>
</head>
<body>

<a href="../dashboard.php" class="back-link no-print">&#8594; العودة للرئيسية</a>

<!-- Page Header -->
<div class="page-header no-print">
    <div>
        <h2>&#128218; تقرير مخزون الإصدارات</h2>
        <small>رصيد المخزن الحالي لكل إصدار — <?= date('d/m/Y H:i') ?></small>
    </div>
    <button class="btn btn-outline"
            style="background:rgba(255,255,255,.2);color:#fff;border-color:rgba(255,255,255,.4);"
            onclick="window.print()">
        &#128424; طباعة
    </button>
</div>

<!-- إحصائيات -->
<div class="stats-grid no-print">
    <div class="stat-card blue">
        <div class="num"><?= count($rows) ?></div>
        <div class="lbl">إجمالي الإصدارات</div>
    </div>
    <div class="stat-card green">
        <div class="num"><?= number_format($totalIn) ?></div>
        <div class="lbl">إجمالي الوارد</div>
    </div>
    <div class="stat-card orange">
        <div class="num"><?= number_format($totalOut) ?></div>
        <div class="lbl">إجمالي الصادر</div>
    </div>
    <div class="stat-card purple">
        <div class="num"><?= number_format($totalReturned) ?></div>
        <div class="lbl">إجمالي المرتجع</div>
    </div>
    <div class="stat-card <?= $totalBalance > 0 ? 'green' : 'red' ?>">
        <div class="num"><?= number_format($totalBalance) ?></div>
        <div class="lbl">الرصيد الكلي</div>
    </div>
    <div class="stat-card blue">
        <div class="num" style="font-size:1.1rem;"><?= number_format($totalValue, 3) ?></div>
        <div class="lbl">القيمة الإجمالية (ر.ع.)</div>
    </div>
</div>

<!-- جدول المخزون -->
<div class="card">
    <div class="card-header">
        تفاصيل المخزون
        <span style="font-weight:400;font-size:.85rem;color:#888;"><?= count($rows) ?> إصدار</span>
    </div>

    <!-- فلتر بحث -->
    <div class="search-bar no-print">
        <input type="text"
               id="searchInput"
               placeholder="&#128269; بحث باسم الإصدار..."
               oninput="filterTable()">
    </div>

    <div class="table-wrap">
        <table id="stockTable">
            <thead>
                <tr>
                    <th>#</th>
                    <th>الإصدار</th>
                    <th>سعر الغلاف</th>
                    <th>وارد (WHR)</th>
                    <th>صادر (DIS)</th>
                    <th>مرتجع (WRT)</th>
                    <th>الرصيد</th>
                    <th>القيمة (ر.ع.)</th>
                    <th>الحالة</th>
                </tr>
            </thead>
            <tbody>
            <?php if (empty($rows)): ?>
                <tr><td colspan="9">
                    <div class="empty-state">
                        <div class="icon">&#128218;</div>
                        <div>لا توجد بيانات مخزون</div>
                    </div>
                </td></tr>
            <?php else: ?>
                <?php foreach ($rows as $idx => $r):
                    $bal   = (int)$r['warehouse_balance'];
                    $value = $bal * (float)$r['cover_price'];
                    if ($bal <= 0)  { $badgeClass = 'badge-zero'; $badgeText = 'نفذ المخزون'; }
                    elseif ($bal < 10) { $badgeClass = 'badge-low';  $badgeText = 'مخزون منخفض'; }
                    else            { $badgeClass = 'badge-ok';   $badgeText = 'متوفر'; }
                ?>
                <tr>
                    <td><?= $idx + 1 ?></td>
                    <td><?= h($r['issue_label']) ?></td>
                    <td><?= number_format((float)$r['cover_price'], 3) ?> ر.ع.</td>
                    <td style="color:#34a853;font-weight:600;"><?= number_format((int)$r['qty_in']) ?></td>
                    <td style="color:#ea4335;font-weight:600;"><?= number_format((int)$r['qty_out']) ?></td>
                    <td style="color:#6f42c1;font-weight:600;"><?= number_format((int)$r['qty_returned']) ?></td>
                    <td style="font-weight:700;font-size:1rem;color:<?= $bal <= 0 ? '#ea4335' : ($bal < 10 ? '#f57c00' : '#333') ?>;">
                        <?= number_format($bal) ?>
                    </td>
                    <td style="color:#1a73e8;font-weight:600;"><?= number_format($value, 3) ?> ر.ع.</td>
                    <td><span class="<?= $badgeClass ?>"><?= $badgeText ?></span></td>
                </tr>
                <?php endforeach; ?>
                <tr class="total-row">
                    <td colspan="3" style="text-align:left;">الإجمالي</td>
                    <td style="color:#34a853;"><?= number_format($totalIn) ?></td>
                    <td style="color:#ea4335;"><?= number_format($totalOut) ?></td>
                    <td style="color:#6f42c1;"><?= number_format($totalReturned) ?></td>
                    <td><?= number_format($totalBalance) ?></td>
                    <td style="color:#1a73e8;"><?= number_format($totalValue, 3) ?> ر.ع.</td>
                    <td></td>
                </tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- تاريخ الطباعة — يظهر عند الطباعة فقط -->
<div style="display:none;" class="print-only"
     id="printFooter">
    <hr>
    <p style="text-align:center;color:#888;font-size:.82rem;">
        تم إنشاء هذا التقرير بتاريخ <?= date('d/m/Y H:i') ?> — MGZ نظام إدارة توزيع المجلات
    </p>
</div>

<script>
/* ── فلتر البحث ── */
function filterTable() {
    var input  = document.getElementById('searchInput').value.toLowerCase();
    var rows   = document.querySelectorAll('#stockTable tbody tr');
    rows.forEach(function(row) {
        var text = row.textContent.toLowerCase();
        row.style.display = text.includes(input) ? '' : 'none';
    });
}
</script>

<style>
@media print {
    #printFooter { display: block !important; }
}
</style>

</body>
</html>
