<?php
// ========================================
// تحلیل و آمار (Analytics)
// پروژه فروشگاه کیف‌لند
// ========================================
require_once '../config/database.php';
require_once '../config/settings.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

Auth::requireAdmin();
$db = Database::getInstance()->getConnection();
$pageTitle = 'تحلیل و آمار | کیف‌لند';

// ========================================
// فیلتر بازه زمانی
// ========================================
$period = in_array($_GET['period'] ?? '', ['7', '30', '90', '365']) ? $_GET['period'] : '30';
$start_date = date('Y-m-d', strtotime("-$period days"));
$end_date   = date('Y-m-d');

// ========================================
// دریافت داده‌های آماری (با مدیریت خطا برای جلوگیری از کرش)
// ========================================
try {
    // درآمد و تعداد سفارشات
    $stmt = $db->prepare("SELECT COALESCE(SUM(final_amount), 0) as total_revenue, COUNT(*) as total_orders FROM orders WHERE status != 'cancelled' AND created_at BETWEEN ? AND ?");
    $stmt->execute([$start_date . ' 00:00:00', $end_date . ' 23:59:59']);
    $revenue_data = $stmt->fetch();

    // بازدیدکنندگان (اگر جدول page_views نبود، از تعداد کاربران جدید استفاده می‌کند)
    $visitors = 0;
    try {
        $stmt = $db->prepare("SELECT COUNT(DISTINCT ip_address) as visitors FROM page_views WHERE visited_at BETWEEN ? AND ?");
        $stmt->execute([$start_date . ' 00:00:00', $end_date . ' 23:59:59']);
        $visitors = $stmt->fetchColumn();
    } catch (Exception $e) {
        $stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE created_at BETWEEN ? AND ?");
        $stmt->execute([$start_date, $end_date]);
        $visitors = $stmt->fetchColumn();
    }
    $visitors = max((int)$visitors, 1); // جلوگیری از تقسیم بر صفر

    // نرخ تبدیل
    $total_orders = (int)$revenue_data['total_orders'];
    $conversion_rate = round(($total_orders / $visitors) * 100, 1);

    // داده‌های نمودار روزانه
    $stmt = $db->prepare("SELECT DATE(created_at) as date, SUM(final_amount) as revenue, COUNT(*) as orders FROM orders WHERE status != 'cancelled' AND created_at BETWEEN ? AND ? GROUP BY DATE(created_at) ORDER BY date ASC");
    $stmt->execute([$start_date . ' 00:00:00', $end_date . ' 23:59:59']);
    $daily_stats = $stmt->fetchAll();

    // محصولات پرفروش
    $stmt = $db->prepare("SELECT p.name, p.image, SUM(oi.quantity) as sold, COALESCE(SUM(oi.subtotal), 0) as revenue FROM order_items oi JOIN products p ON oi.product_id = p.id JOIN orders o ON oi.order_id = o.id WHERE o.status != 'cancelled' AND o.created_at BETWEEN ? AND ? GROUP BY oi.product_id ORDER BY sold DESC LIMIT 5");
    $stmt->execute([$start_date . ' 00:00:00', $end_date . ' 23:59:59']);
    $top_products = $stmt->fetchAll();

    // میانگین ارزش سفارش (AOV)
    $aov = $total_orders > 0 ? round($revenue_data['total_revenue'] / $total_orders) : 0;

} catch (Exception $e) {
    $revenue_data  = ['total_revenue' => 0, 'total_orders' => 0];
    $visitors      = 1;
    $conversion_rate = 0;
    $daily_stats   = [];
    $top_products  = [];
    $aov           = 0;
}

// آماده‌سازی داده‌ها برای نمودار
$chart_labels = [];
$chart_values = [];
$max_val = 1;
foreach ($daily_stats as $row) {
    $chart_labels[] = date('m/d', strtotime($row['date']));
    $chart_values[] = round($row['revenue']);
    if ($row['revenue'] > $max_val) $max_val = $row['revenue'];
}

include 'includes/admin-header.php';
?>

<style>
/* ========================================
   Analytics Page - Complete Internal CSS
   ======================================== */
