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

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

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

$STATUS_AR = [
    'ISSUED'  => 'صدرت',
    'PARTIAL' => 'مدفوعة جزئياً',
    'PAID'    => 'مدفوعة',
];
$STATUS_CS = [
    'ISSUED'  => 'badge-issued',
    'PARTIAL' => 'badge-partial',
    'PAID'    => 'badge-paid',
];
$SOURCE_AR = [
    'DIRECT_SALE'            => 'بيع مباشر',
    'CONSIGNMENT_SETTLEMENT' => 'تسوية أمانة',
];

$where  = '1=1';
$params = [];
if ($outlet_id > 0)   { $where .= ' AND inv.outlet_id = ?';    $params[] = $outlet_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.source_type, inv.status,
           inv.total_amount, inv.total_paid, inv.balance_due, inv.currency,
           o.name AS outlet_name
    FROM invoices inv
    JOIN outlets o ON o.id = inv.outlet_id
    WHERE $where
    ORDER BY inv.issued_at DESC, inv.id DESC
    LIMIT 500
");
$st->execute($params);
$rows = $st->fetchAll();

$sumTotal = 0.0; $sumPaid = 0.0; $sumBal = 0.0;
foreach ($rows as $r) {
    $sumTotal += (float)$r['total_amount'];
    $sumPaid  += (float)$r['total_paid'];
    $sumBal   += (float)$r['balance_due'];
}
?>
<!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, #0d6efd, #6610f2);
    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;
    transition: border-color .2s;
}
input:focus, select:focus {
    outline: none;
    border-color: #0d6efd;
    box-shadow: 0 0 0 3px rgba(13,110,253,.1);
}
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(160px,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.red    { border-color: #ea4335; }
.stat-card.orange { border-color: #fbbc04; }
.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.red    .num { color: #ea4335; }
.stat-card.orange .num { color: #f57c00; }
.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 {
    display: inline-block;
    padding: 3px 12px;
    border-radius: 20px;
    font-size: .78rem;
    font-weight: 700;
}
.badge-issued  { background: #e8f0fe; color: #1a73e8; }
.badge-partial { background: #fff8e1; color: #f57c00; }
.badge-paid    { background: #e6f4ea; color: #1e7e34; }
.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;
    white-space: nowrap;
}
.btn:hover { opacity: .88; }
.btn-primary { background: #0d6efd; 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-red   { font-weight: 700; color: #ea4335; }
.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: #0d6efd;
    box-shadow: 0 0 0 3px rgba(13,110,253,.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>&#128196; كشف حساب منفذ</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="outlet_id">
                        <option value="0">— جميع المنافذ —</option>
                        <?php foreach ($outlets as $o): ?>
                        <option value="<?= (int)$o['id'] ?>"
                            <?= $outlet_id === (int)$o['id'] ? 'selected' : '' ?>>
                            <?= h($o['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($rows) ?></div>
        <div class="lbl">إجمالي الفواتير</div>
    </div>
    <div class="stat-card blue">
        <div class="num" style="font-size:1.1rem;"><?= number_format($sumTotal, 3) ?></div>
        <div class="lbl">إجمالي الفواتير (ر.ع.)</div>
    </div>
    <div class="stat-card green">
        <div class="num" style="font-size:1.1rem;"><?= number_format($sumPaid, 3) ?></div>
        <div class="lbl">إجمالي المحصّل (ر.ع.)</div>
    </div>
    <div class="stat-card <?= $sumBal > 0 ? 'red' : 'green' ?>">
        <div class="num" style="font-size:1.1rem;"><?= number_format($sumBal, 3) ?></div>
        <div class="lbl">إجمالي المتبقي (ر.ع.)</div>
    </div>
    <div class="stat-card orange">
        <div class="num">
            <?= count(array_filter($rows, fn($r) => $r['status'] === 'ISSUED')) ?>
        </div>
        <div class="lbl">فاتورة غير مسددة</div>
    </div>
</div>

<!-- عنوان الطباعة -->
<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;">
        <?= $outlet_id > 0 ? h(array_column($outlets,'name','id')[$outlet_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">
        نتائج التقرير
        <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="reportTable">
            <thead>
                <tr>
                    <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="10">
                    <div class="empty-state">
                        <div class="icon">&#128196;</div>
                        <div>لا توجد نتائج — عدّل معايير الفلتر</div>
                    </div>
                </td></tr>
            <?php else: ?>
                <?php foreach ($rows as $idx => $r): ?>
                <tr>
                    <td><?= $idx + 1 ?></td>
                    <td><?= h($r['issued_at']) ?></td>
                    <td><strong><?= h($r['invoice_no']) ?></strong></td>
                    <td><?= h($r['outlet_name']) ?></td>
                    <td><?= $SOURCE_AR[$r['source_type']] ?? h($r['source_type']) ?></td>
                    <td>
                        <span class="badge <?= $STATUS_CS[$r['status']] ?? 'badge-issued' ?>">
                            <?= $STATUS_AR[$r['status']] ?? h($r['status']) ?>
                        </span>
                    </td>
                    <td class="money"><?= number_format((float)$r['total_amount'], 3) ?> ر.ع.</td>
                    <td class="money-green"><?= number_format((float)$r['total_paid'], 3) ?> ر.ع.</td>
                    <td class="<?= (float)$r['balance_due'] > 0 ? 'money-red' : 'money-green' ?>">
                        <?= number_format((float)$r['balance_due'], 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($sumTotal, 3) ?> ر.ع.</td>
                    <td class="money-green"><?= number_format($sumPaid, 3) ?> ر.ع.</td>
                    <td class="<?= $sumBal > 0 ? 'money-red' : 'money-green' ?>">
                        <?= number_format($sumBal, 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('#reportTable tbody tr');
    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>
