<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/app/auth.php';
require_once __DIR__ . '/app/helpers.php';
require_once __DIR__ . '/app/db.php';

$u    = require_login();
$role = $u['role'];

$ROLE_AR = [
    'ADMIN'       => 'مدير النظام',
    'WAREHOUSE'   => 'أمين المخزن',
    'DISTRIBUTOR' => 'موزع',
];

$pdo     = db();
$stats   = [];
$dbError = '';

try {
    if ($role === 'ADMIN') {
        $stats = $pdo->query("
            SELECT
                (SELECT COUNT(*) FROM invoices
                 WHERE status IN ('ISSUED','PARTIAL'))              AS open_invoices,
                (SELECT COALESCE(SUM(balance_due),0) FROM invoices
                 WHERE status IN ('ISSUED','PARTIAL'))              AS total_due,
                (SELECT COUNT(*) FROM outlet_settlements
                 WHERE status='SUBMITTED')                          AS pending_settlements,
                (SELECT COUNT(*) FROM warehouse_returns
                 WHERE status='SUBMITTED')                          AS pending_returns,
                (SELECT COUNT(*) FROM distributor_dispatches
                 WHERE status='SUBMITTED')                          AS pending_dispatches,
                (SELECT COUNT(*) FROM warehouse_receipts
                 WHERE status='SUBMITTED')                          AS pending_receipts
        ")->fetch();

    } elseif ($role === 'WAREHOUSE') {
        $stats = $pdo->query("
            SELECT
                (SELECT COUNT(*) FROM warehouse_receipts
                 WHERE status='SUBMITTED')                          AS pending_receipts,
                (SELECT COUNT(*) FROM distributor_dispatches
                 WHERE status='SUBMITTED')                          AS pending_dispatches,
                (SELECT COUNT(*) FROM warehouse_returns
                 WHERE status='SUBMITTED')                          AS pending_returns,
                0 AS open_invoices,
                0 AS total_due,
                0 AS pending_settlements
        ")->fetch();

    } elseif ($role === 'DISTRIBUTOR') {
        $distId = (int)($u['distributor_id'] ?? 0);
        $st = $pdo->prepare("
            SELECT
                (SELECT COUNT(*) FROM invoices
                 WHERE distributor_id=?
                   AND status IN ('ISSUED','PARTIAL'))              AS open_invoices,
                (SELECT COALESCE(SUM(balance_due),0) FROM invoices
                 WHERE distributor_id=?
                   AND status IN ('ISSUED','PARTIAL'))              AS total_due,
                (SELECT COUNT(*) FROM outlet_settlements
                 WHERE distributor_id=? AND status='DRAFT')         AS pending_settlements,
                0 AS pending_returns,
                0 AS pending_dispatches,
                0 AS pending_receipts
        ");
        $st->execute([$distId, $distId, $distId]);
        $stats = $st->fetch();
    }
} catch (Throwable $e) {
    $stats   = [];
    $dbError = $e->getMessage();
}
?>
<!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: #f0f2f5;
    direction: rtl;
    min-height: 100vh;
}
.topbar {
    background: linear-gradient(135deg, #1a73e8, #0d47a1);
    color: #fff;
    padding: 0 24px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: sticky;
    top: 0;
    z-index: 100;
    box-shadow: 0 2px 8px rgba(0,0,0,.15);
}
.topbar .brand { font-size: 1.2rem; font-weight: 700; }
.topbar .brand span {
    background: rgba(255,255,255,.2);
    padding: 2px 10px;
    border-radius: 6px;
    margin-right: 8px;
    font-size: .85rem;
}
.topbar .user-info { display: flex; align-items: center; gap: 14px; font-size: .9rem; }
.topbar .role-badge {
    background: rgba(255,255,255,.2);
    padding: 3px 12px;
    border-radius: 20px;
    font-size: .8rem;
}
.topbar .logout-btn {
    background: rgba(255,255,255,.15);
    border: 1px solid rgba(255,255,255,.3);
    color: #fff;
    padding: 5px 14px;
    border-radius: 6px;
    text-decoration: none;
    font-size: .85rem;
}
.topbar .logout-btn:hover { background: rgba(255,255,255,.25); }
.main { padding: 24px; max-width: 1200px; margin: auto; }
.welcome-banner {
    background: linear-gradient(135deg, #1a73e8, #6610f2);
    color: #fff;
    padding: 20px 28px;
    border-radius: 12px;
    margin-bottom: 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 12px;
}
.welcome-banner h2 { font-size: 1.3rem; font-weight: 700; margin-bottom: 4px; }
.welcome-banner p  { opacity: .85; font-size: .9rem; }
.welcome-banner .date-box {
    background: rgba(255,255,255,.15);
    padding: 8px 16px;
    border-radius: 8px;
    font-size: .88rem;
    text-align: center;
}
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(160px,1fr));
    gap: 14px;
    margin-bottom: 28px;
}
.stat-card {
    background: #fff;
    border-radius: 12px;
    padding: 18px 16px;
    box-shadow: 0 2px 8px rgba(0,0,0,.07);
    text-align: center;
    border-top: 4px solid transparent;
    transition: transform .2s;
}
.stat-card:hover { transform: translateY(-3px); }
.stat-card.blue   { border-color: #1a73e8; }
.stat-card.green  { border-color: #34a853; }
.stat-card.orange { border-color: #fbbc04; }
.stat-card.red    { border-color: #ea4335; }
.stat-card.purple { border-color: #6f42c1; }
.stat-card .num   { font-size: 1.9rem; font-weight: 700; line-height: 1; margin-bottom: 6px; }
.stat-card .lbl   { font-size: .8rem; color: #888; }
.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; }
.section-title {
    font-size: 1rem;
    font-weight: 700;
    color: #555;
    margin-bottom: 12px;
    margin-top: 8px;
    display: flex;
    align-items: center;
    gap: 8px;
}
.section-title::after { content:''; flex:1; height:1px; background:#e0e0e0; }
.menu-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(170px,1fr));
    gap: 12px;
    margin-bottom: 24px;
}
.menu-card {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 20px 14px;
    background: #fff;
    border-radius: 12px;
    border: 2px solid #eee;
    text-decoration: none;
    color: #444;
    font-size: .88rem;
    font-weight: 600;
    text-align: center;
    transition: all .2s;
    box-shadow: 0 1px 4px rgba(0,0,0,.05);
}
.menu-card:hover {
    border-color: #1a73e8;
    background: #e8f0fe;
    color: #1a73e8;
    transform: translateY(-2px);
}
.menu-card .icon { font-size: 1.8rem; line-height: 1; }
.menu-card .code {
    font-size: .72rem;
    background: #f1f3f4;
    color: #888;
    padding: 1px 8px;
    border-radius: 10px;
    font-weight: 400;
}
.menu-card:hover .code { background: #c5d9fb; color: #1a73e8; }
.alert-danger {
    background: #fce8e6;
    color: #c62828;
    border-right: 4px solid #ea4335;
    padding: 14px 18px;
    border-radius: 8px;
    margin-bottom: 20px;
    font-size: .9rem;
}
@media (max-width: 600px) {
    .main { padding: 14px; }
    .stats-grid { grid-template-columns: repeat(2,1fr); }
    .menu-grid  { grid-template-columns: repeat(2,1fr); }
    .welcome-banner { flex-direction: column; }
    .topbar .brand span { display: none; }
}
</style>
</head>
<body>

<div class="topbar">
    <div class="brand">
        &#128240; MGZ
        <span>نظام توزيع المجلات</span>
    </div>
    <div class="user-info">
        <span>&#128100; <?= h($u['name']) ?></span>
        <span class="role-badge"><?= $ROLE_AR[$role] ?? $role ?></span>
        <a href="logout.php" class="logout-btn">&#128275; خروج</a>
    </div>
</div>

<div class="main">

    <?php if ($dbError !== ''): ?>
    <div class="alert-danger">
        <strong>&#9888; خطأ في قاعدة البيانات:</strong><br>
        <?= htmlspecialchars($dbError) ?>
    </div>
    <?php endif; ?>

    <div class="welcome-banner">
        <div>
            <h2>أهلاً بك، <?= h($u['name']) ?> &#128075;</h2>
            <p><?= $ROLE_AR[$role] ?? $role ?> — نظام إدارة توزيع المجلات</p>
        </div>
        <div class="date-box">
            <div style="font-size:1.1rem;font-weight:700;"><?= date('d/m/Y') ?></div>
            <div style="opacity:.8;font-size:.82rem;"><?= date('l') ?></div>
        </div>
    </div>

    <?php if (!empty($stats)): ?>
    <div class="stats-grid">
        <?php if ((int)($stats['open_invoices'] ?? 0) > 0): ?>
        <div class="stat-card blue">
            <div class="num"><?= (int)$stats['open_invoices'] ?></div>
            <div class="lbl">فاتورة مفتوحة</div>
        </div>
        <?php endif; ?>
        <?php if ((float)($stats['total_due'] ?? 0) > 0): ?>
        <div class="stat-card red">
            <div class="num" style="font-size:1.2rem;">
                <?= number_format((float)$stats['total_due'], 3) ?>
            </div>
            <div class="lbl">إجمالي المستحق (ر.ع.)</div>
        </div>
        <?php endif; ?>
        <?php if ((int)($stats['pending_settlements'] ?? 0) > 0): ?>
        <div class="stat-card orange">
            <div class="num"><?= (int)$stats['pending_settlements'] ?></div>
            <div class="lbl">تسوية بانتظار الاعتماد</div>
        </div>
        <?php endif; ?>
        <?php if ((int)($stats['pending_returns'] ?? 0) > 0): ?>
        <div class="stat-card purple">
            <div class="num"><?= (int)$stats['pending_returns'] ?></div>
            <div class="lbl">مرتجع بانتظار الاعتماد</div>
        </div>
        <?php endif; ?>
        <?php if ((int)($stats['pending_dispatches'] ?? 0) > 0): ?>
        <div class="stat-card orange">
            <div class="num"><?= (int)$stats['pending_dispatches'] ?></div>
            <div class="lbl">صرف بانتظار الاعتماد</div>
        </div>
        <?php endif; ?>
        <?php if ((int)($stats['pending_receipts'] ?? 0) > 0): ?>
        <div class="stat-card green">
            <div class="num"><?= (int)$stats['pending_receipts'] ?></div>
            <div class="lbl">توريد بانتظار الاعتماد</div>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <?php if ($role === 'ADMIN'): ?>
    <div class="section-title">&#128218; البيانات الأساسية</div>
    <div class="menu-grid">
        <a href="modules/products.php" class="menu-card">
    <span class="icon">&#128240;</span>
    <span>المنتجات</span>
</a>

        
        
        
        <a href="modules/issues.php" class="menu-card">
            <span class="icon">&#128240;</span><span>إصدارات المجلات</span>
        </a>
        <a href="modules/outlets.php" class="menu-card">
            <span class="icon">&#127978;</span><span>منافذ البيع</span>
        
        </a>
        <a href="modules/distributors.php" class="menu-card">
            <span class="icon">&#128666;</span><span>الموزعون</span>
        </a>
    </div>

    <div class="section-title">&#128203; المستندات والحركات</div>
    <div class="menu-grid">
        <a href="modules/wh_receipts.php" class="menu-card">
            <span class="icon">&#128230;</span>
            <span>توريد للمخزن</span>
            <span class="code">WHR</span>
        </a>
        <a href="modules/dispatches.php" class="menu-card">
            <span class="icon">&#128666;</span>
            <span>صرف للموزعين</span>
            <span class="code">DIS</span>
        </a>
        <a href="modules/warehouse_returns.php" class="menu-card">
            <span class="icon">&#128257;</span>
            <span>مرتجع للمخزن</span>
            <span class="code">WRT</span>
        </a>
        <a href="modules/outlet_deliveries.php" class="menu-card">
            <span class="icon">&#128667;</span>
            <span>شحن للمنافذ</span>
            <span class="code">ODL</span>
        </a>
        <a href="modules/settlements.php" class="menu-card">
            <span class="icon">&#128203;</span>
            <span>تسويات الأمانة</span>
            <span class="code">OST</span>
        </a>
        <a href="modules/invoices.php" class="menu-card">
            <span class="icon">&#128196;</span>
            <span>الفواتير</span>
            <span class="code">INV</span>
        </a>
        <a href="modules/payments.php" class="menu-card">
            <span class="icon">&#128178;</span>
            <span>التحصيلات</span>
            <span class="code">PAY</span>
        </a>
    </div>

    <div class="section-title">&#128200; التقارير</div>
    <div class="menu-grid">
        <a href="modules/report_stock.php" class="menu-card">
            <span class="icon">&#128218;</span>
            <span>تقرير المخزون</span>
        </a>
        <a href="modules/report_outlet_statement.php" class="menu-card">
            <span class="icon">&#128196;</span>
            <span>كشف حساب منفذ</span>
        </a>
        <a href="modules/report_distributor_holdings.php" class="menu-card">
            <span class="icon">&#128666;</span>
            <span>عهدة الموزعين</span>
        </a>
        <a href="modules/report_distributor_commission.php" class="menu-card">
            <span class="icon">&#128200;</span>
            <span>عمولات الموزعين</span>
        </a>
    </div>

    <?php elseif ($role === 'WAREHOUSE'): ?>

    <div class="section-title">&#128218; عمليات المخزن</div>
    <div class="menu-grid">
        <a href="modules/issues.php" class="menu-card">
            <span class="icon">&#128240;</span>
            <span>الإصدارات</span>
        </a>
        <a href="modules/wh_receipts.php" class="menu-card">
            <span class="icon">&#128230;</span>
            <span>توريد للمخزن</span>
            <span class="code">WHR</span>
        </a>
        <a href="modules/dispatches.php" class="menu-card">
            <span class="icon">&#128666;</span>
            <span>صرف للموزعين</span>
            <span class="code">DIS</span>
        </a>
        <a href="modules/warehouse_returns.php" class="menu-card">
            <span class="icon">&#128257;</span>
            <span>استلام مرتجع</span>
            <span class="code">WRT</span>
        </a>
        <a href="modules/report_stock.php" class="menu-card">
            <span class="icon">&#128218;</span>
            <span>تقرير المخزون</span>
        </a>
    </div>

    <?php elseif ($role === 'DISTRIBUTOR'): ?>

    <div class="section-title">&#128666; عمليات التوزيع</div>
    <div class="menu-grid">
        <a href="modules/outlet_deliveries.php" class="menu-card">
            <span class="icon">&#128667;</span>
            <span>شحن للمنافذ</span>
            <span class="code">ODL</span>
        </a>
        <a href="modules/settlements.php" class="menu-card">
            <span class="icon">&#128203;</span>
            <span>تسوية مبيعات</span>
            <span class="code">OST</span>
        </a>
        <a href="modules/invoices.php" class="menu-card">
            <span class="icon">&#128196;</span>
            <span>فواتيري</span>
            <span class="code">INV</span>
        </a>
    </div>

    <?php endif; ?>

    <div style="text-align:center;color:#bbb;font-size:.8rem;margin-top:30px;padding-top:16px;border-top:1px solid #eee;">
        MGZ — نظام إدارة توزيع المجلات &copy; <?= date('Y') ?>
    </div>

</div>
</body>
</html>
