<?php
// ========================================
// داشبورد هوشمند پنل مدیریت
// پروژه فروشگاه کیف‌لند - نسخه اصلاح‌شده
// ========================================

require_once '../config/database.php';
require_once '../config/settings.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

Auth::requireAdmin();
Auth::trackVisit('admin_dashboard');

$db = Database::getInstance()->getConnection();

// ========================================
// آمار واقعی از دیتابیس
// ========================================

// کاربران فعال
$stats['users'] = $db->query("SELECT COUNT(*) FROM users WHERE is_active = 1 AND role = 'user'")->fetchColumn();

// درآمد کل
$stats['revenue'] = $db->query("SELECT COALESCE(SUM(final_amount), 0) FROM orders WHERE status != 'cancelled'")->fetchColumn();

// سفارشات جدید (pending/processing)
$stats['new_orders'] = $db->query("SELECT COUNT(*) FROM orders WHERE status IN ('pending', 'processing')")->fetchColumn();

// رضایت مشتریان
$stats['satisfaction'] = $db->query("SELECT COALESCE(AVG(rating), 0) FROM reviews WHERE is_approved = 1")->fetchColumn();

// -------- فروش امروز / هفته / ماه --------
$today      = date('Y-m-d');
$week_start = date('Y-m-d', strtotime('monday this week'));
$month_start = date('Y-m-01');

$stmt = $db->prepare("SELECT COALESCE(SUM(final_amount),0) FROM orders WHERE status != 'cancelled' AND DATE(created_at) = ?");
$stmt->execute([$today]);
$stats['today_revenue'] = $stmt->fetchColumn();

$stmt = $db->prepare("SELECT COALESCE(SUM(final_amount),0) FROM orders WHERE status != 'cancelled' AND created_at >= ?");
$stmt->execute([$week_start . ' 00:00:00']);
$stats['week_revenue'] = $stmt->fetchColumn();

$stmt = $db->prepare("SELECT COALESCE(SUM(final_amount),0) FROM orders WHERE status != 'cancelled' AND created_at >= ?");
$stmt->execute([$month_start . ' 00:00:00']);
$stats['month_revenue'] = $stmt->fetchColumn();

// سفارشات امروز
$stmt = $db->prepare("SELECT COUNT(*) FROM orders WHERE DATE(created_at) = ?");
$stmt->execute([$today]);
$stats['today_orders'] = $stmt->fetchColumn();

// -------- هشدارها --------
$alerts = [];

// محصولات در آستانه اتمام موجودی (موجودی < 5)
$low_stock = $db->query("SELECT COUNT(*) FROM products WHERE stock < 5 AND stock > 0 AND is_active = 1")->fetchColumn();
if ($low_stock > 0) {
    $alerts[] = ['type' => 'warning', 'icon' => 'fa-exclamation-triangle', 'msg' => "$low_stock محصول در آستانه اتمام موجودی"];
}

// محصولات ناموجود
$out_stock = $db->query("SELECT COUNT(*) FROM products WHERE stock = 0 AND is_active = 1")->fetchColumn();
if ($out_stock > 0) {
    $alerts[] = ['type' => 'danger', 'icon' => 'fa-times-circle', 'msg' => "$out_stock محصول ناموجود است"];
}

// پیام‌های خوانده‌نشده
$unread_msgs = $db->query("SELECT COUNT(*) FROM messages WHERE status = 'unread'")->fetchColumn();
if ($unread_msgs > 0) {
    $alerts[] = ['type' => 'info', 'icon' => 'fa-envelope', 'msg' => "$unread_msgs پیام خوانده‌نشده دارید"];
}

// نظرات در انتظار تایید
$pending_reviews = $db->query("SELECT COUNT(*) FROM reviews WHERE status = 'pending'")->fetchColumn();
if ($pending_reviews > 0) {
    $alerts[] = ['type' => 'info', 'icon' => 'fa-star', 'msg' => "$pending_reviews نظر در انتظار تایید"];
}

