<?php $__env->startSection('title', 'تحلیل کاربران'); ?>

<?php $__env->startSection('content'); ?>
<div class="container-fluid">
    <!-- Modern Header Section -->
    <div class="user-analytics-header">
        <div class="header-content">
            <div class="header-text">
                <h1 class="header-title">
                    <i class="fas fa-users-cog me-3"></i>
                    تحلیل کاربران
                </h1>
                <p class="header-subtitle">
                    بررسی جامع رفتار، فعالیت و عملکرد کاربران سیستم
                </p>
            </div>
            <div class="header-controls">
                <div class="btn-group me-2" role="group">
                    <button type="button" class="btn btn-outline-primary" data-user-view="overview">
                        <i class="fas fa-chart-pie me-1"></i>
                        نمای کلی
                    </button>
                    <button type="button" class="btn btn-outline-primary active" data-user-view="activity">
                        <i class="fas fa-chart-line me-1"></i>
                        فعالیت
                    </button>
                    <button type="button" class="btn btn-outline-primary" data-user-view="engagement">
                        <i class="fas fa-heart me-1"></i>
                        تعامل
                    </button>
                    <button type="button" class="btn btn-outline-primary" data-user-view="segmentation">
                        <i class="fas fa-layer-group me-1"></i>
                        بخش‌بندی
                    </button>
                </div>
                <div class="dropdown">
                    <button class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                        <i class="fas fa-cog me-1"></i>
                        تنظیمات
                    </button>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="#" onclick="refreshUserData()">
                            <i class="fas fa-sync me-2"></i>بروزرسانی داده‌ها
                        </a></li>
                        <li><a class="dropdown-item" href="#" onclick="exportUserData('excel')">
                            <i class="fas fa-file-excel me-2"></i>خروجی Excel
                        </a></li>
                        <li><a class="dropdown-item" href="#" onclick="exportUserData('pdf')">
                            <i class="fas fa-file-pdf me-2"></i>خروجی PDF
                        </a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="#" onclick="showUserFilters()">
                            <i class="fas fa-filter me-2"></i>فیلترهای پیشرفته
                        </a></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <!-- Enhanced Overview Cards -->
    <div class="row mb-4" id="user-overview-cards">
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="user-overview-card">
                <div class="card-icon bg-primary">
                    <i class="fas fa-users"></i>
                </div>
                <div class="card-content">
                    <div class="card-value"><?php echo e($userStats['total_users'] ?? 0); ?></div>
                    <div class="card-label">کل کاربران</div>
                    <div class="card-trend <?php echo e(($userStats['user_growth'] ?? 0) >= 0 ? 'positive' : 'negative'); ?>">
                        <i class="fas fa-<?php echo e(($userStats['user_growth'] ?? 0) >= 0 ? 'arrow-up' : 'arrow-down'); ?> me-1"></i>
                        <?php echo e($userStats['user_growth'] ?? 0); ?>% رشد ماهانه
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="user-overview-card">
                <div class="card-icon bg-success">
                    <i class="fas fa-user-check"></i>
                </div>
                <div class="card-content">
                    <div class="card-value"><?php echo e($userStats['active_users'] ?? 0); ?></div>
                    <div class="card-label">کاربران فعال</div>
                    <div class="card-trend neutral">
                        <i class="fas fa-percentage me-1"></i>
                        <?php echo e(round($userStats['active_percentage'] ?? 0)); ?>% از کل
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="user-overview-card">
                <div class="card-icon bg-info">
                    <i class="fas fa-user-plus"></i>
                </div>
                <div class="card-content">
                    <div class="card-value"><?php echo e($userStats['new_users'] ?? 0); ?></div>
                    <div class="card-label">کاربران جدید</div>
                    <div class="card-trend neutral">
                        <i class="fas fa-calendar me-1"></i>
                        30 روز گذشته
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 mb-4">
            <div class="user-overview-card">
                <div class="card-icon bg-warning">
                    <i class="fas fa-sign-in-alt"></i>
                </div>
                <div class="card-content">
                    <div class="card-value"><?php echo e($userStats['recent_logins'] ?? 0); ?></div>
                    <div class="card-label">ورود اخیر</div>
                    <div class="card-trend neutral">
                        <i class="fas fa-clock me-1"></i>
                        7 روز گذشته
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Overview Section -->
    <div class="user-view d-none" id="overview-view">
        <div class="row">
            <div class="col-lg-8 mb-4">
                <div class="user-chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <h5 class="mb-1">
                                <i class="fas fa-chart-area text-primary me-2"></i>
                                نمای کلی کاربران
                            </h5>
                            <p class="text-muted mb-0">توزیع و آمار کلی کاربران سیستم</p>
                        </div>
                        <div class="chart-actions">
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-outline-secondary active" onclick="toggleOverviewChart('users')">
                                    <i class="fas fa-users"></i>
                                </button>
                                <button class="btn btn-outline-secondary" onclick="toggleOverviewChart('growth')">
                                    <i class="fas fa-chart-line"></i>
                                </button>
                                <button class="btn btn-outline-secondary" onclick="toggleOverviewChart('comparison')">
                                    <i class="fas fa-balance-scale"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="chart-body">
                        <div id="overview-chart" class="chart-container"></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4 mb-4">
                <div class="user-stats-card">
                    <div class="stats-header">
                        <h6 class="mb-0">
                            <i class="fas fa-info-circle text-info me-2"></i>
                            آمار سریع
                        </h6>
                    </div>
                    <div class="stats-body">
                        <div class="stat-item">
                            <div class="stat-icon bg-primary">
                                <i class="fas fa-user-shield"></i>
                            </div>
                            <div class="stat-content">
                                <div class="stat-value"><?php echo e($userStats['total_admins'] ?? 0); ?></div>
                                <div class="stat-label">مدیران سیستم</div>
                            </div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-icon bg-success">
                                <i class="fas fa-user-check"></i>
                            </div>
                            <div class="stat-content">
                                <div class="stat-value"><?php echo e($userStats['active_admins'] ?? 0); ?></div>
                                <div class="stat-label">مدیران فعال</div>
                            </div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-icon bg-info">
                                <i class="fas fa-percentage"></i>
                            </div>
                            <div class="stat-content">
                                <div class="stat-value"><?php echo e(round($userStats['login_percentage'] ?? 0)); ?>%</div>
                                <div class="stat-label">نرخ ورود</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Activity Section -->
    <div class="user-view" id="activity-view">
        <div class="row">
            <div class="col-lg-8 mb-4">
                <div class="user-chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <h5 class="mb-1">
                                <i class="fas fa-chart-line text-success me-2"></i>
                                روند فعالیت کاربران
                            </h5>
                            <p class="text-muted mb-0">نمایش فعالیت‌های کاربران در 30 روز گذشته</p>
                        </div>
                        <div class="chart-actions">
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-outline-secondary active" onclick="toggleActivityChart('registrations')">
                                    <i class="fas fa-user-plus"></i>
                                </button>
                                <button class="btn btn-outline-secondary" onclick="toggleActivityChart('logins')">
                                    <i class="fas fa-sign-in-alt"></i>
                                </button>
                                <button class="btn btn-outline-secondary" onclick="toggleActivityChart('both')">
                                    <i class="fas fa-layer-group"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="chart-body">
                        <div id="activity-chart" class="chart-container"></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4 mb-4">
                <div class="user-activity-summary">
                    <div class="summary-header">
                        <h6 class="mb-0">
                            <i class="fas fa-chart-bar text-primary me-2"></i>
                            خلاصه فعالیت
                        </h6>
                    </div>
                    <div class="summary-body">
                        <div class="summary-item">
                            <div class="summary-label">میانگین ثبت‌نام روزانه</div>
                            <div class="summary-value" id="avg-registrations">-</div>
                        </div>
                        <div class="summary-item">
                            <div class="summary-label">میانگین ورود روزانه</div>
                            <div class="summary-value" id="avg-logins">-</div>
                        </div>
                        <div class="summary-item">
                            <div class="summary-label">بیشترین ثبت‌نام در روز</div>
                            <div class="summary-value" id="max-registrations">-</div>
                        </div>
                        <div class="summary-item">
                            <div class="summary-label">بیشترین ورود در روز</div>
                            <div class="summary-value" id="max-logins">-</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Engagement Section -->
    <div class="user-view d-none" id="engagement-view">
        <div class="row">
            <div class="col-lg-6 mb-4">
                <div class="user-engagement-card">
                    <div class="engagement-header">
                        <h5 class="mb-1">
                            <i class="fas fa-heart text-danger me-2"></i>
                            شاخص‌های تعامل
                        </h5>
                        <p class="text-muted mb-0">میزان تعامل و مشارکت کاربران</p>
                    </div>
                    <div class="engagement-body">
                        <div class="engagement-metric">
                            <div class="metric-header">
                                <span class="metric-label">نرخ بازگشت</span>
                                <span class="metric-value"><?php echo e($userEngagementMetrics['return_rate'] ?? 0); ?>%</span>
                            </div>
                            <div class="metric-progress">
                                <div class="progress-bar" style="width: <?php echo e($userEngagementMetrics['return_rate'] ?? 0); ?>%"></div>
                            </div>
                        </div>
                        <div class="engagement-metric">
                            <div class="metric-header">
                                <span class="metric-label">میزان مشارکت</span>
                                <span class="metric-value"><?php echo e($userEngagementMetrics['participation_rate'] ?? 0); ?>%</span>
                            </div>
                            <div class="metric-progress">
                                <div class="progress-bar" style="width: <?php echo e($userEngagementMetrics['participation_rate'] ?? 0); ?>%"></div>
                            </div>
                        </div>
                        <div class="engagement-metric">
                            <div class="metric-header">
                                <span class="metric-label">نرخ ماندگاری</span>
                                <span class="metric-value"><?php echo e($userEngagementMetrics['retention_rate'] ?? 0); ?>%</span>
                            </div>
                            <div class="metric-progress">
                                <div class="progress-bar" style="width: <?php echo e($userEngagementMetrics['retention_rate'] ?? 0); ?>%"></div>
                            </div>
                        </div>
                        <div class="engagement-metric">
                            <div class="metric-header">
                                <span class="metric-label">نرخ رضایت</span>
                                <span class="metric-value"><?php echo e($userEngagementMetrics['satisfaction_rate'] ?? 0); ?>%</span>
                            </div>
                            <div class="metric-progress">
                                <div class="progress-bar" style="width: <?php echo e($userEngagementMetrics['satisfaction_rate'] ?? 0); ?>%"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-6 mb-4">
                <div class="user-timeline-card">
                    <div class="timeline-header">
                        <h6 class="mb-0">
                            <i class="fas fa-clock text-info me-2"></i>
                            فعالیت‌های اخیر
                        </h6>
                    </div>
                    <div class="timeline-body">
                        <div id="user-timeline" class="timeline-container">
                            <!-- Timeline items will be inserted here -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Segmentation Section -->
    <div class="user-view d-none" id="segmentation-view">
        <div class="row">
            <div class="col-lg-6 mb-4">
                <div class="user-chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <h5 class="mb-1">
                                <i class="fas fa-users text-primary me-2"></i>
                                بخش‌بندی بر اساس نقش
                            </h5>
                            <p class="text-muted mb-0">توزیع کاربران بر اساس نقش‌های مختلف</p>
                        </div>
                    </div>
                    <div class="chart-body">
                        <div id="roles-chart" class="chart-container"></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-6 mb-4">
                <div class="user-chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <h5 class="mb-1">
                                <i class="fas fa-chart-pie text-success me-2"></i>
                                بخش‌بندی بر اساس فعالیت
                            </h5>
                            <p class="text-muted mb-0">تقسیم‌بندی کاربران بر اساس میزان فعالیت</p>
                        </div>
                    </div>
                    <div class="chart-body">
                        <div id="activity-segment-chart" class="chart-container"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Advanced Filters Panel -->
    <div class="user-filters-panel d-none" id="user-filters">
        <div class="filters-header">
            <h6 class="mb-0">
                <i class="fas fa-filter me-2"></i>
                فیلترهای پیشرفته
            </h6>
            <button class="btn btn-sm btn-outline-secondary" onclick="hideUserFilters()">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="filters-body">
            <div class="row">
                <div class="col-md-3">
                    <label class="form-label">بازه زمانی</label>
                    <select class="form-select" id="user-date-range">
                        <option value="7">7 روز گذشته</option>
                        <option value="30" selected>30 روز گذشته</option>
                        <option value="90">90 روز گذشته</option>
                        <option value="365">یک سال گذشته</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">نوع کاربر</label>
                    <select class="form-select" id="user-type-filter">
                        <option value="all">همه کاربران</option>
                        <option value="active">کاربران فعال</option>
                        <option value="inactive">کاربران غیرفعال</option>
                        <option value="new">کاربران جدید</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">نقش کاربر</label>
                    <select class="form-select" id="user-role-filter">
                        <option value="all">همه نقش‌ها</option>
                        <option value="user">کاربر عادی</option>
                        <option value="admin">مدیر</option>
                        <option value="moderator">ناظر</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">حداقل فعالیت</label>
                    <input type="number" class="form-control" id="user-min-activity" value="1" min="1">
                </div>
            </div>
            <div class="filters-actions mt-3">
                <button class="btn btn-primary" onclick="applyUserFilters()">
                    <i class="fas fa-check me-1"></i>
                    اعمال فیلترها
                </button>
                <button class="btn btn-outline-secondary" onclick="resetUserFilters()">
                    <i class="fas fa-undo me-1"></i>
                    بازنشانی
                </button>
            </div>
        </div>
    </div>
