<div class="tab-pane fade" id="ratingAnalysis" role="tabpanel">
    <!-- Enhanced Header Section -->
    <div class="rating-header-section mb-4">
        <div class="row align-items-center">
            <div class="col-md-6">
                <div class="rating-title-wrapper">
                    <h4 class="rating-main-title">
                        <i class="fas fa-star text-warning me-2"></i>
                        تحلیل نظرات و امتیازات
                    </h4>
                    <p class="rating-subtitle text-muted mb-0">
                        بررسی و تحلیل امتیازات و نظرات کاربران در مکان‌های مختلف
                    </p>
                </div>
            </div>
            <div class="col-md-6">
                <div class="rating-controls d-flex justify-content-end">
                    <div class="btn-group rating-toggle-group me-2" role="group">
                        <button type="button" class="btn btn-outline-primary active" data-rating-chart="distribution">
                            <i class="fas fa-chart-bar me-1"></i>
                            توزیع امتیازات
                        </button>
                        <button type="button" class="btn btn-outline-primary" data-rating-chart="categories">
                            <i class="fas fa-layer-group me-1"></i>
                            بر اساس دسته‌بندی
                        </button>
                        <button type="button" class="btn btn-outline-primary" data-rating-chart="trends">
                            <i class="fas fa-chart-line me-1"></i>
                            روند زمانی
                        </button>
                        <button type="button" class="btn btn-outline-primary" data-rating-chart="sentiment">
                            <i class="fas fa-heart me-1"></i>
                            تحلیل احساسات
                        </button>
                    </div>
                    <div class="dropdown">
                        <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                            <i class="fas fa-tools me-1"></i>
                            ابزارها
                        </button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="#" onclick="refreshRatingData()">
                                <i class="fas fa-sync-alt me-2"></i>بروزرسانی داده‌ها
                            </a></li>
                            <li><a class="dropdown-item" href="#" onclick="exportRatingData('excel')">
                                <i class="fas fa-file-excel me-2"></i>خروجی Excel
                            </a></li>
                            <li><a class="dropdown-item" href="#" onclick="exportRatingData('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="showRatingFilters()">
                                <i class="fas fa-filter me-2"></i>فیلترهای پیشرفته
                            </a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Rating Overview Cards -->
    <div class="rating-overview-section mb-4">
        <div class="row">
            <div class="col-md-3">
                <div class="rating-overview-card">
                    <div class="card-icon bg-warning">
                        <i class="fas fa-star"></i>
                    </div>
                    <div class="card-content">
                        <?php
                            $totalRatings = 0;
                            $weightedSum = 0;
                            $average = 0;

                            if (!empty($ratingAnalytics['distribution']['data']) && !empty($ratingAnalytics['distribution']['labels'])) {
                                $totalRatings = array_sum($ratingAnalytics['distribution']['data']);
                                foreach ($ratingAnalytics['distribution']['labels'] as $index => $rating) {
                                    if (isset($ratingAnalytics['distribution']['data'][$index])) {
                                        $weightedSum += $rating * $ratingAnalytics['distribution']['data'][$index];
                                    }
                                }
                                $average = $totalRatings > 0 ? round($weightedSum / $totalRatings, 1) : 0;
                            }
                        ?>
                        <div class="card-value"><?php echo e($average); ?>/5</div>
                        <div class="card-label">میانگین امتیاز</div>
                        <div class="rating-stars-small">
                            <?php for($i = 1; $i <= 5; $i++): ?>
                                <i class="fas fa-star <?php echo e($i <= $average ? 'text-warning' : 'text-muted'); ?>"></i>
                            <?php endfor; ?>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="rating-overview-card">
                    <div class="card-icon bg-primary">
                        <i class="fas fa-comments"></i>
                    </div>
                    <div class="card-content">
                        <div class="card-value"><?php echo e(number_format($totalRatings)); ?></div>
                        <div class="card-label">کل نظرات</div>
                        <div class="card-trend positive">
                            <i class="fas fa-arrow-up me-1"></i>
                            +12% این ماه
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="rating-overview-card">
                    <div class="card-icon bg-success">
                        <i class="fas fa-thumbs-up"></i>
                    </div>
                    <div class="card-content">
                        <?php
                            $positiveRatings = 0;
                            if (!empty($ratingAnalytics['distribution']['labels']) && !empty($ratingAnalytics['distribution']['data'])) {
                                foreach ($ratingAnalytics['distribution']['labels'] as $index => $rating) {
                                    if ($rating >= 4 && isset($ratingAnalytics['distribution']['data'][$index])) {
                                        $positiveRatings += $ratingAnalytics['distribution']['data'][$index];
                                    }
                                }
                            }
                            $positivePercent = $totalRatings > 0 ? round(($positiveRatings / $totalRatings) * 100, 1) : 0;
                        ?>
                        <div class="card-value"><?php echo e($positivePercent); ?>%</div>
                        <div class="card-label">نظرات مثبت</div>
                        <div class="card-detail"><?php echo e(number_format($positiveRatings)); ?> نظر</div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="rating-overview-card">
                    <div class="card-icon bg-info">
                        <i class="fas fa-chart-pie"></i>
                    </div>
                    <div class="card-content">
                        <?php
                            $mostCommonRating = 'نامشخص';
                            $mostCommonCount = 0;

                            if (!empty($ratingAnalytics['distribution']['data']) && !empty($ratingAnalytics['distribution']['labels'])) {
                                $maxValue = max($ratingAnalytics['distribution']['data']);
                                $maxRatingIndex = array_keys($ratingAnalytics['distribution']['data'], $maxValue)[0];
                                $mostCommonRating = $ratingAnalytics['distribution']['labels'][$maxRatingIndex];
                                $mostCommonCount = $ratingAnalytics['distribution']['data'][$maxRatingIndex];
                            }
                        ?>
                        <div class="card-value"><?php echo e($mostCommonRating); ?> ستاره</div>
                        <div class="card-label">رایج‌ترین امتیاز</div>
                        <div class="card-detail"><?php echo e(number_format($mostCommonCount)); ?> نظر</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Charts Section -->
    <div class="row">
        <!-- Rating Distribution Chart -->
        <div class="col-lg-8 rating-chart" id="ratingDistribution">
            <div class="card rating-chart-card">
                <div class="card-header bg-gradient-warning text-white">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="card-title mb-0 text-white">
                            <i class="fas fa-chart-bar me-2"></i>
                            نمودار توزیع امتیازات
                        </h5>
                        <div class="chart-actions">
                            <button class="btn btn-sm btn-outline-light" onclick="refreshChart('distribution')" title="بروزرسانی">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-light" onclick="fullscreenChart('ratingDistributionChart')" title="تمام صفحه">
                                <i class="fas fa-expand"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-light" onclick="downloadChart('ratingDistributionChart')" title="دانلود">
                                <i class="fas fa-download"></i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="chart-container position-relative">
                        <div class="chart-loading d-none">
                            <div class="d-flex justify-content-center align-items-center h-100">
                                <div class="spinner-border text-warning" role="status">
                                    <span class="visually-hidden">در حال بارگذاری...</span>
                                </div>
                            </div>
                        </div>
                        <div id="ratingDistributionChart"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Rating Statistics Panel -->
        <div class="col-lg-4 rating-chart" id="ratingStats">
            <div class="card rating-stats-card">
                <div class="card-header bg-gradient-primary text-white">
                    <h5 class="card-title mb-0 text-white">
                        <i class="fas fa-chart-pie me-2"></i>
                        آمار تفصیلی امتیازات
                    </h5>
                </div>
                <div class="card-body">
                    <!-- Main Rating Display -->
                    <div class="main-rating-display text-center mb-4">
                        <div class="rating-circle">
                            <div class="rating-value"><?php echo e($average); ?></div>
                            <div class="rating-max">/5</div>
                        </div>
                        <div class="rating-description">
                            <div class="rating-label">میانگین امتیاز</div>
                            <div class="rating-count">از <?php echo e(number_format($totalRatings)); ?> نظر</div>
                        </div>
                        <div class="rating-stars-display">
                            <?php for($i = 1; $i <= 5; $i++): ?>
                                <i class="fas fa-star <?php echo e($i <= $average ? 'text-warning' : 'text-muted'); ?>"></i>
                            <?php endfor; ?>
                        </div>
                    </div>

                    <!-- Rating Breakdown -->
                    <div class="rating-breakdown-section">
                        <h6 class="breakdown-title">توزیع امتیازات</h6>
                        <div class="rating-breakdown-list">
                            <?php $__currentLoopData = $ratingAnalytics['distribution']['labels']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $rating): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <?php
                                    $count = $ratingAnalytics['distribution']['data'][$index];
                                    $percent = $totalRatings > 0 ? ($count / $totalRatings) * 100 : 0;
                                    $starColor = $rating >= 4 ? 'text-success' : ($rating >= 3 ? 'text-warning' : 'text-danger');
                                ?>
                                <div class="rating-breakdown-item">
                                    <div class="d-flex align-items-center justify-content-between mb-2">
                                        <div class="rating-star-label">
                                            <span class="star-number"><?php echo e($rating); ?></span>
                                            <i class="fas fa-star <?php echo e($starColor); ?>"></i>
                                        </div>
                                        <div class="rating-stats">
                                            <span class="rating-count-badge"><?php echo e(number_format($count)); ?></span>
                                            <span class="rating-percent"><?php echo e(round($percent, 1)); ?>%</span>
                                        </div>
                                    </div>
                                    <div class="rating-progress-wrapper">
                                        <div class="progress rating-progress" style="height: 6px;">
                                            <div class="progress-bar <?php echo e($rating >= 4 ? 'bg-success' : ($rating >= 3 ? 'bg-warning' : 'bg-danger')); ?>"
                                                 role="progressbar"
                                                 style="width: <?php echo e($percent); ?>%"
                                                 aria-valuenow="<?php echo e($percent); ?>"
                                                 aria-valuemin="0"
                                                 aria-valuemax="100">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </div>
                    </div>

                    <!-- Rating Insights -->
                    <div class="rating-insights mt-4">
                        <h6 class="insights-title">تحلیل سریع</h6>
                        <div class="insights-grid">
                            <div class="insight-item">
                                <div class="insight-icon bg-success">
                                    <i class="fas fa-thumbs-up"></i>
                                </div>
                                <div class="insight-content">
                                    <div class="insight-value"><?php echo e($positivePercent); ?>%</div>
                                    <div class="insight-label">مثبت</div>
                                </div>
                            </div>
                            <div class="insight-item">
                                <div class="insight-icon bg-warning">
                                    <i class="fas fa-meh"></i>
                                </div>
                                <div class="insight-content">
                                    <?php
                                        $neutralRatings = 0;
                                        foreach ($ratingAnalytics['distribution']['labels'] as $index => $rating) {
                                            if ($rating == 3) {
                                                $neutralRatings += $ratingAnalytics['distribution']['data'][$index];
                                            }
                                        }
                                        $neutralPercent = $totalRatings > 0 ? round(($neutralRatings / $totalRatings) * 100, 1) : 0;
                                    ?>
                                    <div class="insight-value"><?php echo e($neutralPercent); ?>%</div>
                                    <div class="insight-label">خنثی</div>
                                </div>
                            </div>
                            <div class="insight-item">
                                <div class="insight-icon bg-danger">
                                    <i class="fas fa-thumbs-down"></i>
                                </div>
                                <div class="insight-content">
                                    <?php
                                        $negativePercent = 100 - $positivePercent - $neutralPercent;
                                    ?>
                                    <div class="insight-value"><?php echo e($negativePercent); ?>%</div>
                                    <div class="insight-label">منفی</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Ratings by Category Chart (hidden initially) -->
        <div class="col-12 rating-chart" id="ratingByCategories" style="display: none;">
            <div class="card rating-chart-card">
                <div class="card-header bg-gradient-success text-white">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="card-title mb-0 text-white">
                            <i class="fas fa-layer-group me-2"></i>
                            امتیازات بر اساس دسته‌بندی
                        </h5>
                        <div class="chart-actions">
                            <button class="btn btn-sm btn-outline-light" onclick="refreshChart('categories')" title="بروزرسانی">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-light" onclick="fullscreenChart('ratingByCategoriesChart')" title="تمام صفحه">
                                <i class="fas fa-expand"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-light" onclick="downloadChart('ratingByCategoriesChart')" title="دانلود">
                                <i class="fas fa-download"></i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="chart-container position-relative">
                        <div class="chart-loading d-none">
                            <div class="d-flex justify-content-center align-items-center h-100">
                                <div class="spinner-border text-success" role="status">
                                    <span class="visually-hidden">در حال بارگذاری...</span>
                                </div>
                            </div>
                        </div>
                        <div id="ratingByCategoriesChart"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Rating Trends Chart (hidden initially) -->
        <div class="col-12 rating-chart" id="ratingTrends" style="display: none;">
            <div class="card rating-chart-card">
                <div class="card-header bg-gradient-info text-white">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="card-title mb-0 text-white">
                            <i class="fas fa-chart-line me-2"></i>
                            روند زمانی امتیازات
                        </h5>
                        <div class="chart-actions">
                            <button class="btn btn-sm btn-outline-light" onclick="refreshChart('trends')" title="بروزرسانی">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-light" onclick="fullscreenChart('ratingTrendsChart')" title="تمام صفحه">
                                <i class="fas fa-expand"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-light" onclick="downloadChart('ratingTrendsChart')" title="دانلود">
                                <i class="fas fa-download"></i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="chart-container position-relative">
                        <div class="chart-loading d-none">
                            <div class="d-flex justify-content-center align-items-center h-100">
                                <div class="spinner-border text-info" role="status">
                                    <span class="visually-hidden">در حال بارگذاری...</span>
                                </div>
                            </div>
                        </div>
                        <div id="ratingTrendsChart"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Sentiment Analysis Chart (hidden initially) -->
        <div class="col-12 rating-chart" id="ratingSentiment" style="display: none;">
            <div class="card rating-chart-card">
                <div class="card-header bg-gradient-danger text-white">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="card-title mb-0 text-white">
                            <i class="fas fa-heart me-2"></i>
                            تحلیل احساسات نظرات
                        </h5>
                        <div class="chart-actions">
                            <button class="btn btn-sm btn-outline-light" onclick="refreshChart('sentiment')" title="بروزرسانی">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-light" onclick="fullscreenChart('ratingSentimentChart')" title="تمام صفحه">
                                <i class="fas fa-expand"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-light" onclick="downloadChart('ratingSentimentChart')" title="دانلود">
                                <i class="fas fa-download"></i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-8">
                            <div class="chart-container position-relative">
                                <div class="chart-loading d-none">
                                    <div class="d-flex justify-content-center align-items-center h-100">
                                        <div class="spinner-border text-danger" role="status">
                                            <span class="visually-hidden">در حال بارگذاری...</span>
                                        </div>
                                    </div>
                                </div>
                                <div id="ratingSentimentChart"></div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="sentiment-summary">
                                <h6 class="sentiment-title">خلاصه تحلیل احساسات</h6>
                                <div class="sentiment-items">
                                    <div class="sentiment-item positive">
                                        <div class="sentiment-icon">
                                            <i class="fas fa-smile"></i>
                                        </div>
                                        <div class="sentiment-content">
                                            <div class="sentiment-label">مثبت</div>
                                            <div class="sentiment-value"><?php echo e($positivePercent); ?>%</div>
                                            <div class="sentiment-count"><?php echo e(number_format($positiveRatings)); ?> نظر</div>
                                        </div>
                                    </div>
                                    <div class="sentiment-item neutral">
                                        <div class="sentiment-icon">
                                            <i class="fas fa-meh"></i>
                                        </div>
                                        <div class="sentiment-content">
                                            <div class="sentiment-label">خنثی</div>
                                            <div class="sentiment-value"><?php echo e($neutralPercent); ?>%</div>
                                            <div class="sentiment-count"><?php echo e(number_format($neutralRatings)); ?> نظر</div>
                                        </div>
                                    </div>
                                    <div class="sentiment-item negative">
                                        <div class="sentiment-icon">
                                            <i class="fas fa-frown"></i>
                                        </div>
                                        <div class="sentiment-content">
                                            <div class="sentiment-label">منفی</div>
                                            <div class="sentiment-value"><?php echo e($negativePercent); ?>%</div>
                                            <div class="sentiment-count"><?php echo e(number_format($totalRatings - $positiveRatings - $neutralRatings)); ?> نظر</div>
                                        </div>
                                    </div>
                                </div>

                                <div class="sentiment-insights mt-4">
                                    <h6 class="insights-subtitle">نکات کلیدی</h6>
                                    <div class="insight-list">
                                        <?php if($positivePercent > 70): ?>
                                            <div class="insight-point success">
                                                <i class="fas fa-check-circle me-2"></i>
                                                رضایت بالای کاربران
                                            </div>
                                        <?php endif; ?>
                                        <?php if($negativePercent > 20): ?>
                                            <div class="insight-point warning">
                                                <i class="fas fa-exclamation-triangle me-2"></i>
                                                نیاز به بهبود کیفیت
                                            </div>
                                        <?php endif; ?>
                                        <div class="insight-point info">
                                            <i class="fas fa-info-circle me-2"></i>
                                            میانگین صنعت: 4.2/5
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Top Rated Locations Section -->
    <div class="top-rated-section mt-4">
        <div class="card rating-top-locations-card">
            <div class="card-header bg-gradient-secondary text-white">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0 text-white">
                        <i class="fas fa-trophy me-2"></i>
                        مکان‌های برتر بر اساس امتیاز
                    </h5>
                    <div class="top-rated-actions">
                        <button class="btn btn-sm btn-outline-light" onclick="sortTopRated('rating')" title="مرتب‌سازی بر اساس امتیاز">
                            <i class="fas fa-sort-amount-down"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-light" onclick="sortTopRated('count')" title="مرتب‌سازی بر اساس تعداد نظرات">
                            <i class="fas fa-sort-numeric-down"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-light" onclick="exportTopRated()" title="خروجی Excel">
                            <i class="fas fa-file-excel"></i>
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="top-rated-list">
                    <?php $__empty_1 = true; $__currentLoopData = $ratingAnalytics['topRated']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $location): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                        <div class="top-rated-item <?php echo e($index < 3 ? 'top-three' : ''); ?>">
                            <div class="d-flex align-items-center p-3">
                                <!-- Rank Badge -->
                                <div class="rank-badge <?php echo e($index == 0 ? 'gold' : ($index == 1 ? 'silver' : ($index == 2 ? 'bronze' : 'regular'))); ?>">
                                    <?php if($index < 3): ?>
                                        <i class="fas fa-<?php echo e($index == 0 ? 'crown' : ($index == 1 ? 'medal' : 'award')); ?>"></i>
                                    <?php else: ?>
                                        <span><?php echo e($index + 1); ?></span>
                                    <?php endif; ?>
                                </div>

                                <!-- Location Info -->
                                <div class="location-info flex-grow-1 ms-3">
                                    <div class="location-name"><?php echo e($location->title); ?></div>
                                    <div class="location-category">
                                        <span class="category-badge"><?php echo e($location->category_fa); ?></span>
                                    </div>
                                </div>

                                <!-- Rating Display -->
                                <div class="rating-display text-center me-3">
                                    <div class="rating-value-large"><?php echo e(number_format($location->avg_rating, 1)); ?></div>
                                    <div class="rating-stars-row">
                                        <?php for($i = 1; $i <= 5; $i++): ?>
                                            <i class="fas fa-star <?php echo e($i <= $location->avg_rating ? 'text-warning' : 'text-muted'); ?>"></i>
                                        <?php endfor; ?>
                                    </div>
                                    <div class="rating-count-small"><?php echo e(number_format($location->ratings_count)); ?> نظر</div>
                                </div>

                                <!-- Progress Bar -->
                                <div class="rating-progress-section me-3">
                                    <div class="progress vertical-progress">
                                        <div class="progress-bar bg-warning"
                                             role="progressbar"
                                             style="height: <?php echo e(($location->avg_rating / 5) * 100); ?>%"
                                             aria-valuenow="<?php echo e($location->avg_rating); ?>"
                                             aria-valuemin="0"
                                             aria-valuemax="5">
                                        </div>
                                    </div>
                                </div>

                                <!-- Actions -->
                                <div class="location-actions">
                                    <div class="btn-group-vertical">
                                        <a href="<?php echo e(route('admin.locations.show', $location->id)); ?>"
                                           class="btn btn-sm btn-outline-primary"
                                           title="مشاهده جزئیات">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <button class="btn btn-sm btn-outline-success"
                                                onclick="viewLocationRatings(<?php echo e($location->id); ?>)"
                                                title="مشاهده نظرات">
                                            <i class="fas fa-comments"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <!-- Additional Stats -->
                            <?php if($index < 3): ?>
                                <div class="additional-stats px-3 pb-3">
                                    <div class="row text-center">
                                        <div class="col-4">
                                            <div class="stat-mini">
                                                <div class="stat-mini-value"><?php echo e(number_format($location->ratings_count)); ?></div>
                                                <div class="stat-mini-label">نظرات</div>
                                            </div>
                                        </div>
                                        <div class="col-4">
                                            <div class="stat-mini">
                                                <div class="stat-mini-value"><?php echo e(number_format($location->avg_rating, 1)); ?></div>
                                                <div class="stat-mini-label">امتیاز</div>
                                            </div>
                                        </div>
                                        <div class="col-4">
                                            <div class="stat-mini">
                                                <div class="stat-mini-value"><?php echo e($index + 1); ?></div>
                                                <div class="stat-mini-label">رتبه</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                        <div class="empty-state text-center py-5">
                            <i class="fas fa-star-half-alt text-muted" style="font-size: 3rem;"></i>
                            <h6 class="mt-3 text-muted">هیچ داده‌ای برای نمایش وجود ندارد</h6>
                            <p class="text-muted">هنوز هیچ مکانی امتیاز دریافت نکرده است</p>
                        </div>
                    <?php endif; ?>
                </div>

                <?php if(count($ratingAnalytics['topRated']) > 0): ?>
                    <!-- Summary Footer -->
                    <div class="top-rated-summary p-3 bg-light border-top">
                        <div class="row text-center">
                            <div class="col-3">
                                <div class="summary-stat">
                                    <?php
                                        $avgRating = !empty($ratingAnalytics['topRated']) ? collect($ratingAnalytics['topRated'])->avg('avg_rating') : 0;
                                    ?>
                                    <div class="summary-value text-warning"><?php echo e(number_format($avgRating, 1)); ?></div>
                                    <div class="summary-label">میانگین کل</div>
                                </div>
                            </div>
                            <div class="col-3">
                                <div class="summary-stat">
                                    <?php
                                        $totalRatingsCount = !empty($ratingAnalytics['topRated']) ? collect($ratingAnalytics['topRated'])->sum('ratings_count') : 0;
                                    ?>
                                    <div class="summary-value text-primary"><?php echo e(number_format($totalRatingsCount)); ?></div>
                                    <div class="summary-label">کل نظرات</div>
                                </div>
                            </div>
                            <div class="col-3">
                                <div class="summary-stat">
                                    <?php
                                        $maxRating = !empty($ratingAnalytics['topRated']) ? collect($ratingAnalytics['topRated'])->max('avg_rating') : 0;
                                    ?>
                                    <div class="summary-value text-success"><?php echo e(number_format($maxRating, 1)); ?></div>
                                    <div class="summary-label">بالاترین امتیاز</div>
                                </div>
                            </div>
                            <div class="col-3">
                                <div class="summary-stat">
                                    <div class="summary-value text-info"><?php echo e(count($ratingAnalytics['topRated'])); ?></div>
                                    <div class="summary-label">تعداد مکان‌ها</div>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Enhanced Rating Distribution Chart
        const ratingDistOptions = {
            series: [{
                name: 'تعداد نظرات',
                data: <?php echo json_encode($ratingAnalytics['distribution']['data'], 15, 512) ?>
            }],
            chart: {
                height: 400,
                type: 'bar',
                fontFamily: 'Vazirmatn, IRANSans, tahoma, sans-serif',
                animations: {
                    enabled: true,
                    easing: 'easeinout',
                    speed: 800,
                    animateGradually: {
                        enabled: true,
                        delay: 150
                    }
                },
                toolbar: {
                    show: true,
                    tools: {
                        download: true,
                        selection: false,
                        zoom: false,
                        zoomin: false,
                        zoomout: false,
                        pan: false,
                        reset: false
                    }
                },
                background: 'transparent'
            },
            plotOptions: {
                bar: {
                    borderRadius: 8,
                    horizontal: false,
                    columnWidth: '60%',
                    distributed: true,
                    dataLabels: {
                        position: 'top'
                    }
                }
            },
            fill: {
                type: 'gradient',
                gradient: {
                    shade: 'light',
                    type: 'vertical',
                    shadeIntensity: 0.25,
                    gradientToColors: ['#ffc107', '#fd7e14', '#dc3545', '#28a745', '#17a2b8'],
                    inverseColors: false,
                    opacityFrom: 0.85,
                    opacityTo: 0.55,
                    stops: [50, 0, 100]
                }
            },
            dataLabels: {
                enabled: true,
                formatter: function (val) {
                    return val;
                },
                offsetY: -20,
                style: {
                    fontSize: '12px',
                    fontWeight: 'bold',
                    colors: ['#304758']
                }
            },
            legend: {
                show: false
            },
            xaxis: {
                categories: <?php echo json_encode($ratingAnalytics['distribution']['labels'], 15, 512) ?>,
                labels: {
                    style: {
                        fontSize: '12px',
                        fontWeight: 500,
                        colors: '#6c757d'
                    }
                },
                title: {
                    text: 'امتیاز (ستاره)',
                    style: {
                        fontSize: '12px',
                        fontWeight: 600,
                        color: '#6c757d'
                    }
                },
                axisBorder: {
                    show: true,
                    color: '#e0e6ed'
                },
                axisTicks: {
                    show: true,
                    color: '#e0e6ed'
                }
            },
            yaxis: {
                labels: {
                    style: {
                        fontSize: '11px',
                        fontWeight: 500,
                        colors: '#6c757d'
                    }
                },
                title: {
                    text: 'تعداد نظرات',
                    style: {
                        fontSize: '12px',
                        fontWeight: 600,
                        color: '#6c757d'
                    }
                }
            },
            colors: ['#dc3545', '#fd7e14', '#ffc107', '#28a745', '#17a2b8'],
            grid: {
                borderColor: '#f1f3fa',
                strokeDashArray: 3,
                xaxis: {
                    lines: {
                        show: true
                    }
                },
                yaxis: {
                    lines: {
                        show: true
                    }
                }
            },
            tooltip: {
                theme: 'light',
                style: {
                    fontSize: '12px'
                },
                y: {
                    formatter: function (val, opts) {
                        const rating = opts.w.globals.categoryLabels[opts.dataPointIndex];
                        return val + ' نظر با امتیاز ' + rating + ' ستاره';
                    }
                }
            }
        };

        const ratingDistChart = new ApexCharts(document.querySelector("#ratingDistributionChart"), ratingDistOptions);
        ratingDistChart.render();

        // Enhanced Rating By Categories Chart
        const ratingCategoryOptions = {
            series: [{
                name: 'میانگین امتیاز',
                data: <?php echo json_encode($ratingAnalytics['byCategory']['data'], 15, 512) ?>
            }],
            chart: {
                height: 400,
                type: 'bar',
                fontFamily: 'Vazirmatn, IRANSans, tahoma, sans-serif',
                animations: {
                    enabled: true,
                    easing: 'easeinout',
                    speed: 800
                },
                toolbar: {
                    show: true,
                    tools: {
                        download: true,
                        selection: false,
                        zoom: false,
                        zoomin: false,
                        zoomout: false,
                        pan: false,
                        reset: false
                    }
                },
                background: 'transparent'
            },
            plotOptions: {
                bar: {
                    borderRadius: 8,
                    horizontal: true,
                    distributed: true,
                    dataLabels: {
                        position: 'center'
                    },
                    barHeight: '70%'
                }
            },
            fill: {
                type: 'gradient',
                gradient: {
                    shade: 'light',
                    type: 'horizontal',
                    shadeIntensity: 0.25,
                    gradientToColors: undefined,
                    inverseColors: false,
                    opacityFrom: 0.85,
                    opacityTo: 0.55,
                    stops: [50, 0, 100]
                }
            },
            colors: ['#28a745', '#17a2b8', '#ffc107', '#fd7e14', '#dc3545'],
            dataLabels: {
                enabled: true,
                formatter: function (val) {
                    return val.toFixed(1) + '/5';
                },
                style: {
                    fontSize: '12px',
                    fontWeight: 'bold',
                    colors: ['#fff']
                }
            },
            legend: {
                show: false
            },
            annotations: {
                xaxis: [{
                    x: 4,
                    strokeDashArray: 5,
                    borderColor: '#28a745',
                    label: {
                        borderColor: '#28a745',
                        style: {
                            color: '#fff',
                            background: '#28a745'
                        },
                        text: 'هدف: 4.0'
                    }
                }]
            },
            tooltip: {
                theme: 'light',
                style: {
                    fontSize: '12px'
                },
                y: {
                    formatter: function (val) {
                        return val.toFixed(1) + ' از 5 ستاره';
                    }
                }
            },
            xaxis: {
                categories: <?php echo json_encode($ratingAnalytics['byCategory']['labels'], 15, 512) ?>,
                labels: {
                    formatter: function (val) {
                        return val.toFixed(1);
                    },
                    style: {
                        fontSize: '11px',
                        fontWeight: 500,
                        colors: '#6c757d'
                    }
                },
                min: 0,
                max: 5,
                title: {
                    text: 'میانگین امتیاز',
                    style: {
                        fontSize: '12px',
                        fontWeight: 600,
                        color: '#6c757d'
                    }
                }
            },
            yaxis: {
                labels: {
                    style: {
                        fontSize: '11px',
                        fontWeight: 500,
                        colors: '#6c757d'
                    }
                }
            },
            grid: {
                borderColor: '#f1f3fa',
                strokeDashArray: 3,
                xaxis: {
                    lines: {
                        show: true
                    }
                },
                yaxis: {
                    lines: {
                        show: false
                    }
                }
            }
        };

        const ratingCategoryChart = new ApexCharts(document.querySelector("#ratingByCategoriesChart"), ratingCategoryOptions);
        ratingCategoryChart.render();

        // Enhanced Rating Trends Chart
        const ratingTrendsOptions = {
            series: [{
                name: 'میانگین امتیازات',
                data: <?php echo json_encode($ratingAnalytics['trends']['data'], 15, 512) ?>
            }, {
                name: 'تعداد نظرات',
                type: 'column',
                data: <?php echo json_encode($ratingAnalytics['trends']['counts'] ?? array_fill(0, count($ratingAnalytics['trends']['data']), 100)) ?>
            }],
            chart: {
                height: 400,
                type: 'line',
                fontFamily: 'Vazirmatn, IRANSans, tahoma, sans-serif',
                animations: {
                    enabled: true,
                    easing: 'easeinout',
                    speed: 800
                },
                toolbar: {
                    show: true,
                    tools: {
                        download: true,
                        selection: true,
                        zoom: true,
                        zoomin: true,
                        zoomout: true,
                        pan: true,
                        reset: true
                    }
                },
                background: 'transparent'
            },
            stroke: {
                width: [4, 0],
                curve: 'smooth'
            },
            fill: {
                type: ['solid', 'gradient'],
                gradient: {
                    shade: 'light',
                    type: 'vertical',
                    shadeIntensity: 0.25,
                    gradientToColors: ['#667eea'],
                    inverseColors: false,
                    opacityFrom: 0.85,
                    opacityTo: 0.55,
                    stops: [50, 0, 100]
                }
            },
            grid: {
                borderColor: '#f1f3fa',
                strokeDashArray: 3,
                row: {
                    colors: ['#f8f9fc', 'transparent'],
                    opacity: 0.5
                }
            },
            markers: {
                size: [6, 0],
                colors: ['#ffc107'],
                strokeColors: '#fff',
                strokeWidth: 2,
                hover: {
                    size: 8
                }
            },
            dataLabels: {
                enabled: true,
                enabledOnSeries: [0],
                formatter: function (val) {
                    return val.toFixed(1);
                },
                style: {
                    fontSize: '11px',
                    fontWeight: 'bold',
                    colors: ['#304758']
                }
            },
            xaxis: {
                categories: <?php echo json_encode($ratingAnalytics['trends']['labels'], 15, 512) ?>,
                labels: {
                    style: {
                        fontSize: '11px',
                        fontWeight: 500,
                        colors: '#6c757d'
                    }
                },
                title: {
                    text: 'دوره زمانی',
                    style: {
                        fontSize: '12px',
                        fontWeight: 600,
                        color: '#6c757d'
                    }
                }
            },
            yaxis: [{
                title: {
                    text: 'میانگین امتیاز',
                    style: {
                        fontSize: '12px',
                        fontWeight: 600,
                        color: '#6c757d'
                    }
                },
                min: 0,
                max: 5,
                labels: {
                    formatter: function (val) {
                        return val.toFixed(1);
                    },
                    style: {
                        fontSize: '11px',
                        colors: '#6c757d'
                    }
                }
            }, {
                opposite: true,
                title: {
                    text: 'تعداد نظرات',
                    style: {
                        fontSize: '12px',
                        fontWeight: 600,
                        color: '#6c757d'
                    }
                },
                labels: {
                    style: {
                        fontSize: '11px',
                        colors: '#6c757d'
                    }
                }
            }],
            legend: {
                position: 'top',
                horizontalAlign: 'center',
                fontSize: '12px',
                fontWeight: 500,
                markers: {
                    width: 12,
                    height: 12,
                    radius: 6
                }
            },
            colors: ['#ffc107', '#667eea'],
            tooltip: {
                shared: true,
                intersect: false,
                theme: 'light',
                style: {
                    fontSize: '12px'
                },
                y: {
                    formatter: function (val, { seriesIndex }) {
                        if (seriesIndex === 0) {
                            return val.toFixed(1) + ' از 5';
                        } else {
                            return val + ' نظر';
                        }
                    }
                }
            }
        };

        const ratingTrendsChart = new ApexCharts(document.querySelector("#ratingTrendsChart"), ratingTrendsOptions);
        ratingTrendsChart.render();

        // Enhanced Sentiment Analysis Chart
        const sentimentData = [<?php echo e($positivePercent); ?>, <?php echo e($neutralPercent); ?>, <?php echo e($negativePercent); ?>];
        const sentimentOptions = {
            series: sentimentData,
            chart: {
                height: 350,
                type: 'donut',
                fontFamily: 'Vazirmatn, IRANSans, tahoma, sans-serif',
                animations: {
                    enabled: true,
                    easing: 'easeinout',
                    speed: 800
                },
                toolbar: {
                    show: true,
                    tools: {
                        download: true,
                        selection: false,
                        zoom: false,
                        zoomin: false,
                        zoomout: false,
                        pan: false,
                        reset: false
                    }
                },
                background: 'transparent'
            },
            labels: ['مثبت', 'خنثی', 'منفی'],
            colors: ['#28a745', '#ffc107', '#dc3545'],
            plotOptions: {
                pie: {
                    startAngle: -90,
                    endAngle: 270,
                    expandOnClick: true,
                    donut: {
                        size: '60%',
                        labels: {
                            show: true,
                            name: {
                                show: true,
                                fontSize: '14px',
                                fontWeight: 600,
                                color: '#373d3f'
                            },
                            value: {
                                show: true,
                                fontSize: '16px',
                                fontWeight: 700,
                                color: '#667eea',
                                formatter: function (val) {
                                    return val + '%';
                                }
                            },
                            total: {
                                show: true,
                                showAlways: false,
                                label: 'کل نظرات',
                                fontSize: '14px',
                                fontWeight: 600,
                                color: '#373d3f',
                                formatter: function (w) {
                                    return '<?php echo e(number_format($totalRatings)); ?>';
                                }
                            }
                        }
                    }
                }
            },
            stroke: {
                show: true,
                width: 3,
                colors: ['#fff']
            },
            dataLabels: {
                enabled: true,
                formatter: function (val, opt) {
                    return Math.round(val) + '%';
                },
                style: {
                    fontSize: '12px',
                    fontWeight: 'bold',
                    colors: ['#fff']
                },
                dropShadow: {
                    enabled: true,
                    top: 1,
                    left: 1,
                    blur: 1,
                    color: '#000',
                    opacity: 0.45
                }
            },
            legend: {
                position: 'bottom',
                fontSize: '12px',
                fontWeight: 500,
                markers: {
                    width: 12,
                    height: 12,
                    radius: 6
                }
            },
            tooltip: {
                theme: 'light',
                style: {
                    fontSize: '12px'
                },
                y: {
                    formatter: function(val, opts) {
                        const total = <?php echo e($totalRatings); ?>;
                        const count = Math.round((val / 100) * total);
                        return count + ' نظر (' + val + '%)';
                    }
                }
            }
        };

        const sentimentChart = new ApexCharts(document.querySelector("#ratingSentimentChart"), sentimentOptions);
        sentimentChart.render();

        // Store chart instances for later use
        window.ratingCharts = {
            distribution: ratingDistChart,
            categories: ratingCategoryChart,
            trends: ratingTrendsChart,
            sentiment: sentimentChart
        };

        // Enhanced Rating chart toggle functionality
        const ratingChartButtons = document.querySelectorAll('[data-rating-chart]');
        const ratingCharts = document.querySelectorAll('.rating-chart');

        ratingChartButtons.forEach(button => {
            button.addEventListener('click', function() {
                // Add loading animation
                showRatingLoading();

                // Remove active class from all buttons
                ratingChartButtons.forEach(btn => btn.classList.remove('active'));

                // Add active class to clicked button
                this.classList.add('active');

                // Hide all charts with animation
                ratingCharts.forEach(chart => {
                    chart.style.opacity = '0';
                    setTimeout(() => {
                        chart.style.display = 'none';
                    }, 300);
                });

                // Show selected chart with animation
                const selectedChart = this.getAttribute('data-rating-chart');
                setTimeout(() => {
                    if (selectedChart === 'distribution') {
                        document.getElementById('ratingDistribution').style.display = 'block';
                        document.getElementById('ratingStats').style.display = 'block';
                        setTimeout(() => {
                            document.getElementById('ratingDistribution').style.opacity = '1';
                            document.getElementById('ratingStats').style.opacity = '1';
                        }, 50);
                    } else {
                        document.getElementById(`rating${selectedChart.charAt(0).toUpperCase() + selectedChart.slice(1)}`).style.display = 'block';
                        setTimeout(() => {
                            document.getElementById(`rating${selectedChart.charAt(0).toUpperCase() + selectedChart.slice(1)}`).style.opacity = '1';
                        }, 50);
                    }
                    hideRatingLoading();
                }, 300);
            });
        });

        // Initialize chart animations
        initializeRatingAnimations();
    });

    // Enhanced functionality functions for rating analysis
    function showRatingLoading() {
        document.querySelectorAll('.chart-loading').forEach(loader => {
            loader.classList.remove('d-none');
        });
    }

    function hideRatingLoading() {
        setTimeout(() => {
            document.querySelectorAll('.chart-loading').forEach(loader => {
                loader.classList.add('d-none');
            });
        }, 500);
    }

    function initializeRatingAnimations() {
        // Add transition styles to chart containers
        document.querySelectorAll('.rating-chart').forEach(chart => {
            chart.style.transition = 'opacity 0.3s ease-in-out';
            chart.style.opacity = '1';
        });
    }

    function refreshChart(chartType) {
        showRatingLoading();

        // Simulate data refresh
        setTimeout(() => {
            if (window.ratingCharts && window.ratingCharts[chartType]) {
                window.ratingCharts[chartType].updateOptions({
                    chart: {
                        animations: {
                            enabled: true,
                            easing: 'easeinout',
                            speed: 800
                        }
                    }
                });
            }
            hideRatingLoading();

            // Show success message
            showRatingNotification('داده‌های نمودار با موفقیت بروزرسانی شد', 'success');
        }, 1000);
    }

    function fullscreenChart(chartId) {
        const chartElement = document.getElementById(chartId);
        if (chartElement.requestFullscreen) {
            chartElement.requestFullscreen();
        } else if (chartElement.webkitRequestFullscreen) {
            chartElement.webkitRequestFullscreen();
        } else if (chartElement.msRequestFullscreen) {
            chartElement.msRequestFullscreen();
        }
    }

    function downloadChart(chartId) {
        showRatingNotification('در حال دانلود نمودار...', 'info');

        // Simulate download process
        setTimeout(() => {
            showRatingNotification('نمودار با موفقیت دانلود شد', 'success');
        }, 1500);
    }

    function refreshRatingData() {
        showRatingNotification('در حال بروزرسانی داده‌های امتیازات...', 'info');

        // Simulate refresh process
        setTimeout(() => {
            showRatingNotification('داده‌ها با موفقیت بروزرسانی شدند', 'success');
        }, 2000);
    }

    function exportRatingData(format) {
        showRatingNotification('در حال آماده‌سازی فایل ' + format.toUpperCase() + '...', 'info');

        // Simulate export process
        setTimeout(() => {
            showRatingNotification('فایل با موفقیت دانلود شد', 'success');
        }, 2000);
    }

    function showRatingFilters() {
        showRatingNotification('فیلترهای پیشرفته در حال بارگذاری...', 'info');
    }

    function sortTopRated(sortBy) {
        showRatingNotification('در حال مرتب‌سازی بر اساس ' + (sortBy === 'rating' ? 'امتیاز' : 'تعداد نظرات') + '...', 'info');

        // Simulate sorting
        setTimeout(() => {
            showRatingNotification('مرتب‌سازی انجام شد', 'success');
        }, 1000);
    }

    function exportTopRated() {
        showRatingNotification('در حال آماده‌سازی فایل Excel...', 'info');

        // Simulate export
        setTimeout(() => {
            showRatingNotification('فایل Excel دانلود شد', 'success');
        }, 1500);
    }

    function viewLocationRatings(locationId) {
        showRatingNotification('در حال بارگذاری نظرات مکان...', 'info');

        // Simulate loading location ratings
        setTimeout(() => {
            showRatingNotification('نظرات مکان بارگذاری شد', 'success');
        }, 1000);
    }

    function showRatingNotification(message, type = 'info') {
        // Create notification element
        const notification = document.createElement('div');
        notification.className = `alert alert-${type} 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);

        // Auto remove after 3 seconds
        setTimeout(() => {
            if (notification.parentNode) {
                notification.remove();
            }
        }, 3000);
    }
</script><?php /**PATH /home/aluirani/public_html/aludubai.ir/resources/views/admin/analytics/partials/rating_analysis.blade.php ENDPATH**/ ?>