<?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();
$distributor_id = (int)($_GET['distributor_id'] ?? 0);

$distributors = $pdo->query("SELECT id, name FROM distributors WHERE active=1 ORDER BY name")->fetchAll();

$whereDist = '';
$params    = [];
if ($distributor_id > 0) { $whereDist = 'WHERE d.id = ?'; $params[] = $distributor_id; }

$st = $pdo->prepare("
    SELECT
        d.id   AS distributor_id,
        d.name AS distributor_name,
        i.id   AS issue_id,
        i.cover_price,
        CONCAT(p.name,' - ',LPAD(i.issue_month,2,'0'),'/',i.issue_year) AS issue_label,

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

        COALESCE((
            SELECT SUM(odi.qty_delivered)
            FROM outlet_delivery_items odi
            JOIN outlet_deliveries od ON od.id = odi.delivery_id
            WHERE od.status = 'APPROVED'
              AND od.distributor_id = d.id
              AND odi.issue_id = i.id
        ),0) AS qty_to_outlets,

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

        (
            COALESCE((
                SELECT SUM(ddi.qty)
                FROM distributor_dispatch_items ddi
                JOIN distributor_dispatches dd ON dd.id = ddi.dispatch_id
                WHERE dd.status = 'APPROVED'
                  AND dd.distributor_id = d.id
                  AND ddi.issue_id = i.id
            ),0)
            -
            COALESCE((
                SELECT SUM(odi.qty_delivered)
                FROM outlet_delivery_items odi
                JOIN outlet_deliveries od ON od.id = odi.delivery_id
                WHERE od.status = 'APPROVED'
                  AND od.distributor_id = d.id
                  AND odi.issue_id = i.id
            ),0)
            -
            COALESCE((
                SELECT SUM(wrti.qty)
                FROM warehouse_return_items wrti
                JOIN warehouse_returns wrt ON wrt.id = wrti.return_id
                WHERE wrt.status = 'APPROVED'
                  AND wrt.distributor_id = d.id
                  AND wrti.issue_id = i.id
            ),0)
        ) AS distributor_balance

    FROM distributors d
    CROSS JOIN issues i
    JOIN products p ON p.id = i.product_id
    $whereDist
    HAVING distributor_balance <> 0
        OR qty_from_warehouse  <> 0
        OR qty_to_outlets      <> 0
        OR qty_returned_to_warehouse <> 0
    ORDER BY d.name, i.issue_year DESC, i.issue_month DESC, p.name
");
$st->execute($params);
$rows = $st->fetchAll();

/* إجماليات */
$grandIn      = array_sum(array_column($rows, 'qty_from_warehouse'));
$grandOut     = array_sum(array_column($rows, 'qty_to_outlets'));
$grandBack    = array_sum(array_column($rows, 'qty_returned_to_warehouse'));
$grandBalance = array_sum(array_column($rows, 'distributor_balance'));
$grandValue   = array_sum(array_map(
    fn($r) => (int)$r['distributor_balance'] * (float)$r['cover_price'],
    $rows
));

/* تجميع حسب الموزع لبطاقات الملخص */
$byDist = [];
foreach ($rows as $r) {
    $did = $r['distributor_id'];
    if (!isset($byDist[$did])) {
        $byDist[$did] = ['name' => $r['distributor_name'], 'balance' => 0, 'value' => 0.0];
    }
    $byDist[$did]['balance'] += (int)$r['distributor_balance'];
    $byDist[$did]['value']   += (int)$r['distributor_balance'] * (float)$r['cover_price'];
}
?>
<!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>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
    font-family: 'Tajawal', 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, #e65100, #f57c00);
    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; }