</div>

<?php $__env->stopSection(); ?>

<?php $__env->startSection('styles'); ?>
<style>
    /* Modern User Analytics Styles */
    .user-analytics-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 20px;
        padding: 2rem;
        margin-bottom: 2rem;
        color: white;
        position: relative;
        overflow: hidden;
    }

    .user-analytics-header::before {
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        width: 100%;
        height: 100%;
        background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="white" opacity="0.1"/><circle cx="75" cy="75" r="1" fill="white" opacity="0.1"/><circle cx="50" cy="10" r="0.5" fill="white" opacity="0.1"/><circle cx="10" cy="50" r="0.5" fill="white" opacity="0.1"/><circle cx="90" cy="30" r="0.5" fill="white" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
        pointer-events: none;
    }

    .header-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        position: relative;
        z-index: 1;
    }

    .header-title {
        font-size: 2.5rem;
        font-weight: 700;
        margin-bottom: 0.5rem;
        text-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .header-subtitle {
        font-size: 1.1rem;
        opacity: 0.9;
        margin-bottom: 0;
    }

    .header-controls .btn {
        margin-left: 0.5rem;
        border-color: rgba(255,255,255,0.3);
        color: white;
        backdrop-filter: blur(10px);
        transition: all 0.3s ease;
    }

    .header-controls .btn:hover {
        background: rgba(255,255,255,0.2);
        border-color: rgba(255,255,255,0.5);
        transform: translateY(-2px);
    }

    .header-controls .btn.active {
        background: rgba(255,255,255,0.2);
        border-color: rgba(255,255,255,0.5);
    }

    /* Overview Cards */
    .user-overview-card {
        background: white;
        border-radius: 16px;
        padding: 1.5rem;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        border: 1px solid #f0f0f0;
        transition: all 0.3s ease;
        height: 100%;
        display: flex;
        align-items: center;
        gap: 1rem;
    }

    .user-overview-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 30px rgba(0,0,0,0.12);
    }

    .user-overview-card .card-icon {
        width: 60px;
        height: 60px;
        border-radius: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.5rem;
        color: white;
        flex-shrink: 0;
    }

    .user-overview-card .card-content {
        flex: 1;
    }

    .user-overview-card .card-value {
        font-size: 2rem;
        font-weight: 700;
        color: #2c3e50;
        margin-bottom: 0.25rem;
    }

    .user-overview-card .card-label {
        font-size: 0.9rem;
        color: #6c757d;
        margin-bottom: 0.5rem;
    }

    .user-overview-card .card-trend {
        font-size: 0.8rem;
        font-weight: 500;
        display: flex;
        align-items: center;
    }

    .user-overview-card .card-trend.positive {
        color: #28a745;
    }

    .user-overview-card .card-trend.negative {
        color: #dc3545;
    }

    .user-overview-card .card-trend.neutral {
        color: #6c757d;
    }

    /* Chart Cards */
    .user-chart-card {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        border: 1px solid #f0f0f0;
        overflow: hidden;
        height: 100%;
    }

    .chart-header {
        padding: 1.5rem;
        border-bottom: 1px solid #f0f0f0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: #fafbfc;
    }

    .chart-title h5 {
        color: #2c3e50;
        font-weight: 600;
        margin-bottom: 0.25rem;
    }

    .chart-title p {
        font-size: 0.9rem;
        margin-bottom: 0;
    }

    .chart-actions .btn {
        border-radius: 8px;
        padding: 0.5rem 0.75rem;
        transition: all 0.3s ease;
    }

    .chart-actions .btn.active {
        background: #667eea;
        border-color: #667eea;
        color: white;
    }

    .chart-body {
        padding: 1.5rem;
    }

    .chart-container {
        height: 350px;
        position: relative;
    }

    /* Stats Card */
    .user-stats-card {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        border: 1px solid #f0f0f0;
        overflow: hidden;
        height: 100%;
    }

    .stats-header {
        padding: 1.5rem;
        border-bottom: 1px solid #f0f0f0;
        background: #fafbfc;
    }

    .stats-body {
        padding: 1.5rem;
    }

    .stat-item {
        display: flex;
        align-items: center;
        gap: 1rem;
        padding: 1rem 0;
        border-bottom: 1px solid #f0f0f0;
    }

    .stat-item:last-child {
        border-bottom: none;
    }

    .stat-icon {
        width: 50px;
        height: 50px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 1.2rem;
    }

    .stat-value {
        font-size: 1.5rem;
        font-weight: 700;
        color: #2c3e50;
    }

    .stat-label {
        font-size: 0.9rem;
        color: #6c757d;
    }

    /* Activity Summary */
    .user-activity-summary {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        border: 1px solid #f0f0f0;
        overflow: hidden;
        height: 100%;
    }

    .summary-header {
        padding: 1.5rem;
        border-bottom: 1px solid #f0f0f0;
        background: #fafbfc;
    }

    .summary-body {
        padding: 1.5rem;
    }

    .summary-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 1rem 0;
        border-bottom: 1px solid #f0f0f0;
    }

    .summary-item:last-child {
        border-bottom: none;
    }

    .summary-label {
        font-size: 0.9rem;
        color: #6c757d;
    }

    .summary-value {
        font-size: 1.2rem;
        font-weight: 600;
        color: #2c3e50;
    }

    /* Engagement Card */
    .user-engagement-card {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        border: 1px solid #f0f0f0;
        overflow: hidden;
        height: 100%;
    }

    .engagement-header {
        padding: 1.5rem;
        border-bottom: 1px solid #f0f0f0;
        background: #fafbfc;
    }

    .engagement-body {
        padding: 1.5rem;
    }

    .engagement-metric {
        margin-bottom: 1.5rem;
    }

    .engagement-metric:last-child {
        margin-bottom: 0;
    }

    .metric-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 0.5rem;
    }

    .metric-label {
        font-size: 0.9rem;
        color: #6c757d;
        font-weight: 500;
    }

    .metric-value {
        font-size: 1rem;
        font-weight: 600;
        color: #2c3e50;
    }

    .metric-progress {
        height: 8px;
        background: #f0f0f0;
        border-radius: 4px;
        overflow: hidden;
    }

    .metric-progress .progress-bar {
        height: 100%;
        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
        border-radius: 4px;
        transition: width 0.3s ease;
    }

    /* Timeline Card */
    .user-timeline-card {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        border: 1px solid #f0f0f0;
        overflow: hidden;
        height: 100%;
    }

    .timeline-header {
        padding: 1.5rem;
        border-bottom: 1px solid #f0f0f0;
        background: #fafbfc;
    }

    .timeline-body {
        padding: 1.5rem;
        max-height: 400px;
        overflow-y: auto;
    }

    .timeline-container {
        position: relative;
    }

    .timeline-item {
        display: flex;
        align-items: flex-start;
        gap: 1rem;
        margin-bottom: 1.5rem;
        position: relative;
    }

    .timeline-item:last-child {
        margin-bottom: 0;
    }

    .timeline-item::before {
        content: '';
        position: absolute;
        left: 25px;
        top: 50px;
        width: 2px;
        height: calc(100% + 1.5rem);
        background: #e9ecef;
        z-index: 0;
    }

    .timeline-item:last-child::before {
        display: none;
    }

    .timeline-icon {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 1.2rem;
        flex-shrink: 0;
        position: relative;
        z-index: 1;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    .timeline-content {
        flex: 1;
        background: #f8f9fa;
        border-radius: 12px;
        padding: 1rem;
        border-left: 4px solid #667eea;
        position: relative;
    }

    .timeline-title {
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 0.5rem;
        font-size: 0.95rem;
    }

    .timeline-text {
        color: #6c757d;
        font-size: 0.9rem;
        margin-bottom: 0.5rem;
        line-height: 1.4;
    }

    .timeline-time {
        font-size: 0.8rem;
        color: #adb5bd;
        font-style: italic;
    }

    /* Filters Panel */
    .user-filters-panel {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        border: 1px solid #f0f0f0;
        margin-bottom: 2rem;
        overflow: hidden;
    }

    .filters-header {
        padding: 1rem 1.5rem;
        border-bottom: 1px solid #f0f0f0;
        background: #fafbfc;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .filters-body {
        padding: 1.5rem;
    }

    .filters-actions {
        display: flex;
        gap: 1rem;
    }

    /* View Management */
    .user-view {
        animation: fadeIn 0.3s ease;
    }

    .user-view.d-none {
        display: none !important;
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    /* Responsive Design */
    @media (max-width: 768px) {
        .header-content {
            flex-direction: column;
            gap: 1rem;
        }

        .header-controls {
            width: 100%;
            justify-content: center;
        }

        .header-controls .btn-group {
            flex-wrap: wrap;
        }

        .user-overview-card {
            flex-direction: column;
            text-align: center;
        }

        .chart-header {
            flex-direction: column;
            gap: 1rem;
            align-items: flex-start;
        }
    }
</style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script src="https://cdn.jsdelivr.net/npm/apexcharts@latest"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // User data from backend
    const userStats = <?php echo json_encode($userStats ?? [], 15, 512) ?>;
    const userActivityTrends = <?php echo json_encode($userActivityTrends ?? [], 15, 512) ?>;
    const userSegmentation = <?php echo json_encode($userSegmentation ?? [], 15, 512) ?>;
    const userEngagementMetrics = <?php echo json_encode($userEngagementMetrics ?? [], 15, 512) ?>;
    const recentUserActivities = <?php echo json_encode($recentUserActivities ?? [], 15, 512) ?>;

    // Initialize the page
    initUserAnalytics();

    function initUserAnalytics() {
        // Initialize view management
        initViewManagement();

        // Initialize charts
        initOverviewChart();
        initActivityChart();
        initRolesChart();
        initActivitySegmentChart();

        // Initialize timeline
        initUserTimeline();

        // Calculate and display summary metrics
        calculateSummaryMetrics();
    }

    function initViewManagement() {
        // Handle view switching
        document.querySelectorAll('[data-user-view]').forEach(button => {
            button.addEventListener('click', function() {
                const viewType = this.getAttribute('data-user-view');
                switchUserView(viewType);

                // Update active button
                document.querySelectorAll('[data-user-view]').forEach(btn => btn.classList.remove('active'));
                this.classList.add('active');
            });
        });
    }

    function switchUserView(viewType) {
        // Hide all views
        document.querySelectorAll('.user-view').forEach(view => {
            view.classList.add('d-none');
        });

        // Show selected view
        const targetView = document.getElementById(viewType + '-view');
        if (targetView) {
            targetView.classList.remove('d-none');
        }
    }

    function initOverviewChart() {
        const options = {
            series: [{
                name: 'کاربران',
                data: [
                    userStats.total_users || 0,
                    userStats.active_users || 0,
                    userStats.new_users || 0,
                    userStats.recent_logins || 0
                ]
            }],
            chart: {
                type: 'bar',
                height: 350,
                fontFamily: 'IRANSans, tahoma, sans-serif',
                toolbar: {
                    show: false
                }
            },
            plotOptions: {
                bar: {
                    horizontal: false,
                    columnWidth: '55%',
                    endingShape: 'rounded',
                    distributed: true
                }
            },
            dataLabels: {
                enabled: true,
                style: {
                    colors: ['#fff']
                }
            },
            stroke: {
                show: true,
                width: 2,
                colors: ['transparent']
            },
            xaxis: {
                categories: ['کل کاربران', 'کاربران فعال', 'کاربران جدید', 'ورود اخیر'],
                labels: {
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            yaxis: {
                title: {
                    text: 'تعداد',
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            fill: {
                opacity: 1
            },
            colors: ['#667eea', '#28a745', '#17a2b8', '#ffc107'],
            tooltip: {
                y: {
                    formatter: function (val) {
                        return val + " کاربر"
                    }
                }
            }
        };

        const chart = new ApexCharts(document.querySelector("#overview-chart"), options);
        chart.render();
        window.overviewChart = chart;
    }

    function initActivityChart() {
        const dates = userActivityTrends.dates || [];
        const registrations = userActivityTrends.registrations || [];
        const logins = userActivityTrends.logins || [];

        const options = {
            series: [{
                name: 'ثبت‌نام‌های جدید',
                data: registrations
            }, {
                name: 'ورود کاربران',
                data: logins
            }],
            chart: {
                type: 'area',
                height: 350,
                fontFamily: 'IRANSans, tahoma, sans-serif',
                toolbar: {
                    show: false
                }
            },
            dataLabels: {
                enabled: false
            },
            stroke: {
                curve: 'smooth',
                width: 3
            },
            xaxis: {
                categories: dates,
                labels: {
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            yaxis: {
                title: {
                    text: 'تعداد',
                    style: {
                        fontFamily: 'IRANSans, tahoma, sans-serif'
                    }
                }
            },
            fill: {
                type: 'gradient',
                gradient: {
                    shadeIntensity: 1,
                    opacityFrom: 0.7,
                    opacityTo: 0.3,
                    stops: [0, 90, 100]
                }
            },
            colors: ['#667eea', '#28a745'],
            tooltip: {
                y: {
                    formatter: function (val) {
                        return val + " کاربر"
                    }
                }
            }
        };

        const chart = new ApexCharts(document.querySelector("#activity-chart"), options);
        chart.render();
        window.activityChart = chart;
    }

    function initRolesChart() {
        const rolesData = userSegmentation.roles || {};
        const labels = rolesData.labels || [];
        const data = rolesData.data || [];

        const options = {
            series: data,
            chart: {
                type: 'donut',
                height: 350,
                fontFamily: 'IRANSans, tahoma, sans-serif'
            },
            labels: labels,
            colors: ['#667eea', '#28a745', '#17a2b8', '#ffc107'],
            plotOptions: {
                pie: {
                    donut: {
                        size: '70%'
                    }
                }
            },
            legend: {
                position: 'bottom',
                fontFamily: 'IRANSans, tahoma, sans-serif'
            },
            tooltip: {
                y: {
                    formatter: function (val) {
                        return val + " کاربر"
                    }
                }
            }
        };

        const chart = new ApexCharts(document.querySelector("#roles-chart"), options);
        chart.render();
        window.rolesChart = chart;
    }

    function initActivitySegmentChart() {
        const activityData = userSegmentation.activity || {};
        const labels = activityData.labels || ['بسیار فعال', 'فعال', 'گاه‌به‌گاه', 'غیرفعال'];
        const data = activityData.data || [0, 0, 0, 0];

        const options = {
            series: data,
            chart: {
                type: 'donut',
                height: 350,
                fontFamily: 'IRANSans, tahoma, sans-serif'
            },
            labels: labels,
            colors: ['#28a745', '#667eea', '#ffc107', '#dc3545'],
            plotOptions: {
                pie: {
                    donut: {
                        size: '70%'
                    }
                }
            },
            legend: {
                position: 'bottom',
                fontFamily: 'IRANSans, tahoma, sans-serif'
            },
            tooltip: {
                y: {
                    formatter: function (val) {
                        return val + " کاربر"
                    }
                }
            }
        };

        const chart = new ApexCharts(document.querySelector("#activity-segment-chart"), options);
        chart.render();
        window.activitySegmentChart = chart;
    }

    function initUserTimeline() {
        const timelineContainer = document.getElementById('user-timeline');
        if (!timelineContainer) return;

        let timelineHTML = '';

        if (recentUserActivities && recentUserActivities.length > 0) {
            recentUserActivities.forEach((activity, index) => {
                const iconClass = getActivityIcon(activity.type);
                const colorClass = getActivityColor(activity.type);

                timelineHTML += `
                    <div class="timeline-item">
                        <div class="timeline-icon bg-${colorClass}">
                            <i class="fas fa-${iconClass}"></i>
                        </div>
                        <div class="timeline-content">
                            <div class="timeline-title">${activity.title || 'فعالیت کاربر'}</div>
                            <div class="timeline-text">
                                کاربر <strong>${activity.user_name}</strong>
                                ${getActivityText(activity)}
                            </div>
                            <div class="timeline-time">${activity.time_diff || 'اکنون'}</div>
                        </div>
                    </div>
                `;
            });
        } else {
            timelineHTML = '<div class="text-center text-muted p-3">هیچ فعالیت اخیری یافت نشد</div>';
        }

        timelineContainer.innerHTML = timelineHTML;
    }

    function getActivityIcon(type) {
        const icons = {
            'registration': 'user-plus',
            'login': 'sign-in-alt',
            'rating': 'star',
            'comment': 'comment',
            'error': 'exclamation-triangle'
        };
        return icons[type] || 'user';
    }

    function getActivityColor(type) {
        const colors = {
            'registration': 'success',
            'login': 'primary',
            'rating': 'warning',
            'comment': 'info',
            'error': 'danger'
        };
        return colors[type] || 'secondary';
    }

    function getActivityText(activity) {
        switch(activity.type) {
            case 'registration':
                return 'در سیستم ثبت‌نام کرد';
            case 'login':
                return 'وارد سیستم شد';
            case 'rating':
                return `امتیاز ${activity.rating || 5} را ثبت کرد`;
            case 'comment':
                return 'یک نظر جدید ثبت کرد';
            case 'error':
                return 'با خطای احراز هویت مواجه شد';
            default:
                return 'فعالیتی انجام داد';
        }
    }

    function calculateSummaryMetrics() {
        const registrations = userActivityTrends.registrations || [];
        const logins = userActivityTrends.logins || [];

        if (registrations.length > 0) {
            const avgReg = Math.round(registrations.reduce((a, b) => a + b, 0) / registrations.length);
            const maxReg = Math.max(...registrations);
            document.getElementById('avg-registrations').textContent = avgReg;
            document.getElementById('max-registrations').textContent = maxReg;
        }

        if (logins.length > 0) {
            const avgLogin = Math.round(logins.reduce((a, b) => a + b, 0) / logins.length);
            const maxLogin = Math.max(...logins);
            document.getElementById('avg-logins').textContent = avgLogin;
            document.getElementById('max-logins').textContent = maxLogin;
        }
    }

    // Chart toggle functions
    window.toggleOverviewChart = function(type) {
        // Update chart based on type
        console.log('Toggling overview chart to:', type);
        // Implementation for different chart types
    };

    window.toggleActivityChart = function(type) {
        if (!window.activityChart) return;

        const registrations = userActivityTrends.registrations || [];
        const logins = userActivityTrends.logins || [];

        let newSeries = [];

        switch(type) {
            case 'registrations':
                newSeries = [{
                    name: 'ثبت‌نام‌های جدید',
                    data: registrations
                }];
                break;
            case 'logins':
                newSeries = [{
                    name: 'ورود کاربران',
                    data: logins
                }];
                break;
            case 'both':
            default:
                newSeries = [{
                    name: 'ثبت‌نام‌های جدید',
                    data: registrations
                }, {
                    name: 'ورود کاربران',
                    data: logins
                }];
                break;
        }

        window.activityChart.updateSeries(newSeries);

        // Update active button
        document.querySelectorAll('#activity-view .chart-actions .btn').forEach(btn => btn.classList.remove('active'));
        event.target.classList.add('active');
    };

    // Global functions for external use
    window.refreshUserData = function() {
        console.log('Refreshing user data...');
        showNotification('در حال بروزرسانی داده‌ها...', 'info');

        // Simulate refresh
        setTimeout(() => {
            location.reload();
        }, 1000);
    };

    window.exportUserData = function(format) {
        console.log('Exporting user data as:', format);
        showNotification(`در حال تهیه فایل ${format.toUpperCase()}...`, 'info');

        // Simulate export
        setTimeout(() => {
            showNotification(`فایل ${format.toUpperCase()} آماده دانلود است`, 'success');
        }, 2000);
    };

    window.showUserFilters = function() {
        const filtersPanel = document.getElementById('user-filters');
        if (filtersPanel) {
            filtersPanel.classList.remove('d-none');
        }
    };

    window.hideUserFilters = function() {
        const filtersPanel = document.getElementById('user-filters');
        if (filtersPanel) {
            filtersPanel.classList.add('d-none');
        }
    };

    window.applyUserFilters = function() {
        const dateRange = document.getElementById('user-date-range').value;
        const userType = document.getElementById('user-type-filter').value;
        const userRole = document.getElementById('user-role-filter').value;
        const minActivity = document.getElementById('user-min-activity').value;

        console.log('Applying filters:', { dateRange, userType, userRole, minActivity });
        showNotification('فیلترها اعمال شدند', 'success');

        // Hide filters panel
        hideUserFilters();

        // Simulate filter application
        setTimeout(() => {
            location.reload();
        }, 1000);
    };

    window.resetUserFilters = function() {
        document.getElementById('user-date-range').value = '30';
        document.getElementById('user-type-filter').value = 'all';
        document.getElementById('user-role-filter').value = 'all';
        document.getElementById('user-min-activity').value = '1';

        showNotification('فیلترها بازنشانی شدند', 'success');
    };

    function showNotification(message, type = 'info') {
        const alertClass = type === 'success' ? 'alert-success' :
                         type === 'error' ? 'alert-danger' : 'alert-info';

        const notification = document.createElement('div');
        notification.className = `alert ${alertClass} alert-dismissible fade show position-fixed`;
        notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
        notification.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;

        document.body.appendChild(notification);

        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 3000);
    }
});
</script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('admin.layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/aluirani/public_html/aludubai.ir/resources/views/admin/analytics/user_modern.blade.php ENDPATH**/ ?>