.analytics-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    flex-wrap: wrap;
    gap: 16px;
}
.period-selector {
    display: flex;
    gap: 8px;
    background: var(--glass-bg);
    backdrop-filter: blur(15px);
    padding: 6px;
    border-radius: var(--radius-sm);
    border: 1px solid var(--glass-border);
}
.period-btn {
    padding: 8px 16px;
    border-radius: var(--radius-xs);
    font-size: 13px;
    font-weight: 600;
    color: var(--text-secondary);
    background: transparent;
    border: none;
    cursor: pointer;
    transition: all var(--transition-fast);
    font-family: 'Vazirmatn', sans-serif;
}
.period-btn:hover { background: var(--glass-hover); color: var(--text-primary); }
.period-btn.active { background: var(--primary); color: white; box-shadow: 0 2px 8px rgba(0,122,255,0.25); }

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 16px;
    margin-bottom: 24px;
}
.stat-card {
    background: var(--glass-bg);
    backdrop-filter: blur(40px) saturate(180%);
    border: 1px solid var(--glass-border);
    border-radius: var(--radius);
    padding: 18px;
    display: flex;
    align-items: center;
    gap: 14px;
    box-shadow: var(--shadow-card);
    transition: all var(--transition-fast);
}
.stat-card:hover { transform: translateY(-3px); box-shadow: var(--shadow-soft); background: var(--glass-bg-light); }
.stat-icon {
    width: 52px; height: 52px; border-radius: 14px;
    display: flex; align-items: center; justify-content: center;
    font-size: 20px; color: white; box-shadow: 0 4px 12px rgba(0,0,0,0.15); flex-shrink: 0;
}
.stat-icon.blue { background: linear-gradient(135deg, #007AFF 0%, #5856D6 100%); }
.stat-icon.green { background: linear-gradient(135deg, #34C759 0%, #30D158 100%); }
.stat-icon.orange { background: linear-gradient(135deg, #FF9500 0%, #FF6B35 100%); }
.stat-icon.purple { background: linear-gradient(135deg, #5856D6 0%, #AF52DE 100%); }
.stat-info h3 { font-size: 24px; font-weight: 700; margin: 0 0 4px; letter-spacing: -0.3px; }
.stat-info p { color: var(--text-secondary); font-size: 12px; margin: 0 0 6px; opacity: 0.8; }
.stat-change { display: inline-flex; align-items: center; gap: 4px; font-size: 10px; font-weight: 600; padding: 3px 8px; border-radius: 8px; }
.stat-change.positive { background: rgba(52,199,89,0.15); color: var(--success); }
.stat-change.negative { background: rgba(255,59,48,0.15); color: var(--danger); }

.content-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(360px, 1fr));
    gap: 20px;
}
.glass-card {
    background: var(--glass-bg); backdrop-filter: blur(40px) saturate(180%);
    border: 1px solid var(--glass-border); border-radius: var(--radius);
    padding: 18px; box-shadow: var(--shadow-card); transition: all var(--transition-fast);
}
.glass-card:hover { box-shadow: var(--shadow-soft); background: var(--glass-bg-light); }
.card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; }
.card-header h3 { margin: 0; font-size: 16px; font-weight: 700; }

/* Chart */
.chart-container { padding: 10px 0; }
.bar-chart { display: flex; align-items: flex-end; justify-content: space-between; gap: 10px; height: 180px; margin-top: 16px; }
.bar-item { flex: 1; display: flex; flex-direction: column; align-items: center; gap: 6px; }
.bar {
    width: 100%; background: linear-gradient(to top, #007AFF 0%, #5856D6 100%);
    border-radius: 8px 8px 0 0; min-height: 4px; transition: height 0.8s cubic-bezier(0.4, 0, 0.2, 1);
    box-shadow: 0 2px 8px rgba(0, 122, 255, 0.2); position: relative;
}
.bar:hover { opacity: 0.9; }
.bar-tooltip {
    position: absolute; top: -28px; left: 50%; transform: translateX(-50%);
    background: var(--dark); color: white; padding: 4px 8px; border-radius: 6px;
    font-size: 10px; white-space: nowrap; opacity: 0; transition: opacity 0.2s; pointer-events: none;
}
.bar:hover .bar-tooltip { opacity: 1; }
.bar-item span { font-size: 10px; color: var(--text-secondary); }

/* Lists & Tables */
.products-list { display: flex; flex-direction: column; gap: 10px; }
.list-item {
    display: flex; align-items: center; gap: 12px; padding: 12px;
    background: rgba(255,255,255,0.2); border-radius: var(--radius-sm);
    border: 0.5px solid var(--glass-border); transition: all var(--transition-fast);
}
.list-item:hover { background: rgba(255,255,255,0.35); transform: translateX(-2px); }
.list-item img { width: 48px; height: 48px; border-radius: 10px; object-fit: cover; border: 0.5px solid rgba(255,255,255,0.3); }
.list-info { flex: 1; min-width: 0; }
.list-title { font-size: 14px; font-weight: 600; margin-bottom: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.list-sub { font-size: 12px; color: var(--text-secondary); }
.list-price { font-size: 14px; font-weight: 700; color: var(--primary); white-space: nowrap; }

.table-responsive { overflow-x: auto; border-radius: var(--radius-sm); }
.data-table { width: 100%; border-collapse: collapse; min-width: 600px; }
.data-table th { text-align: right; padding: 12px; font-size: 11px; font-weight: 600; color: var(--text-secondary); border-bottom: 1px solid var(--glass-border); }
.data-table td { padding: 12px; font-size: 13px; border-bottom: 0.5px solid rgba(255,255,255,0.15); }
.data-table tr:hover { background: rgba(255,255,255,0.15); }

.status { display: inline-flex; padding: 4px 8px; border-radius: 6px; font-size: 10px; font-weight: 600; }
.status.success { background: rgba(52,199,89,0.2); color: var(--success); }
.status.pending { background: rgba(255,149,0,0.2); color: var(--warning); }
.status.cancelled { background: rgba(255,59,48,0.2); color: var(--danger); }

.btn-secondary {
    background: rgba(0,122,255,0.12); color: var(--primary); border: 0.5px solid rgba(0,122,255,0.2);
    padding: 6px 12px; border-radius: var(--radius-sm); font-size: 12px; font-weight: 600;
    cursor: pointer; transition: all var(--transition-fast); text-decoration: none; display: inline-flex; align-items: center; gap: 6px;
}
.btn-secondary:hover { background: rgba(0,122,255,0.2); }

.empty-state { text-align: center; padding: 30px; color: var(--text-secondary); }
.empty-state i { font-size: 32px; opacity: 0.4; margin-bottom: 8px; display: block; }

@media (max-width: 768px) {
    .analytics-header { flex-direction: column; align-items: flex-start; }
    .stats-grid { grid-template-columns: 1fr; }
    .content-grid { grid-template-columns: 1fr; }
    .period-selector { width: 100%; overflow-x: auto; }
}
</style>

<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">
            <a href="export.php?type=analytics&period=<?= $period ?>" class="btn btn-ghost btn-sm"><i class="fas fa-download"></i> خروجی PDF</a>
        </div>
    </header>

    <div class="dashboard-content">
        <div class="analytics-header">
            <div class="page-title" style="margin:0;">
                <h1>تحلیل و آمار فروشگاه</h1>
                <p>نمای کلی عملکرد فروش، بازدید و تبدیل</p>
            </div>
            <form method="GET" class="period-selector">
                <button type="submit" name="period" value="7" class="period-btn <?= $period=='7'?'active':'' ?>">۷ روز</button>
                <button type="submit" name="period" value="30" class="period-btn <?= $period=='30'?'active':'' ?>">۳۰ روز</button>
                <button type="submit" name="period" value="90" class="period-btn <?= $period=='90'?'active':'' ?>">۳ ماه</button>
                <button type="submit" name="period" value="365" class="period-btn <?= $period=='365'?'active':'' ?>">۱ سال</button>
            </form>
        </div>

        <!-- کارت‌های آمار -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon blue"><i class="fas fa-coins"></i></div>
                <div class="stat-info">
                    <h3><?= number_format($revenue_data['total_revenue']) ?> تومان</h3>
                    <p>درآمد خالص</p>
                    <span class="stat-change positive"><i class="fas fa-arrow-up"></i> <?= $total_orders ?> سفارش</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon green"><i class="fas fa-shopping-bag"></i></div>
                <div class="stat-info">
                    <h3><?= number_format($total_orders) ?></h3>
                    <p>سفارشات موفق</p>
                    <span class="stat-change positive"><i class="fas fa-wallet"></i> میانگین <?= number_format($aov) ?> تومان</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon orange"><i class="fas fa-eye"></i></div>
                <div class="stat-info">
                    <h3><?= number_format($visitors) ?></h3>
                    <p>بازدیدکننده یکتا</p>
                    <span class="stat-change <?= $visitors>100?'positive':'negative' ?>"><i class="fas fa-globe"></i> بازه انتخابی</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon purple"><i class="fas fa-chart-line"></i></div>
                <div class="stat-info">
                    <h3><?= $conversion_rate ?>٪</h3>
                    <p>نرخ تبدیل</p>
                    <span class="stat-change <?= $conversion_rate>2?'positive':'negative' ?>"><i class="fas fa-users"></i> عملکرد فروشگاه</span>
                </div>
            </div>
        </div>

        <!-- گرید محتوا -->
        <div class="content-grid">
            <!-- نمودار درآمد -->
            <div class="glass-card">
                <div class="card-header">
                    <h3><i class="fas fa-chart-bar" style="margin-left:8px; color:var(--primary);"></i> روند درآمد روزانه</h3>
                    <span class="btn btn-secondary">تومان</span>
                </div>
                <div class="chart-container" id="revenueChart">
                    <?php if (!empty($chart_values)): ?>
                    <div class="bar-chart">
                        <?php foreach ($chart_values as $i => $val): 
                            $height = max(4, ($val / $max_val) * 100); 
                        ?>
                        <div class="bar-item">
                            <div class="bar" style="height: 0%;" data-height="<?= $height ?>">
                                <div class="bar-tooltip"><?= number_format($val) ?> تومان</div>
                            </div>
                            <span><?= $chart_labels[$i] ?></span>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php else: ?>
                    <div class="empty-state"><i class="fas fa-chart-area"></i> داده‌ای برای این بازه موجود نیست.</div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- محصولات پرفروش -->
            <div class="glass-card">
                <div class="card-header">
                    <h3><i class="fas fa-fire" style="margin-left:8px; color:var(--warning);"></i> محصولات پرفروش</h3>
                    <a href="products.php" class="btn btn-secondary">مشاهده همه</a>
                </div>
                <div class="products-list">
                    <?php if (!empty($top_products)): ?>
                        <?php foreach ($top_products as $prod): ?>
                        <div class="list-item">
                            <?php 
                            $img = $prod['image'] && file_exists('../uploads/products/'.$prod['image']) ? '../uploads/products/'.$prod['image'] : '';
                            $img_html = $img ? "<img src='$img' alt='".htmlspecialchars($prod['name'])."'>" : "<div style='width:48px;height:48px;background:var(--glass-hover);border-radius:10px;display:flex;align-items:center;justify-content:center;color:var(--text-muted);'><i class='fas fa-image'></i></div>";
                            ?>
                            <?= $img_html ?>
                            <div class="list-info">
                                <h4 class="list-title"><?= htmlspecialchars($prod['name']) ?></h4>
                                <p class="list-sub"><?= number_format($prod['sold']) ?> فروش</p>
                            </div>
                            <span class="list-price"><?= number_format($prod['revenue']) ?> تومان</span>
                        </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="empty-state"><i class="fas fa-box-open"></i> فروشی در این بازه ثبت نشده است.</div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- سفارشات اخیر -->
            <div class="glass-card" style="grid-column: 1 / -1;">
                <div class="card-header">
                    <h3><i class="fas fa-clock" style="margin-left:8px; color:var(--info);"></i> سفارشات اخیر</h3>
                    <a href="orders.php" class="btn btn-secondary">مدیریت سفارشات</a>
                </div>
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr><th>شماره</th><th>مشتری</th><th>مبلغ</th><th>وضعیت</th><th>تاریخ</th></tr>
                        </thead>
                        <tbody>
                            <?php
                            $recent_stmt = $db->prepare("SELECT o.order_number, o.final_amount, o.status, o.created_at, u.full_name FROM orders o LEFT JOIN users u ON o.user_id = u.id WHERE o.created_at BETWEEN ? AND ? ORDER BY o.created_at DESC LIMIT 5");
                            $recent_stmt->execute([$start_date.' 00:00:00', $end_date.' 23:59:59']);
                            $recent_orders = $recent_stmt->fetchAll();
                            
                            if (!empty($recent_orders)):
                                foreach ($recent_orders as $ord):
                            ?>
                            <tr>
                                <td><strong>#<?= htmlspecialchars($ord['order_number']) ?></strong></td>
                                <td><?= htmlspecialchars($ord['full_name'] ?: 'مهمان') ?></td>
                                <td><?= number_format($ord['final_amount']) ?> تومان</td>
                                <td><span class="status <?= $ord['status']=='delivered'?'success':($ord['status']=='cancelled'?'cancelled':'pending') ?>"><?= getStatusText($ord['status']) ?></span></td>
                                <td style="font-size:12px; color:var(--text-secondary);"><?= jdate($ord['created_at']) ?></td>
                            </tr>
                            <?php 
                                endforeach; 
                            else: 
                            ?>
                            <tr><td colspan="5" class="text-center text-muted py-4">سفارشی در این بازه یافت نشد.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</main>

<script src="assets/js/script.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // انیمیشن نمودار میله‌ای
    const bars = document.querySelectorAll('#revenueChart .bar');
    if (bars.length > 0) {
        setTimeout(() => {
            bars.forEach((bar, i) => {
                setTimeout(() => {
                    bar.style.height = bar.dataset.height + '%';
                }, i * 60);
            });
        }, 300);
    }

    // ذخیره بازه انتخابی در localStorage برای تجربه بهتر
    const periodForm = document.querySelector('.period-selector');
    if (periodForm) {
        periodForm.addEventListener('submit', function(e) {
            const activeBtn = this.querySelector('.period-btn.active');
            if (activeBtn) {
                localStorage.setItem('admin_analytics_period', activeBtn.value);
            }
        });
        
        // بازیابی بازه قبلی
        const savedPeriod = localStorage.getItem('admin_analytics_period');
        if (savedPeriod && !new URLSearchParams(window.location.search).has('period')) {
            window.location.href = '?period=' + savedPeriod;
        }
    }
});
</script>

<?php include 'includes/admin-footer.php'; ?>