.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;
}
.card-body { padding: 20px; }
.filter-grid {
    display: grid;
    grid-template-columns: 2fr auto;
    gap: 14px;
    align-items: end;
}
.form-group label {
    display: block;
    font-weight: 600;
    color: #555;
    margin-bottom: 5px;
    font-size: .85rem;
}
select, input[type=text] {
    width: 100%;
    padding: 8px 10px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: .9rem;
    font-family: inherit;
    background: #fff;
}
select:focus, input:focus {
    outline: none;
    border-color: #f57c00;
    box-shadow: 0 0 0 3px rgba(245,124,0,.1);
}
.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: #f57c00; }
.stat-card.red    { border-color: #ea4335; }
.stat-card.purple { border-color: #6f42c1; }
.stat-card .num   { font-size: 1.5rem; 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.red    .num { color: #ea4335; }
.stat-card.purple .num { color: #6f42c1; }

/* بطاقات ملخص الموزعين */
.dist-summary-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px,1fr));
    gap: 12px;
    margin-bottom: 20px;
}
.dist-card {
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0,0,0,.08);
    padding: 16px;
    border-right: 4px solid #f57c00;
}
.dist-card .dist-name { font-weight: 700; font-size: .95rem; margin-bottom: 8px; color: #333; }
.dist-card .dist-balance { font-size: 1.4rem; font-weight: 700; color: #f57c00; }
.dist-card .dist-value { font-size: .85rem; color: #888; margin-top: 2px; }

.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: #fffbf0; }
.total-row td { font-weight: 700; background: #fff3e0; }
.dist-group-row td {
    background: #fff8e1;
    font-weight: 700;
    color: #e65100;
    font-size: .88rem;
    padding: 6px 14px;
}
.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-primary { background: #f57c00; color: #fff; }
.btn-sm { padding: 4px 10px; font-size: .8rem; }
.money       { font-weight: 700; color: #1a73e8; }
.money-green { font-weight: 700; color: #34a853; }
.money-red   { font-weight: 700; color: #ea4335; }
.money-orange{ font-weight: 700; color: #f57c00; }
.badge-ok   { background: #e6f4ea; color: #1e7e34; padding: 2px 10px; border-radius: 12px; font-size: .78rem; font-weight: 700; }
.badge-warn { 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; }
.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: #f57c00;
    box-shadow: 0 0 0 3px rgba(245,124,0,.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; }
    .filter-grid { grid-template-columns: 1fr; }
}
</style>
</head>
<body>

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

<!-- Page Header -->
<div class="page-header no-print">
    <div>
        <h2>&#128666; عهدة الموزعين</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="card no-print">
    <div class="
    <div class="card-header">&#128269; فلتر التقرير</div>
    <div class="card-body">
        <form method="get">
            <div class="filter-grid">
                <div class="form-group">
                    <label>الموزع</label>
                    <select name="distributor_id">
                        <option value="0">— جميع الموزعين —</option>
                        <?php foreach ($distributors as $d): ?>
                        <option value="<?= (int)$d['id'] ?>"
                            <?= $distributor_id === (int)$d['id'] ? 'selected' : '' ?>>
                            <?= h($d['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>&nbsp;</label>
                    <button type="submit" class="btn btn-primary" style="width:100%;">
                        &#128269; عرض
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- إحصائيات -->
<div class="stats-grid no-print">
    <div class="stat-card blue">
        <div class="num"><?= count($byDist) ?></div>
        <div class="lbl">عدد الموزعين</div>
    </div>
    <div class="stat-card orange">
        <div class="num"><?= number_format($grandIn) ?></div>
        <div class="lbl">إجمالي الوارد (DIS)</div>
    </div>
    <div class="stat-card green">
        <div class="num"><?= number_format($grandOut) ?></div>
        <div class="lbl">إجمالي الموزّع (ODL)</div>
    </div>
    <div class="stat-card purple">
        <div class="num"><?= number_format($grandBack) ?></div>
        <div class="lbl">إجمالي المرتجع (WRT)</div>
    </div>
    <div class="stat-card <?= $grandBalance > 0 ? 'orange' : 'green' ?>">
        <div class="num"><?= number_format($grandBalance) ?></div>
        <div class="lbl">إجمالي العهدة</div>
    </div>
    <div class="stat-card blue">
        <div class="num" style="font-size:1.1rem;"><?= omr($grandValue) ?></div>
        <div class="lbl">القيمة الإجمالية (ر.ع.)</div>
    </div>
</div>

<!-- بطاقات ملخص الموزعين -->
<?php if (!empty($byDist)): ?>
<div class="dist-summary-grid no-print">
    <?php foreach ($byDist as $did => $ds): ?>
    <div class="dist-card">
        <div class="dist-name">&#128666; <?= h($ds['name']) ?></div>
        <div class="dist-balance"><?= number_format($ds['balance']) ?> نسخة</div>
        <div class="dist-value"><?= omr($ds['value']) ?></div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- عنوان الطباعة -->
<div style="display:none;" id="printHeader">
    <h2 style="text-align:center;margin-bottom:4px;">تقرير عهدة الموزعين</h2>
    <p style="text-align:center;color:#888;font-size:.85rem;margin-bottom:16px;">
        <?= $distributor_id > 0
            ? h(array_column($distributors,'name','id')[$distributor_id] ?? '')
            : 'جميع الموزعين' ?>
        — تاريخ الطباعة: <?= date('d/m/Y H:i') ?>
    </p>
</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="holdingsTable">
            <thead>
                <tr>
                    <th>#</th>
                    <th>الموزع</th>
                    <th>الإصدار</th>
                    <th>سعر الغلاف</th>
                    <th>وارد (DIS)</th>
                    <th>صادر (ODL)</th>
                    <th>مرتجع (WRT)</th>
                    <th>الرصيد</th>
                    <th>القيمة (ر.ع.)</th>
                    <th>الحالة</th>
                </tr>
            </thead>
            <tbody>
            <?php if (empty($rows)): ?>
                <tr><td colspan="10">
                    <div class="empty-state">
                        <div class="icon">&#128666;</div>
                        <div>لا توجد بيانات عهدة</div>
                    </div>
                </td></tr>
            <?php else: ?>
                <?php
                $prevDist = null;
                $distIdx  = 0;
                foreach ($rows as $idx => $r):
                    $bal   = (int)$r['distributor_balance'];
                    $value = $bal * (float)$r['cover_price'];
                    if ($bal <= 0)       { $bc = 'badge-zero'; $bt = 'صفر'; }
                    elseif ($bal < 5)    { $bc = 'badge-warn'; $bt = 'منخفض'; }
                    else                 { $bc = 'badge-ok';   $bt = 'بعهدته'; }

                    /* فاصل الموزع */
                    if ($r['distributor_id'] !== $prevDist):
                        $prevDist = $r['distributor_id'];
                        $distIdx++;
                ?>
                <tr class="dist-group-row">
                    <td colspan="10">
                        &#128666; <?= h($r['distributor_name']) ?>
                        &nbsp;&nbsp;
                        <span style="font-weight:400;font-size:.82rem;color:#888;">
                            إجمالي العهدة:
                            <?= number_format($byDist[$r['distributor_id']]['balance']) ?> نسخة |
                            <?= omr($byDist[$r['distributor_id']]['value']) ?>
                        </span>
                    </td>
                </tr>
                <?php endif; ?>
                <tr>
                    <td><?= $idx + 1 ?></td>
                    <td><?= h($r['distributor_name']) ?></td>
                    <td><?= h($r['issue_label']) ?></td>
                    <td><?= omr((float)$r['cover_price']) ?></td>
                    <td style="color:#34a853;font-weight:600;"><?= number_format((int)$r['qty_from_warehouse']) ?></td>
                    <td style="color:#1a73e8;font-weight:600;"><?= number_format((int)$r['qty_to_outlets']) ?></td>
                    <td style="color:#6f42c1;font-weight:600;"><?= number_format((int)$r['qty_returned_to_warehouse']) ?></td>
                    <td class="money-orange" style="font-size:1rem;"><?= number_format($bal) ?></td>
                    <td class="money"><?= omr($value) ?></td>
                    <td><span class="<?= $bc ?>"><?= $bt ?></span></td>
                </tr>
                <?php endforeach; ?>
                <tr class="total-row">
                    <td colspan="4" style="text-align:left;">الإجمالي الكلي</td>
                    <td style="color:#34a853;"><?= number_format($grandIn) ?></td>
                    <td style="color:#1a73e8;"><?= number_format($grandOut) ?></td>
                    <td style="color:#6f42c1;"><?= number_format($grandBack) ?></td>
                    <td class="money-orange"><?= number_format($grandBalance) ?></td>
                    <td class="money"><?= omr($grandValue) ?></td>
                    <td></td>
                </tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
function filterTable() {
    var input = document.getElementById('searchInput').value.toLowerCase();
    var rows  = document.querySelectorAll('#holdingsTable tbody tr:not(.dist-group-row):not(.total-row)');
    rows.forEach(function(row) {
        row.style.display = row.textContent.toLowerCase().includes(input) ? '' : 'none';
    });
}
</script>

<style>
@media print {
    #printHeader { display: block !important; }
    .no-print    { display: none !important; }
}
</style>

</body>
</html>