// -------- نمودار فروش ۳۰ روز اخیر --------
$stmt = $db->query("SELECT DATE(created_at) as date, COALESCE(SUM(final_amount),0) as revenue, COUNT(*) as orders
    FROM orders WHERE status != 'cancelled' AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    GROUP BY DATE(created_at) ORDER BY date ASC");
$chart_raw = $stmt->fetchAll();

$chart_labels = [];
$chart_revenue = [];
$chart_orders = [];
foreach ($chart_raw as $row) {
    $chart_labels[] = date('m/d', strtotime($row['date']));
    $chart_revenue[] = (int)$row['revenue'];
    $chart_orders[] = (int)$row['orders'];
}

// -------- سفارشات اخیر --------
$stmt = $db->query("SELECT o.*, u.full_name as customer_name, u.email as customer_email
    FROM orders o LEFT JOIN users u ON o.user_id = u.id
    ORDER BY o.created_at DESC LIMIT 7");
$recentOrders = $stmt->fetchAll();

// -------- محصولات پرفروش --------
$stmt = $db->query("SELECT * FROM products WHERE is_active = 1 ORDER BY sales_count DESC LIMIT 5");
$topProducts = $stmt->fetchAll();

// -------- محصولات با موجودی بحرانی --------
$stmt = $db->query("SELECT id, name, stock FROM products WHERE stock < 10 AND is_active = 1 ORDER BY stock ASC LIMIT 5");
$criticalStock = $stmt->fetchAll();

// -------- اعلان موجودی بحرانی به تلگرام --------
if (!empty($criticalStock)) {
    try {
        require_once '../config/telegram.php';
        $tg = new TelegramBot();
        if ($tg->isConfigured()) {
            foreach ($criticalStock as $product) {
                if ($product['stock'] <= 3) $tg->sendLowStockAlert($product['name'], $product['stock']);
            }
        }
    } catch (Exception $e) { error_log("Telegram low stock error: " . $e->getMessage()); }
}

// -------- فعالیت‌های اخیر --------
$stmt = $db->query("SELECT al.*, u.username FROM activity_logs al LEFT JOIN users u ON al.user_id = u.id ORDER BY al.created_at DESC LIMIT 8");
$recentActivities = $stmt->fetchAll();

// -------- مشتریان برتر --------
$stmt = $db->query("SELECT u.full_name, u.email, COUNT(o.id) as order_count, SUM(o.final_amount) as total_spent
    FROM users u JOIN orders o ON u.id = o.user_id
    GROUP BY u.id ORDER BY total_spent DESC LIMIT 4");
$topCustomers = $stmt->fetchAll();

$currentAdmin = Auth::currentUser();

function getOrderStatusClass($status) {
    switch ($status) {
        case 'delivered': case 'paid': return 'delivered';
        case 'pending': return 'pending';
        case 'processing': return 'processing';
        case 'shipped': return 'shipped';
        case 'cancelled': case 'refunded': return 'cancelled';
        default: return 'pending';
    }
}

$pageTitle = 'داشبورد مدیریت | کیف‌لند';
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $pageTitle ?></title>
    <link href="https://cdn.jsdelivr.net/gh/rastikerdar/vazirmatn@v33.003/Vazirmatn-font-face.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
    <style>
    /* ========================================
       Dashboard Extra Styles
       ======================================== */

    /* کارت‌های آمار بالا */
    .stats-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin-bottom: 24px; }
    .stat-card { background: var(--glass-bg); backdrop-filter: blur(20px); border: 1px solid var(--glass-border); border-radius: var(--radius); padding: 20px; display: flex; align-items: center; gap: 16px; transition: all var(--transition-fast); }
    .stat-card:hover { transform: translateY(-3px); box-shadow: var(--glass-shadow); }
    .stat-icon { width: 52px; height: 52px; border-radius: var(--radius-sm); display: flex; align-items: center; justify-content: center; font-size: 20px; flex-shrink: 0; }
    .stat-icon.blue { background: rgba(0,122,255,0.12); color: var(--primary); }
    .stat-icon.green { background: rgba(52,199,89,0.12); color: var(--success); }
    .stat-icon.orange { background: rgba(255,159,10,0.12); color: var(--warning); }
    .stat-icon.purple { background: rgba(175,82,222,0.12); color: #af52de; }
    .stat-icon.red { background: rgba(255,59,48,0.12); color: var(--danger); }
    .stat-icon.teal { background: rgba(90,200,250,0.12); color: #5ac8fa; }
    .stat-info h3 { font-size: 22px; font-weight: 700; margin: 0 0 2px 0; }
    .stat-info p { font-size: 12px; color: var(--text-secondary); margin: 0 0 4px 0; }
    .stat-change { font-size: 11px; font-weight: 600; }
    .stat-change.positive { color: var(--success); }
    .stat-change.negative { color: var(--danger); }

    /* ردیف آمار زمانی */
    .time-stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; margin-bottom: 24px; }
    .time-stat-card { background: var(--glass-bg); border: 1px solid var(--glass-border); border-radius: var(--radius); padding: 20px; text-align: center; }
    .time-stat-card .label { font-size: 12px; color: var(--text-secondary); margin-bottom: 8px; }
    .time-stat-card .value { font-size: 20px; font-weight: 700; color: var(--primary); }
    .time-stat-card .sub { font-size: 11px; color: var(--text-muted); margin-top: 4px; }

    /* هشدارها */
    .alerts-section { margin-bottom: 24px; display: flex; flex-direction: column; gap: 8px; }
    .alert-item { display: flex; align-items: center; gap: 10px; padding: 12px 16px; border-radius: var(--radius-sm); font-size: 13px; font-weight: 500; }
    .alert-item.warning { background: rgba(255,159,10,0.1); border: 1px solid rgba(255,159,10,0.3); color: #b8690a; }
    .alert-item.danger { background: rgba(255,59,48,0.1); border: 1px solid rgba(255,59,48,0.3); color: #c0392b; }
    .alert-item.info { background: rgba(0,122,255,0.08); border: 1px solid rgba(0,122,255,0.2); color: #0066cc; }

    /* گرید محتوا */
    .content-grid { display: grid; grid-template-columns: 2fr 1fr; gap: 20px; }
    .glass-card { background: var(--glass-bg); backdrop-filter: blur(20px); border: 1px solid var(--glass-border); border-radius: var(--radius); padding: 20px; }
    .card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
    .card-header h2 { font-size: 16px; font-weight: 700; margin: 0; }

    /* نمودار */
    .chart-container { height: 220px; position: relative; }

    /* جدول سفارشات */
    .data-table { width: 100%; border-collapse: collapse; }
    .data-table thead th { text-align: right; padding: 10px 12px; font-size: 11px; font-weight: 600; color: var(--text-secondary); border-bottom: 1px solid var(--glass-border); }
    .data-table tbody td { padding: 12px; font-size: 13px; border-bottom: 0.5px solid rgba(255,255,255,0.1); vertical-align: middle; }
    .data-table tbody tr:hover { background: rgba(255,255,255,0.15); }

    /* وضعیت سفارش */
    .status { display: inline-flex; align-items: center; gap: 4px; padding: 3px 9px; border-radius: 20px; font-size: 11px; font-weight: 600; }
    .status.pending { background: #fff3cd; color: #856404; }
    .status.processing { background: #cce5ff; color: #004085; }
    .status.shipped { background: #e2e3e5; color: #383d41; }
    .status.delivered { background: #d4edda; color: #155724; }
    .status.cancelled { background: #f8d7da; color: #721c24; }

    /* محصولات */
    .products-list { display: flex; flex-direction: column; gap: 12px; }
    .product-item { display: flex; align-items: center; gap: 12px; padding: 10px; border-radius: var(--radius-sm); background: rgba(255,255,255,0.1); }
    .product-item img { width: 44px; height: 44px; border-radius: 8px; object-fit: cover; background: #eee; }
    .product-info { flex: 1; min-width: 0; }
    .product-info h4 { font-size: 13px; font-weight: 600; margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .product-info p { font-size: 11px; color: var(--text-secondary); margin: 2px 0 0; }
    .product-price { font-size: 12px; font-weight: 700; color: var(--primary); white-space: nowrap; }

    /* موجودی بحرانی */
    .stock-item { display: flex; align-items: center; gap: 10px; padding: 8px 0; border-bottom: 0.5px solid rgba(255,255,255,0.1); }
    .stock-item:last-child { border-bottom: none; }
    .stock-bar { flex: 1; height: 6px; background: rgba(0,0,0,0.08); border-radius: 4px; overflow: hidden; }
    .stock-bar-fill { height: 100%; border-radius: 4px; }
    .stock-bar-fill.critical { background: var(--danger); }
    .stock-bar-fill.low { background: var(--warning); }

    /* فعالیت‌ها */
    .activities-list { display: flex; flex-direction: column; gap: 10px; }
    .activity-item { display: flex; align-items: flex-start; gap: 10px; padding: 8px 0; border-bottom: 0.5px solid rgba(255,255,255,0.1); }
    .activity-item:last-child { border-bottom: none; }
    .activity-icon { width: 34px; height: 34px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 12px; flex-shrink: 0; }
    .activity-icon.blue { background: rgba(0,122,255,0.1); color: var(--primary); }
    .activity-icon.green { background: rgba(52,199,89,0.1); color: var(--success); }
    .activity-icon.orange { background: rgba(255,159,10,0.1); color: var(--warning); }
    .activity-info h4 { font-size: 12px; font-weight: 600; margin: 0 0 2px; }
    .activity-info p { font-size: 11px; color: var(--text-muted); margin: 0; }

    /* مشتریان */
    .customers-list { display: flex; flex-direction: column; gap: 10px; }
    .customer-item { display: flex; align-items: center; gap: 10px; padding: 8px; border-radius: var(--radius-sm); background: rgba(255,255,255,0.08); }
    .customer-item img { width: 38px; height: 38px; border-radius: 50%; }
    .customer-info { flex: 1; min-width: 0; }
    .customer-info h4 { font-size: 13px; font-weight: 600; margin: 0; }
    .customer-info p { font-size: 11px; color: var(--text-secondary); margin: 2px 0 0; }
    .customer-badge { font-size: 10px; color: #f39c12; font-weight: 700; }

    /* عملیات سریع */
    .quick-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
    .action-btn { display: flex; align-items: center; gap: 8px; padding: 12px; border-radius: var(--radius-sm); background: rgba(255,255,255,0.1); border: 1px solid var(--glass-border); color: var(--text-primary); text-decoration: none; font-size: 12px; font-weight: 600; transition: all var(--transition-fast); }
    .action-btn:hover { background: var(--primary); color: white; border-color: var(--primary); transform: translateY(-2px); }
    .action-btn i { font-size: 14px; }

    /* دکمه‌ها */
    .btn-secondary { font-size: 12px; color: var(--primary); text-decoration: none; font-weight: 600; }
    .btn-secondary:hover { text-decoration: underline; }
    .badge { background: var(--danger); color: white; border-radius: 10px; font-size: 10px; padding: 2px 6px; font-weight: 700; margin-right: 4px; }

    /* ریسپانسیو */
    @media (max-width: 1100px) {
        .stats-grid { grid-template-columns: repeat(2, 1fr); }
        .content-grid { grid-template-columns: 1fr; }
    }
    @media (max-width: 768px) {
        .stats-grid { grid-template-columns: 1fr 1fr; }
        .time-stats { grid-template-columns: 1fr; }
        .quick-actions { grid-template-columns: 1fr; }
    }
    @media (max-width: 480px) {
        .stats-grid { grid-template-columns: 1fr; }
    }
    </style>
</head>
<body>

<div class="overlay" id="overlay"></div>

<aside class="sidebar" id="sidebar">
    <div class="sidebar-header">
        <div class="logo">
            <i class="fas fa-shopping-bag"></i>
            <span>پنل مدیریت</span>
        </div>
        <button class="close-btn" id="closeSidebar"><i class="fas fa-times"></i></button>
    </div>
    <nav class="sidebar-nav">
        <ul>
            <li class="active">
                <a href="index.php"><i class="fas fa-th-large"></i> داشبورد</a>
            </li>
            <li class="dropdown">
                <a href="#" class="dropdown-toggle">
                    <i class="fas fa-users"></i> کاربران <i class="fas fa-chevron-down arrow"></i>
                </a>
                <ul class="dropdown-menu">
                    <li><a href="users.php"><i class="fas fa-list"></i> لیست کاربران</a></li>
                    <li><a href="user-add.php"><i class="fas fa-user-plus"></i> افزودن کاربر</a></li>
                </ul>
            </li>
            <li class="dropdown">
                <a href="#" class="dropdown-toggle">
                    <i class="fas fa-box-open"></i> محصولات <i class="fas fa-chevron-down arrow"></i>
                </a>
                <ul class="dropdown-menu">
                    <li><a href="products.php"><i class="fas fa-list"></i> لیست محصولات</a></li>
                    <li><a href="product-add.php"><i class="fas fa-plus"></i> افزودن محصول</a></li>
                    <li><a href="categories.php"><i class="fas fa-tags"></i> دسته‌بندی‌ها</a></li>
                </ul>
            </li>
            <li>
                <a href="orders.php">
                    <i class="fas fa-shopping-cart"></i> سفارشات
                    <span class="badge"><?= $stats['new_orders'] ?></span>
                </a>
            </li>
            <li>
                <a href="messages.php">
                    <i class="fas fa-envelope"></i> پیام‌ها
                    <?php if($unread_msgs > 0): ?><span class="badge"><?= $unread_msgs ?></span><?php endif; ?>
                </a>
            </li>
            <li>
                <a href="reviews.php"><i class="fas fa-star"></i> نظرات</a>
            </li>
            <li>
                <a href="wallet.php"><i class="fas fa-wallet"></i> کیف پول</a>
            </li>
            <li>
                <a href="analytics.php"><i class="fas fa-chart-bar"></i> آنالیتیکس</a>
            </li>
            <li>
                <a href="reports.php"><i class="fas fa-chart-line"></i> گزارشات</a>
            </li>
            <li>
                <a href="backup.php"><i class="fas fa-database"></i> بک‌آپ</a>
            </li>
            <li class="dropdown">
                <a href="#" class="dropdown-toggle">
                    <i class="fas fa-cog"></i> تنظیمات <i class="fas fa-chevron-down arrow"></i>
                </a>
                <ul class="dropdown-menu">
                    <li><a href="settings.php"><i class="fas fa-sliders-h"></i> عمومی</a></li>
                    <li><a href="settings.php#security"><i class="fas fa-shield-alt"></i> امنیت</a></li>
                    <li><a href="settings.php?tab=payment"><i class="fas fa-credit-card"></i> پرداخت</a></li>
                </ul>
            </li>
        </ul>
    </nav>
    <div class="sidebar-footer">
        <div class="user-profile">
            <img src="../uploads/logo/default-avatar.png" alt="User"
                 onerror="this.style.background='#667eea';this.style.display='flex';this.style.alignItems='center';this.style.justifyContent='center';">
            <div class="user-info">
                <h4><?= htmlspecialchars($currentAdmin['full_name'] ?? $currentAdmin['username']) ?></h4>
                <p><?= $currentAdmin['role'] === 'admin' ? 'مدیر ارشد' : 'اپراتور' ?></p>
            </div>
        </div>
        <a href="logout.php" class="logout-btn" title="خروج">
            <i class="fas fa-sign-out-alt"></i>
        </a>
    </div>
</aside>

<main class="main-content">
    <header class="top-header">
        <button class="menu-toggle" id="menuToggle"><i class="fas fa-bars"></i></button>
        <div class="search-box">
            <i class="fas fa-search"></i>
            <input type="text" placeholder="جستجو در سفارشات، کاربران...">
        </div>
        <div class="header-actions">
            <button class="header-btn" onclick="window.location='messages.php'">
                <i class="fas fa-envelope"></i>
                <?php if($unread_msgs > 0): ?><span class="notification-dot"></span><?php endif; ?>
            </button>
            <button class="header-btn" onclick="window.location='orders.php'">
                <i class="fas fa-bell"></i>
                <?php if($stats['new_orders'] > 0): ?><span class="notification-dot"></span><?php endif; ?>
            </button>
        </div>
    </header>

    <div class="dashboard-content">
        <div class="page-title">
            <h1>خوش آمدید 👋</h1>
            <p>گزارش کلی وضعیت فروشگاه در یک نگاه — <?= date('Y/m/d') ?></p>
        </div>

        <!-- هشدارها -->
        <?php if (!empty($alerts)): ?>
        <div class="alerts-section">
            <?php foreach ($alerts as $alert): ?>
            <div class="alert-item <?= $alert['type'] ?>">
                <i class="fas <?= $alert['icon'] ?>"></i>
                <?= $alert['msg'] ?>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <!-- کارت‌های آمار اصلی -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon blue"><i class="fas fa-users"></i></div>
                <div class="stat-info">
                    <h3><?= formatNumber($stats['users']) ?></h3>
                    <p>کاربران فعال</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon green"><i class="fas fa-wallet"></i></div>
                <div class="stat-info">
                    <h3><?= formatPrice($stats['revenue']) ?></h3>
                    <p>درآمد کل</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon orange"><i class="fas fa-box"></i></div>
                <div class="stat-info">
                    <h3><?= formatNumber($stats['new_orders']) ?></h3>
                    <p>سفارشات جدید</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon purple"><i class="fas fa-smile"></i></div>
                <div class="stat-info">
                    <h3><?= number_format($stats['satisfaction'], 1) ?>/5</h3>
                    <p>میانگین رضایت</p>
                </div>
            </div>
        </div>

        <!-- آمار امروز / هفته / ماه -->
        <div class="time-stats">
            <div class="time-stat-card">
                <div class="label"><i class="fas fa-calendar-day"></i> فروش امروز</div>
                <div class="value"><?= formatPrice($stats['today_revenue']) ?></div>
                <div class="sub"><?= formatNumber($stats['today_orders']) ?> سفارش امروز</div>
            </div>
            <div class="time-stat-card">
                <div class="label"><i class="fas fa-calendar-week"></i> فروش این هفته</div>
                <div class="value"><?= formatPrice($stats['week_revenue']) ?></div>
            </div>
            <div class="time-stat-card">
                <div class="label"><i class="fas fa-calendar-alt"></i> فروش این ماه</div>
                <div class="value"><?= formatPrice($stats['month_revenue']) ?></div>
            </div>
        </div>

        <!-- نمودار فروش -->
        <div class="glass-card" style="margin-bottom: 20px;">
            <div class="card-header">
                <h2><i class="fas fa-chart-area" style="color:var(--primary); margin-left:6px;"></i> نمودار فروش ۳۰ روز اخیر</h2>
                <a href="analytics.php" class="btn-secondary">گزارش کامل</a>
            </div>
            <div class="chart-container">
                <canvas id="salesChart"></canvas>
            </div>
        </div>

        <!-- گرید اصلی محتوا -->
        <div class="content-grid">

            <!-- سفارشات اخیر -->
            <div class="glass-card">
                <div class="card-header">
                    <h2>سفارشات اخیر</h2>
                    <a href="orders.php" class="btn-secondary">مشاهده همه</a>
                </div>
                <div style="overflow-x: auto;">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>شماره سفارش</th>
                                <th>مشتری</th>
                                <th>مبلغ</th>
                                <th>وضعیت</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(!empty($recentOrders)): ?>
                                <?php foreach($recentOrders as $order): ?>
                                <tr>
                                    <td><strong>#<?= htmlspecialchars($order['order_number']) ?></strong></td>
                                    <td><?= htmlspecialchars($order['customer_name'] ?? 'مهمان') ?></td>
                                    <td><?= number_format($order['final_amount']) ?> ت</td>
                                    <td>
                                        <span class="status <?= getOrderStatusClass($order['status']) ?>">
                                            <?= getStatusText($order['status']) ?>
                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="4" style="text-align:center; color:var(--text-muted);">سفارشی وجود ندارد</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- ستون راست -->
            <div style="display: flex; flex-direction: column; gap: 20px;">

                <!-- موجودی بحرانی -->
                <?php if (!empty($criticalStock)): ?>
                <div class="glass-card">
                    <div class="card-header">
                        <h2><i class="fas fa-exclamation-triangle" style="color:var(--danger);margin-left:6px;"></i> موجودی بحرانی</h2>
                        <a href="products.php?status=out_of_stock" class="btn-secondary">مشاهده</a>
                    </div>
                    <?php foreach ($criticalStock as $p): ?>
                    <div class="stock-item">
                        <span style="font-size:12px; flex:1; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;"><?= htmlspecialchars($p['name']) ?></span>
                        <div class="stock-bar">
                            <div class="stock-bar-fill <?= $p['stock'] == 0 ? 'critical' : 'low' ?>"
                                 style="width: <?= min(100, ($p['stock'] / 10) * 100) ?>%"></div>
                        </div>
                        <span style="font-size:11px; font-weight:700; color:<?= $p['stock']==0?'var(--danger)':'var(--warning)' ?>; width:30px; text-align:left;"><?= $p['stock'] ?></span>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>

                <!-- محصولات پرفروش -->
                <div class="glass-card">
                    <div class="card-header">
                        <h2>محصولات پرفروش</h2>
                        <a href="products.php" class="btn-secondary">همه</a>
                    </div>
                    <div class="products-list">
                        <?php if(!empty($topProducts)): ?>
                            <?php foreach($topProducts as $product): ?>
                            <div class="product-item">
                                <img src="../uploads/products/<?= htmlspecialchars($product['image'] ?? '') ?>"
                                     alt="<?= htmlspecialchars($product['name']) ?>"
                                     onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 44 44%22><rect width=%2244%22 height=%2244%22 fill=%22%23eee%22/><text x=%2222%22 y=%2228%22 text-anchor=%22middle%22 font-size=%2220%22>🎒</text></svg>'">
                                <div class="product-info">
                                    <h4><?= htmlspecialchars($product['name']) ?></h4>
                                    <p><?= $product['sales_count'] ?> فروش</p>
                                </div>
                                <div class="product-price"><?= number_format($product['price']) ?></div>
                            </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <p style="text-align:center; color:var(--text-muted);">محصولی موجود نیست</p>
                        <?php endif; ?>
                    </div>
                </div>

            </div><!-- /.column-right -->
        </div><!-- /.content-grid -->

        <!-- ردیف دوم -->
        <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; margin-top: 20px;">

            <!-- عملیات سریع -->
            <div class="glass-card">
                <div class="card-header"><h2>عملیات سریع</h2></div>
                <div class="quick-actions">
                    <a href="product-add.php" class="action-btn"><i class="fas fa-plus-circle"></i> افزودن محصول</a>
                    <a href="user-add.php" class="action-btn"><i class="fas fa-user-plus"></i> افزودن کاربر</a>
                    <a href="orders.php" class="action-btn"><i class="fas fa-file-invoice"></i> سفارشات</a>
                    <a href="reports.php" class="action-btn"><i class="fas fa-chart-line"></i> گزارش‌گیری</a>
                    <a href="messages.php" class="action-btn"><i class="fas fa-envelope"></i> پیام‌ها</a>
                    <a href="reviews.php" class="action-btn"><i class="fas fa-star"></i> نظرات</a>
                </div>
            </div>

            <!-- فعالیت‌های اخیر -->
            <div class="glass-card">
                <div class="card-header"><h2>فعالیت‌های اخیر</h2></div>
                <div class="activities-list">
                    <?php if(!empty($recentActivities)): ?>
                        <?php foreach($recentActivities as $log): ?>
                        <div class="activity-item">
                            <div class="activity-icon blue"><i class="fas fa-history"></i></div>
                            <div class="activity-info">
                                <h4><?= htmlspecialchars($log['description'] ?? $log['action']) ?></h4>
                                <p><?= timeAgo($log['created_at']) ?> <?php if($log['username']): ?>— <?= htmlspecialchars($log['username']) ?><?php endif; ?></p>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p style="text-align:center; color:var(--text-muted);">فعالیتی ثبت نشده</p>
                    <?php endif; ?>
                </div>
            </div>

            <!-- مشتریان برتر -->
            <div class="glass-card">
                <div class="card-header"><h2>مشتریان برتر</h2><a href="users.php" class="btn-secondary">همه</a></div>
                <div class="customers-list">
                    <?php if(!empty($topCustomers)): ?>
                        <?php foreach($topCustomers as $customer): ?>
                        <div class="customer-item">
                            <img src="../uploads/logo/default-avatar.png" alt=""
                                 onerror="this.style.background='#667eea'">
                            <div class="customer-info">
                                <h4><?= htmlspecialchars($customer['full_name'] ?: 'بدون نام') ?></h4>
                                <p><?= $customer['order_count'] ?> سفارش &bull; <?= number_format($customer['total_spent']) ?> ت</p>
                            </div>
                            <div class="customer-badge"><i class="fas fa-crown"></i></div>
                        </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p style="text-align:center; color:var(--text-muted);">مشتری فعالی وجود ندارد</p>
                    <?php endif; ?>
                </div>
            </div>

        </div><!-- /.row-2 -->

    </div><!-- /.dashboard-content -->
</main>

<script src="assets/js/script.js"></script>
<script>
// نمودار فروش ۳۰ روز
const ctx = document.getElementById('salesChart')?.getContext('2d');
if (ctx) {
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: <?= json_encode($chart_labels, JSON_UNESCAPED_UNICODE) ?>,
            datasets: [{
                label: 'فروش (تومان)',
                data: <?= json_encode($chart_revenue) ?>,
                borderColor: '#007AFF',
                backgroundColor: 'rgba(0,122,255,0.08)',
                borderWidth: 2.5,
                fill: true,
                tension: 0.4,
                pointRadius: 3,
                pointBackgroundColor: '#007AFF'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false },
                tooltip: {
                    callbacks: {
                        label: ctx => new Intl.NumberFormat('fa-IR').format(ctx.parsed.y) + ' تومان'
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: val => new Intl.NumberFormat('fa-IR', {notation:'compact'}).format(val),
                        font: { family: 'Vazirmatn', size: 11 }
                    },
                    grid: { color: 'rgba(0,0,0,0.05)' }
                },
                x: {
                    ticks: { font: { family: 'Vazirmatn', size: 10 }, maxTicksLimit: 10 },
                    grid: { display: false }
                }
            }
        }
    });
}
</script>
</body>
</html>