<?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();

$date_from      = trim($_GET['from']            ?? '');
$date_to        = trim($_GET['to']              ?? '');
$distributor_id = (int)($_GET['distributor_id'] ?? 0);

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

$COMM_AR   = ['PERCENT' => 'نسبة مئوية', 'FIXED' => 'مبلغ ثابت', 'PER_COPY' => 'لكل نسخة'];
$SOURCE_AR = ['DIRECT_SALE' => 'بيع مباشر', 'CONSIGNMENT_SETTLEMENT' => 'تسوية أمانة'];

$where  = "inv.status IN ('ISSUED','PARTIAL','PAID') AND inv.distributor_id IS NOT NULL";
$params = [];
if ($distributor_id > 0)   { $where .= ' AND inv.distributor_id = ?'; $params[] = $distributor_id; }
if ($date_from !== '')      { $where .= ' AND inv.issued_at >= ?';     $params[] = $date_from . ' 00:00:00'; }
if ($date_to   !== '')      { $where .= ' AND inv.issued_at <= ?';     $params[] = $date_to   . ' 23:59:59'; }

$st = $pdo->prepare("
    SELECT
        inv.id, inv.invoice_no, inv.issued_at,
        inv.total_amount, inv.total_paid, inv.balance_due,
        inv.currency, inv.source_type,
        d.id               AS distributor_id,
        d.name             AS distributor_name,
        d.commission_type,
        d.commission_value,
        o.name             AS outlet_name
    FROM invoices inv
    JOIN distributors d ON d.id = inv.distributor_id
    JOIN outlets      o ON o.id = inv.outlet_id
    WHERE $where
    ORDER BY inv.issued_at DESC, inv.id DESC
    LIMIT 2000
");
$st->execute($params);
$rows = $st->fetchAll();

function calc_commission_rep(array $r): float {
    $type  = $r['commission_type'];
    $val   = (float)$r['commission_value'];
    $total = (float)$r['total_amount'];
    if ($type === 'PERCENT')  return round($total * max(0.0, $val) / 100.0, 3);
    if ($type === 'FIXED')    return round(max(0.0, $val), 3);
    return 0.0;
}

/* تجميع حسب الموزع */
$agg = [];
foreach ($rows as $r) {
    $cid  = (int)$r['distributor_id'];
    $comm = calc_commission_rep($r);
    if (!isset($agg[$cid])) {
        $agg[$cid] = [
            'name'       => $r['distributor_name'],
            'comm_type'  => $r['commission_type'],
            'comm_value' => $r['commission_value'],
            'sales'      => 0.0,
            'commission' => 0.0,
            'count'      => 0,
        ];
    }
    $agg[$cid]['sales']      += (float)$r['total_amount'];
    $agg[$cid]['commission'] += $comm;
    $agg[$cid]['count']++;
}

$grandSales = array_sum(array_column($agg, 'sales'));
$grandComm  = array_sum(array_column($agg, 'commission'));
?>
<!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, #6f42c1, #9c27b0);
    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 1fr 1fr auto;
    gap: 14px;
    align-items: end;
}
.form-group label {
    display: block;
    font-weight: 600;
    color: #555;
    margin-bottom: 5px;
    font-size: .85rem;
}
input[type=date], select {
    width: 100%;
    padding: 8px 10px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: .9rem;
    font-family: inherit;
    background: #fff;
}
input:focus, select:focus {
    outline: none;
    border-color: #6f42c1;
    box-shadow: 0 0 0 3px rgba(111,66,193,.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.purple { border-color: #6f42c1; }
.stat-card.orange { border-color: #f57c00; }
.stat-card .num   { font-size: 1.4rem; 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.purple .num { color: #6f42c1; }
.stat-card.orange .num { color: #f57c00; }
.summary-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px,1fr));
    gap: 12px;
    margin-bottom: 20px;
}
.summary-card {
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0,0,0,.08);
    padding: 16px;
    border-right: 4px solid #6f42c1;
}
.summary-card .s-name  { font-weight: 700; font-size: .95rem; margin-bottom: 8px; color: #333; }
.summary-card .s-sales { font-size: .85rem; color: #888; margin-bottom: 4px; }
.summary-card .s-comm  { font-size: 1.3rem; font-weight: 700; color: #6f42c1; }
.summary-card .s-type  {
    font-size: .75rem;
    background: #f3e8ff;
    color: #6f42c1;
    padding: 2px 8px;
    border-radius: 10px;
    display: inline-block;
    margin-top: 4px;
}
.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: #fdf8ff; }
.total-row td { font-weight: 700; background: #f3e8ff; }
.dist-group-row td {
    background: #ede7f6;
    font-weight: 700;
    color: #4a148c;
    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-primary { background: #6f42c1; color: #fff; }
.btn-outline { background: transparent; border: 1px solid #ccc; color: #555; }
.btn-sm { padding: 4px 10px; font-size: .8rem; }
.money        { font-weight: 700; color: #1a73e8; }
.money-green  { font-weight: 700; color: #34a853; }
.money-purple { font-weight: 700; color: #6f42c1; }
.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: #6f42c1;
    box-shadow: 0 0 0 3px rgba(111,66,193,.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; }
    .filter-grid { grid-template-columns: 1fr; }
    .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>&#128200; تقرير عمولات الموزعين</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="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>من تاريخ</label>
                    <input type="date" name="from" value="<?= h($date_from) ?>">
                </div>
                <div class="form-group">
                    <label>إلى تاريخ</label>
                    <input type="date" name="to" value="<?= h($date_to) ?>">
                </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($agg) ?></div>
        <div class="lbl">عدد الموزعين</div>
    </div>
    <div class="stat-card orange">
        <div class="num"><?= count($rows) ?></div>
        <div class="lbl">إجمالي الفواتير</div>
    </div>
    <div class="stat-card green">
        <div class="num" style="font-size:1.1rem;"><?= number_format($grandSales, 3) ?></div>
        <div class="lbl">إجمالي المبيعات (ر.ع.)</div>
    </div>
    <div class="stat-card purple">
        <div class="num" style="font-size:1.1rem;"><?= number_format($grandComm, 3) ?></div>
        <div class="lbl">إجمالي العمولات (ر.ع.)</div>
    </div>
</div>

<!-- بطاقات ملخص الموزعين -->
<?php if (!empty($agg)): ?>
<div class="summary-grid no-print">
    <?php foreach ($agg as $a): ?>
    <div class="summary-card">
        <div class="s-name">&#128666; <?= h($a['name']) ?></div>
        <div class="s-sales">المبيعات: <?= number_format($a['sales'], 3) ?> ر.ع. (<?= (int)$a['count'] ?> فاتورة)</div>
        <div class="s-comm"><?= number_format($a['commission'], 3) ?> ر.ع.</div>
        <span class="s-type"><?= $COMM_AR[$a['comm_type']] ?? h($a['comm_type']) ?> — <?= h($a['comm_value']) ?></span>
    </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_from ? ' | من: ' . h($date_from) : '' ?>
        <?= $date_to   ? ' إلى: '  . h($date_to)   : '' ?>
        — تاريخ الطباعة: <?= date('d/m/Y H:i') ?>
    </p>
</div>

<!-- ملخص حسب الموزع -->
<div class="card">
    <div class="card-header">
        &#128200; ملخص العمولات حسب الموزع
        <span style="font-weight:400;font-size:.85rem;color:#888;"><?= count($agg) ?> موزع</span>
    </div>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>الموزع</th>
                    <th>نوع العمولة</th>
                    <th>القيمة / النسبة</th>
                    <th>عدد الفواتير</th>
                    <th>إجمالي المبيعات</th>
                    <th>إجمالي العمولة</th>
                    <th>نسبة العمولة %</th>
                </tr>
            </thead>
            <tbody>
            <?php if (empty($agg)): ?>
                <tr><td colspan="8">
                    <div class="empty-state">
                        <div class="icon">&#128200;</div>
                        <div>لا توجد بيانات — عدّل معايير الفلتر</div>
                    </div>
                </td></tr>
            <?php else: ?>
                <?php $aggIdx = 0; foreach ($agg as $cid => $a): $aggIdx++; ?>
                <tr>
                    <td><?= $aggIdx ?></td>
                    <td><strong><?= h($a['name']) ?></strong></td>
                    <td><?= $COMM_AR[$a['comm_type']] ?? h($a['comm_type']) ?></td>
                    <td>
                        <?= h($a['comm_value']) ?>
                        <?= $a['comm_type'] === 'PERCENT' ? '%' : ' ر.ع.' ?>
                    </td>
                    <td style="text-align:center;"><?= (int)$a['count'] ?></td>
                    <td class="money"><?= number_format($a['sales'], 3) ?> ر.ع.</td>
                    <td class="money-purple"><?= number_format($a['commission'], 3) ?> ر.ع.</td>
                    <td>
                        <?php
                        $pct = $a['sales'] > 0 ? ($a['commission'] / $a['sales'] * 100) : 0;
                        echo number_format($pct, 2) . '%';
                        ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <tr class="total-row">
                    <td colspan="4" style="text-align:left;">الإجمالي الكلي</td>
                    <td style="text-align:center;"><?= count($rows) ?></td>
                    <td class="money"><?= number_format($grandSales, 3) ?> ر.ع.</td>
                    <td class="money-purple"><?= number_format($grandComm, 3) ?> ر.ع.</td>
                    <td>
                        <?= $grandSales > 0 ? number_format($grandComm / $grandSales * 100, 2) . '%' : '—' ?>
                    </td>
                </tr>
            <?php endif; ?>
            </tbody>
        </table>
    </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="detailTable">
            <thead>
                <tr>
                    <th>#</th>
                    <th>التاريخ</th>
                    <th>رقم الفاتورة</th>
                    <th>الموزع</th>
                    <th>المنفذ</th>
                    <th>المصدر</th>
                    <th>إجمالي الفاتورة</th>
                    <th>نوع العمولة</th>
                    <th>القيمة</th>
                    <th>العمولة المستحقة</th>
                    <th class="no-print">فتح</th>
                </tr>
            </thead>
            <tbody>
            <?php if (empty($rows)): ?>
                <tr><td colspan="11">
                    <div class="empty-state">
                        <div class="icon">&#128200;</div>
                        <div>لا توجد فواتير</div>
                    </div>
                </td></tr>
            <?php else: ?>
                <?php
                $prevDist = null;
                foreach ($rows as $idx => $r):
                    $comm = calc_commission_rep($r);
                    if ($r['distributor_id'] !== $prevDist):
                        $prevDist = $r['distributor_id'];
                        $distAgg  = $agg[(int)$r['distributor_id']] ?? null;
                ?>
                <tr class="dist-group-row">
                    <td colspan="11">
                        &#128666; <?= h($r['distributor_name']) ?>
                        <?php if ($distAgg): ?>
                        &nbsp;&nbsp;
                        <span style="font-weight:400;font-size:.82rem;color:#7b1fa2;">
                            إجمالي العمولة: <?= number_format($distAgg['commission'], 3) ?> ر.ع.
                            | المبيعات: <?= number_format($distAgg['sales'], 3) ?> ر.ع.
                        </span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endif; ?>
                <tr>
                    <td><?= $idx + 1 ?></td>
                    <td><?= h($r['issued_at']) ?></td>
                    <td><strong><?= h($r['invoice_no']) ?></strong></td>
                    <td><?= h($r['distributor_name']) ?></td>
                    <td><?= h($r['outlet_name']) ?></td>
                    <td><?= $SOURCE_AR[$r['source_type']] ?? h($r['source_type']) ?></td>
                    <td class="money"><?= number_format((float)$r['total_amount'], 3) ?> ر.ع.</td>
                    <td><?= $COMM_AR[$r['commission_type']] ?? h($r['commission_type']) ?></td>
                    <td>
                        <?= h($r['commission_value']) ?>
                        <?= $r['commission_type'] === 'PERCENT' ? '%' : ' ر.ع.' ?>
                    </td>
                    <td class="money-purple"><?= number_format($comm, 3) ?> ر.ع.</td>
                    <td class="no-print">
                        <a href="invoices.php?action=view&id=<?= (int)$r['id'] ?>"
                           class="btn btn-outline btn-sm">
                            &#128065; فتح
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
                <tr class="total-row">
                    <td colspan="6" style="text-align:left;">الإجمالي الكلي</td>
                    <td class="money"><?= number_format($grandSales, 3) ?> ر.ع.</td>
                    <td colspan="2"></td>
                    <td class="money-purple"><?= number_format($grandComm, 3) ?> ر.ع.</td>
                    <td class="no-print"></td>
                </tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
function filterTable() {
    var input = document.getElementById('searchInput').value.toLowerCase();
    var rows  = document.querySelectorAll('#detailTable 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>
