@extends('admin.layouts.app')

@section('title', 'Enhanced Individual Ad Analytics - Safety & Moderation')

@section('content')
    <!-- Enhanced Individual Ad Analytics Dashboard with Safety & Moderation -->
    <div class="enhanced-individual-ad-analytics">
        <!-- Ad Header Section -->
        <div class="ad-header">
            <div class="ad-info-card">
                <div class="ad-title-section">
                    <h1 style="margin: 0; font-size: 1.5rem; color: var(--text-primary);">Enhanced Ad Analytics</h1>
                    <div style="font-size: 1.1rem; color: var(--text-secondary); margin-top: 4px;" id="ad-title">Loading...</div>
                </div>
                <div class="ad-meta-info">
                    <div class="meta-item">
                        <span class="meta-label">Category:</span>
                        <span class="meta-value" id="ad-category">Loading...</span>
                    </div>
                    <div class="meta-item">
                        <span class="meta-label">Price:</span>
                        <span class="meta-value" id="ad-price">Loading...</span>
                    </div>
                    <div class="meta-item">
                        <span class="meta-label">Location:</span>
                        <span class="meta-value" id="ad-location">Loading...</span>
                    </div>
                    <div class="meta-item">
                        <span class="meta-label">Created:</span>
                        <span class="meta-value" id="ad-created">Loading...</span>
                    </div>
                </div>
                <div class="seller-info">
                    <div class="seller-avatar">👤</div>
                    <div class="seller-details">
                        <div style="font-weight: 600; color: var(--text-primary);" id="seller-name">Loading...</div>
                        <div style="font-size: 0.875rem; color: var(--text-secondary);" id="seller-email">Loading...</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Analytics Controls -->
        <div class="analytics-controls">
            <div style="display: flex; gap: 20px; align-items: center; flex-wrap: wrap;">
                <div>
                    <label style="display: block; font-size: 0.875rem; color: var(--text-secondary); margin-bottom: 4px;">Start Date</label>
                    <input type="date" id="start-date" style="padding: 8px; border: 1px solid var(--border-color); border-radius: 4px; background: var(--card-bg); color: var(--text-primary);">
                </div>
                <div>
                    <label style="display: block; font-size: 0.875rem; color: var(--text-secondary); margin-bottom: 4px;">End Date</label>
                    <input type="date" id="end-date" style="padding: 8px; border: 1px solid var(--border-color); border-radius: 4px; background: var(--card-bg); color: var(--text-primary);">
                </div>
                <div style="margin-top: 24px;">
                    <button onclick="refreshAnalytics()" style="padding: 10px 20px; background: var(--primary-color); color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">Refresh Data</button>
                    <button onclick="showDownloadOptions()" style="padding: 10px 20px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; margin-left: 10px;">Download Reports</button>
                </div>
            </div>
        </div>

        <!-- Safety & Risk Assessment Section -->
        <div class="safety-section">
            <div class="safety-header">
                <h2 style="margin: 0; font-size: 1.5rem; color: var(--text-primary);">🛡️ Safety & Risk Assessment</h2>
                <div class="risk-level" id="risk-level">Loading...</div>
            </div>
            
            <div class="safety-grid">
                <!-- Safety Score -->
                <div class="safety-card">
                    <div class="safety-icon">🔒</div>
                    <div class="safety-title">Safety Score</div>
                    <div class="safety-value" id="safety-score">0%</div>
                    <div class="safety-description">Overall ad safety rating</div>
                </div>

                <!-- Trust Score -->
                <div class="safety-card">
                    <div class="safety-icon">⭐</div>
                    <div class="safety-title">User Trust Score</div>
                    <div class="safety-value" id="trust-score">0/100</div>
                    <div class="safety-description">Seller credibility rating</div>
                </div>

                <!-- Total Reports -->
                <div class="safety-card">
                    <div class="safety-icon">⚠️</div>
                    <div class="safety-title">Total Reports</div>
                    <div class="safety-value" id="total-reports">0</div>
                    <div class="safety-description">Safety reports against this ad</div>
                </div>

                <!-- Pending Reports -->
                <div class="safety-card">
                    <div class="safety-icon">⏳</div>
                    <div class="safety-title">Pending Reports</div>
                    <div class="safety-value" id="pending-reports">0</div>
                    <div class="safety-description">Unresolved safety issues</div>
                </div>
            </div>
        </div>

        <!-- Moderation Actions Section -->
        <div class="moderation-section">
            <div class="moderation-header">
                <h3 style="margin: 0; font-size: 1.2rem; color: var(--text-primary);">🔧 Moderation Actions</h3>
                <div class="ad-status" id="ad-status">Loading...</div>
            </div>
            
            <div class="moderation-actions">
                <button onclick="moderateAd('suspend')" style="padding: 10px 20px; background: #f59e0b; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; margin-right: 10px;">Suspend Ad</button>
                <button onclick="moderateAd('reject')" style="padding: 10px 20px; background: #ef4444; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; margin-right: 10px;">Reject Ad</button>
                <button onclick="moderateAd('delete')" style="padding: 10px 20px; background: #dc2626; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; margin-right: 10px;">Delete Ad</button>
                <button onclick="moderateAd('approve')" style="padding: 10px 20px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; margin-right: 10px;">Approve Ad</button>
            </div>
        </div>

        <!-- Performance Metrics Section -->
        <div class="dashboard-grid">
            <!-- Impressions -->
            <div class="card">
                <div class="card-header">
                    <div>
                        <div class="card-title">Impressions</div>
                        <div class="card-value" id="impressions-count">0</div>
                    </div>
                    <div class="stat-icon">👁️</div>
                </div>
                <div class="card-change" id="impressions-change">+0% from last period</div>
            </div>

            <!-- Views -->
            <div class="card">
                <div class="card-header">
                    <div>
                        <div class="card-title">Views</div>
                        <div class="card-value" id="views-count">0</div>
                    </div>
                    <div class="stat-icon">📊</div>
                </div>
                <div class="card-change" id="views-change">+0% from last period</div>
            </div>

            <!-- Clicks -->
            <div class="card">
                <div class="card-header">
                    <div>
                        <div class="card-title">Clicks</div>
                        <div class="card-value" id="clicks-count">0</div>
                    </div>
                    <div class="stat-icon">👆</div>
                </div>
                <div class="card-change" id="clicks-change">+0% from last period</div>
            </div>

            <!-- CTR -->
            <div class="card">
                <div class="card-header">
                    <div>
                        <div class="card-title">CTR</div>
                        <div class="card-value" id="ctr-value">0%</div>
                    </div>
                    <div class="stat-icon">📈</div>
                </div>
                <div class="card-change" id="ctr-change">+0% from last period</div>
            </div>
        </div>

        <!-- Reported Ads & Reporter Information Section -->
        <div class="content-grid">
            <!-- Reported Ads Table -->
            <div class="table-card">
                <div class="card-header">
                    <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">🚨 Reported Ads</h3>
                    <div style="font-size: 0.875rem; color: var(--text-secondary);">All reports against this ad</div>
                </div>
                
                <div style="margin-top: 20px;">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Report ID</th>
                                <th>Reporter</th>
                                <th>Report Type</th>
                                <th>Reason</th>
                                <th>Status</th>
                                <th>Date</th>
                            </tr>
                        </thead>
                        <tbody id="reports-table">
                            <!-- Data loaded via JavaScript -->
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Reporter Analytics -->
            <div class="table-card">
                <div class="card-header">
                    <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">👤 Reporter Analytics</h3>
                    <div style="font-size: 0.875rem; color: var(--text-secondary);">Reporter credibility and history</div>
                </div>
                
                <div style="margin-top: 20px;">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Reporter</th>
                                <th>Total Reports</th>
                                <th>Accuracy Rate</th>
                                <th>Credibility</th>
                                <th>Risk Level</th>
                            </tr>
                        </thead>
                        <tbody id="reporter-table">
                            <!-- Data loaded via JavaScript -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- User Profile & Safety Analysis Section -->
        <div class="content-grid">
            <!-- User Profile Analytics -->
            <div class="table-card">
                <div class="card-header">
                    <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">👤 User Profile Analytics</h3>
                    <div style="font-size: 0.875rem; color: var(--text-secondary);">Complete user safety analysis</div>
                </div>
                
                <div style="margin-top: 20px;">
                    <div id="user-profile-container">
                        <!-- User profile data loaded via JavaScript -->
                    </div>
                </div>
            </div>

            <!-- User Management Actions -->
            <div class="table-card">
                <div class="card-header">
                    <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">🔧 User Management</h3>
                    <div style="font-size: 0.875rem; color: var(--text-secondary);">Account actions and appeals</div>
                </div>
                
                <div style="margin-top: 20px;">
                    <div class="user-actions-grid">
                        <button onclick="manageUser('suspend')" style="padding: 10px 20px; background: #f59e0b; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; margin-bottom: 10px; width: 100%;">Suspend User</button>
                        <button onclick="manageUser('ban')" style="padding: 10px 20px; background: #ef4444; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; margin-bottom: 10px; width: 100%;">Ban User</button>
                        <button onclick="manageUser('unban')" style="padding: 10px 20px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; margin-bottom: 10px; width: 100%;">Unban User</button>
                        <button onclick="showUserAppeals()" style="padding: 10px 20px; background: #7c3aed; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; margin-bottom: 10px; width: 100%;">View Appeals</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- User Appeals Section -->
        <div class="content-grid">
            <!-- User Appeals -->
            <div class="table-card">
                <div class="card-header">
                    <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">📋 User Appeals</h3>
                    <div style="font-size: 0.875rem; color: var(--text-secondary);">Appeal management and review</div>
                </div>
                
                <div style="margin-top: 20px;">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Appeal Type</th>
                                <th>Status</th>
                                <th>Reason</th>
                                <th>Date</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="appeals-table">
                            <!-- Data loaded via JavaScript -->
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Risk Indicators -->
            <div class="table-card">
                <div class="card-header">
                    <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">⚠️ Risk Indicators</h3>
                    <div style="font-size: 0.875rem; color: var(--text-secondary);">Suspicious activity patterns</div>
                </div>
                
                <div style="margin-top: 20px;">
                    <div id="risk-indicators-container">
                        <!-- Risk indicators loaded via JavaScript -->
                    </div>
                </div>
            </div>
        </div>

        <!-- Moderation Actions History -->
        <div class="content-grid">
            <!-- Ad Moderation Actions -->
            <div class="table-card">
                <div class="card-header">
                    <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">📋 Ad Moderation Actions</h3>
                    <div style="font-size: 0.875rem; color: var(--text-secondary);">All moderation actions taken</div>
                </div>
                
                <div style="margin-top: 20px;">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Action Type</th>
                                <th>Admin</th>
                                <th>Reason</th>
                                <th>Date</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody id="moderation-actions-table">
                            <!-- Data loaded via JavaScript -->
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- User Moderation Actions -->
            <div class="table-card">
                <div class="card-header">
                    <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">👤 User Moderation Actions</h3>
                    <div style="font-size: 0.875rem; color: var(--text-secondary);">Actions taken against the user</div>
                </div>
                
                <div style="margin-top: 20px;">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Action Type</th>
                                <th>Admin</th>
                                <th>Reason</th>
                                <th>Date</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody id="user-moderation-table">
                            <!-- Data loaded via JavaScript -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Engagement & Chat Analytics -->
        <div class="content-grid">
            <!-- Engagement Metrics -->
            <div class="chart-card">
                <div class="card-header">
                    <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Likes & Favorites</h3>
                    <div style="font-size: 0.875rem; color: var(--text-secondary);">User engagement</div>
                </div>
                
                <div style="margin-top: 20px; height: 300px; position: relative;">
                    <canvas id="engagementChart" width="600" height="300"></canvas>
                </div>
            </div>

            <!-- Chat Analytics -->
            <div class="table-card">
                <div class="card-header">
                    <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Chat Analytics</h3>
                    <div style="font-size: 0.875rem; color: var(--text-secondary);">Conversation insights</div>
                </div>
                
                <div style="margin-top: 20px;">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Conversation</th>
                                <th>Messages</th>
                                <th>Avg Response Time</th>
                            </tr>
                        </thead>
                        <tbody id="chat-table">
                            <!-- Data loaded via JavaScript -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Download Options Modal -->
        <div id="download-modal" class="modal" style="display: none;">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 style="margin: 0; font-size: 1.2rem; color: var(--text-primary);">Download Reports</h3>
                    <button onclick="hideDownloadOptions()" style="background: none; border: none; font-size: 1.5rem; cursor: pointer;">×</button>
                </div>
                <div class="modal-body">
                    <div class="download-options-grid">
                        <div class="download-option" onclick="downloadReport('pdf')">
                            <div class="download-icon">📄</div>
                            <div class="download-info">
                                <div style="font-weight: 600;">PDF Report</div>
                                <div style="font-size: 0.875rem; color: var(--text-secondary);">Professional PDF with charts</div>
                            </div>
                        </div>
                        <div class="download-option" onclick="downloadReport('excel')">
                            <div class="download-icon">📈</div>
                            <div class="download-info">
                                <div style="font-weight: 600;">Excel Spreadsheet</div>
                                <div style="font-size: 0.875rem; color: var(--text-secondary);">Detailed data with formulas</div>
                            </div>
                        </div>
                        <div class="download-option" onclick="downloadReport('csv')">
                            <div class="download-icon">📊</div>
                            <div class="download-info">
                                <div style="font-weight: 600;">CSV File</div>
                                <div style="font-size: 0.875rem; color: var(--text-secondary);">Raw data for analysis</div>
                            </div>
                        </div>
                        <div class="download-option" onclick="downloadReport('json')">
                            <div class="download-icon">📊</div>
                            <div class="download-info">
                                <div style="font-weight: 600;">JSON Data</div>
                                <div style="font-size: 0.875rem; color: var(--text-secondary);">Machine-readable data</div>
                            </div>
                        </div>
                        <div class="download-option" onclick="downloadReport('chat')">
                            <div class="download-icon">💬</div>
                            <div class="download-info">
                                <div style="font-weight: 600;">Chat Transcripts</div>
                                <div style="font-size: 0.875rem; color: var(--text-secondary);">Complete chat conversations</div>
                            </div>
                        </div>
                        <div class="download-option" onclick="downloadReport('safety')">
                            <div class="download-icon">🛡️</div>
                            <div class="download-info">
                                <div style="font-weight: 600;">Safety Report</div>
                                <div style="font-size: 0.875rem; color: var(--text-secondary);">Comprehensive safety analysis</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Moderation Modal -->
        <div id="moderation-modal" class="modal" style="display: none;">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 style="margin: 0; font-size: 1.2rem; color: var(--text-primary);" id="moderation-title">Moderation Action</h3>
                    <button onclick="hideModerationModal()" style="background: none; border: none; font-size: 1.5rem; cursor: pointer;">×</button>
                </div>
                <div class="modal-body">
                    <div style="margin-bottom: 20px;">
                        <label style="display: block; font-size: 0.875rem; color: var(--text-secondary); margin-bottom: 4px;">Reason for Action</label>
                        <textarea id="moderation-reason" rows="4" style="width: 100%; padding: 8px; border: 1px solid var(--border-color); border-radius: 4px; background: var(--card-bg); color: var(--text-primary);"></textarea>
                    </div>
                    <div style="display: flex; gap: 10px;">
                        <label style="display: flex; align-items: center; gap: 8px; font-size: 0.875rem; color: var(--text-secondary);">
                            <input type="checkbox" id="notify-user"> Notify user
                        </label>
                        <label style="display: flex; align-items: center; gap: 8px; font-size: 0.875rem; color: var(--text-secondary);">
                            <input type="checkbox" id="create-ticket"> Create support ticket
                        </label>
                    </div>
                    <div style="margin-top: 20px; display: flex; gap: 10px; justify-content: flex-end;">
                        <button onclick="hideModerationModal()" style="padding: 10px 20px; background: #6b7280; color: white; border: none; border-radius: 6px; cursor: pointer;">Cancel</button>
                        <button onclick="executeModerationAction()" style="padding: 10px 20px; background: var(--primary-color); color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;" id="moderation-action-btn">Execute Action</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Chart.js Library -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <!-- Enhanced Individual Ad Analytics JavaScript -->
    <script>
        // Chart instances
        let engagementChart;

        // Current moderation action
        let currentModerationAction = '';

        // Initialize dashboard
        document.addEventListener('DOMContentLoaded', function() {
            initializeCharts();
            loadEnhancedIndividualAdAnalytics();
            
            // Set default date range
            const today = new Date();
            const lastMonth = new Date();
            lastMonth.setMonth(lastMonth.getMonth() - 1);
            
            document.getElementById('start-date').value = lastMonth.toISOString().split('T')[0];
            document.getElementById('end-date').value = today.toISOString().split('T')[0];
            
            // Add event listeners
            document.getElementById('start-date').addEventListener('change', loadEnhancedIndividualAdAnalytics);
            document.getElementById('end-date').addEventListener('change', loadEnhancedIndividualAdAnalytics);
        });

        function initializeCharts() {
            // Engagement Chart
            const engagementCtx = document.getElementById('engagementChart').getContext('2d');
            engagementChart = new Chart(engagementCtx, {
                type: 'bar',
                data: {
                    labels: ['Likes', 'Favorites', 'Call Clicks', 'WhatsApp Clicks'],
                    datasets: [{
                        label: 'Engagement Metrics',
                        data: [0, 0, 0, 0],
                        backgroundColor: ['#7c3aed', '#10b981', '#f59e0b', '#ef4444']
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    }
                }
            });
        }

        async function loadEnhancedIndividualAdAnalytics() {
            const adId = {{ $adId }};
            const startDate = document.getElementById('start-date').value;
            const endDate = document.getElementById('end-date').value;

            try {
                const response = await fetch(`/api/analytics/ad/${adId}?start_date=${startDate}&end_date=${endDate}`);
                const data = await response.json();

                if (data.success) {
                    updateAdInfo(data.data.ad_info);
                    updateSafetyAnalytics(data.data.safety_analytics);
                    updatePerformanceMetrics(data.data.performance_metrics);
                    updateEngagementChart(data.data.engagement_analytics);
                    updateReportedAds(data.data.safety_analytics.report_details);
                    updateReporterAnalytics(data.data.reporter_analytics.reporter_details);
                    updateUserProfile(data.data.user_profile_analytics);
                    updateModerationActions(data.data.moderation_actions);
                }

            } catch (error) {
                console.error('Error loading enhanced individual ad analytics:', error);
                alert('Error loading enhanced individual ad analytics. Please try again.');
            }
        }

        function updateAdInfo(adInfo) {
            document.getElementById('ad-title').textContent = adInfo.title;
            document.getElementById('ad-category').textContent = adInfo.category;
            document.getElementById('ad-price').textContent = `₹${adInfo.price}`;
            document.getElementById('ad-location').textContent = adInfo.location;
            document.getElementById('ad-created').textContent = new Date(adInfo.created_at).toLocaleDateString();
            document.getElementById('seller-name').textContent = adInfo.seller_info.name;
            document.getElementById('seller-email').textContent = adInfo.seller_info.email;
        }

        function updateSafetyAnalytics(safetyData) {
            // Update safety score
            document.getElementById('safety-score').textContent = `${safetyData.safety_score}%`;
            document.getElementById('trust-score').textContent = `${safetyData.user_trust_score}/100`;
            document.getElementById('total-reports').textContent = safetyData.total_reports;
            document.getElementById('pending-reports').textContent = safetyData.pending_reports;
            
            // Update risk level
            const riskLevelEl = document.getElementById('risk-level');
            riskLevelEl.textContent = safetyData.risk_level;
            riskLevelEl.style.backgroundColor = getRiskColor(safetyData.risk_level);
            
            // Update ad status
            const adStatusEl = document.getElementById('ad-status');
            adStatusEl.textContent = safetyData.current_ad_status || 'Active';
            adStatusEl.style.backgroundColor = getStatusColor(safetyData.current_ad_status || 'Active');
        }

        function updatePerformanceMetrics(metrics) {
            document.getElementById('impressions-count').textContent = metrics.impressions.toLocaleString();
            document.getElementById('views-count').textContent = metrics.views.total.toLocaleString();
            document.getElementById('clicks-count').textContent = metrics.clicks.total.toLocaleString();
            document.getElementById('ctr-value').textContent = `${metrics.ctr}%`;
        }

        function updateReportedAds(reports) {
            const tableBody = document.getElementById('reports-table');
            tableBody.innerHTML = '';

            if (reports && reports.length > 0) {
                reports.forEach(report => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td style="font-weight: 600;">#${report.id}</td>
                        <td>${report.reporter_info.name}</td>
                        <td>${report.report_type}</td>
                        <td style="max-width: 200px; overflow: hidden; text-overflow: ellipsis;">${report.reason}</td>
                        <td><span class="status-badge ${report.status}">${report.status}</span></td>
                        <td>${new Date(report.created_at).toLocaleString()}</td>
                    `;
                    tableBody.appendChild(row);
                });
            } else {
                const row = document.createElement('tr');
                row.innerHTML = '<td colspan="6" style="text-align: center; color: var(--text-secondary);">No reports found</td>';
                tableBody.appendChild(row);
            }
        }

        function updateReporterAnalytics(reporters) {
            const tableBody = document.getElementById('reporter-table');
            tableBody.innerHTML = '';

            if (reporters && reporters.length > 0) {
                reporters.forEach(reporter => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td style="font-weight: 600;">${reporter.reporter_info.name}</td>
                        <td>${reporter.reporter_history.total_reports}</td>
                        <td>${reporter.reporter_history.reporter_accuracy}%</td>
                        <td><span class="credibility-badge ${reporter.reporter_history.credibility_score > 80 ? 'high' : reporter.reporter_history.credibility_score > 50 ? 'medium' : 'low'}">${reporter.reporter_history.credibility_score}%</span></td>
                        <td><span class="risk-badge ${reporter.risk_assessment.reporter_risk_level}">${reporter.risk_assessment.reporter_risk_level}</span></td>
                    `;
                    tableBody.appendChild(row);
                });
            } else {
                const row = document.createElement('tr');
                row.innerHTML = '<td colspan="5" style="text-align: center; color: var(--text-secondary);">No reporter data found</td>';
                tableBody.appendChild(row);
            }
        }

        function updateUserProfile(userProfile) {
            const container = document.getElementById('user-profile-container');
            container.innerHTML = `
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                    <div style="background: var(--card-bg); padding: 16px; border-radius: 8px;">
                        <h4 style="margin: 0 0 12px 0; color: var(--text-primary);">Basic Information</h4>
                        <div style="display: grid; gap: 8px;">
                            <div><strong>Name:</strong> ${userProfile.user_info.name}</div>
                            <div><strong>Email:</strong> ${userProfile.user_info.email}</div>
                            <div><strong>Phone:</strong> ${userProfile.user_info.phone || 'Not provided'}</div>
                            <div><strong>Join Date:</strong> ${new Date(userProfile.user_info.join_date).toLocaleDateString()}</div>
                            <div><strong>Last Activity:</strong> ${userProfile.user_info.last_activity ? new Date(userProfile.user_info.last_activity).toLocaleString() : 'Never'}</div>
                        </div>
                    </div>
                    <div style="background: var(--card-bg); padding: 16px; border-radius: 8px;">
                        <h4 style="margin: 0 0 12px 0; color: var(--text-primary);">Verification Status</h4>
                        <div style="display: grid; gap: 8px;">
                            <div><strong>Email Verified:</strong> <span class="${userProfile.verification_status.email_verified ? 'verified' : 'not-verified'}">${userProfile.verification_status.email_verified ? '✅' : '❌'}</span></div>
                            <div><strong>Phone Verified:</strong> <span class="${userProfile.verification_status.phone_verified ? 'verified' : 'not-verified'}">${userProfile.verification_status.phone_verified ? '✅' : '❌'}</span></div>
                            <div><strong>ID Verified:</strong> <span class="${userProfile.verification_status.id_verified ? 'verified' : 'not-verified'}">${userProfile.verification_status.id_verified ? '✅' : '❌'}</span></div>
                            <div><strong>Total Verifications:</strong> ${userProfile.verification_status.total_verifications}/3</div>
                        </div>
                    </div>
                </div>
            `;
        }

        function updateModerationActions(moderationData) {
            // Update ad moderation actions
            const adTableBody = document.getElementById('moderation-actions-table');
            adTableBody.innerHTML = '';

            if (moderationData.ad_moderation_actions && moderationData.ad_moderation_actions.length > 0) {
                moderationData.ad_moderation_actions.forEach(action => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td style="font-weight: 600;">${action.action_type}</td>
                        <td>${action.admin_user}</td>
                        <td style="max-width: 200px; overflow: hidden; text-overflow: ellipsis;">${action.reason}</td>
                        <td>${new Date(action.created_at).toLocaleString()}</td>
                        <td><span class="status-badge ${action.status}">${action.status}</span></td>
                    `;
                    adTableBody.appendChild(row);
                });
            } else {
                const row = document.createElement('tr');
                row.innerHTML = '<td colspan="5" style="text-align: center; color: var(--text-secondary);">No moderation actions found</td>';
                adTableBody.appendChild(row);
            }

            // Update user moderation actions
            const userTableBody = document.getElementById('user-moderation-table');
            userTableBody.innerHTML = '';

            if (moderationData.user_moderation_actions && moderationData.user_moderation_actions.length > 0) {
                moderationData.user_moderation_actions.forEach(action => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td style="font-weight: 600;">${action.action_type}</td>
                        <td>${action.admin_user}</td>
                        <td style="max-width: 200px; overflow: hidden; text-overflow: ellipsis;">${action.reason}</td>
                        <td>${new Date(action.created_at).toLocaleString()}</td>
                        <td><span class="status-badge ${action.status}">${action.status}</span></td>
                    `;
                    userTableBody.appendChild(row);
                });
            } else {
                const row = document.createElement('tr');
                row.innerHTML = '<td colspan="5" style="text-align: center; color: var(--text-secondary);">No user moderation actions found</td>';
                userTableBody.appendChild(row);
            }
        }

        function moderateAd(action) {
            currentModerationAction = action;
            document.getElementById('moderation-title').textContent = `Moderate Ad - ${action.toUpperCase()}`;
            document.getElementById('moderation-action-btn').textContent = action.toUpperCase();
            document.getElementById('moderation-action-btn').style.backgroundColor = getActionColor(action);
            document.getElementById('moderation-modal').style.display = 'block';
        }

        function hideModerationModal() {
            document.getElementById('moderation-modal').style.display = 'none';
            document.getElementById('moderation-reason').value = '';
            document.getElementById('notify-user').checked = false;
            document.getElementById('create-ticket').checked = false;
        }

        async function executeModerationAction() {
            const adId = {{ $adId }};
            const reason = document.getElementById('moderation-reason').value;
            const notifyUser = document.getElementById('notify-user').checked;
            const createTicket = document.getElementById('create-ticket').checked;

            if (!reason.trim()) {
                alert('Please provide a reason for the moderation action.');
                return;
            }

            try {
                let endpoint = '';
                switch(currentModerationAction) {
                    case 'suspend':
                        endpoint = `/api/analytics/ad/${adId}/suspend`;
                        break;
                    case 'reject':
                        endpoint = `/api/analytics/ad/${adId}/reject`;
                        break;
                    case 'delete':
                        endpoint = `/api/analytics/ad/${adId}/delete`;
                        break;
                    case 'approve':
                        endpoint = `/api/analytics/ad/${adId}/approve`;
                        break;
                }

                const response = await fetch(endpoint, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify({
                        reason: reason,
                        notify_user: notifyUser,
                        create_ticket: createTicket
                    })
                });

                const result = await response.json();

                if (result.success) {
                    alert(`Ad ${currentModerationAction}ed successfully!`);
                    hideModerationModal();
                    loadEnhancedIndividualAdAnalytics();
                } else {
                    alert(`Error: ${result.message}`);
                }

            } catch (error) {
                console.error('Error executing moderation action:', error);
                alert('Error executing moderation action. Please try again.');
            }
        }

        function getRiskColor(riskLevel) {
            switch(riskLevel) {
                case 'HIGH': return '#ef4444';
                case 'MEDIUM': return '#f59e0b';
                case 'LOW': return '#10b981';
                default: return '#6b7280';
            }
        }

        function getStatusColor(status) {
            switch(status.toLowerCase()) {
                case 'active': return '#10b981';
                case 'suspended': return '#f59e0b';
                case 'rejected': return '#ef4444';
                case 'deleted': return '#6b7280';
                default: return '#6b7280';
            }
        }

        function getActionColor(action) {
            switch(action) {
                case 'suspend': return '#f59e0b';
                case 'reject': return '#ef4444';
                case 'delete': return '#dc2626';
                case 'approve': return '#10b981';
                default: return 'var(--primary-color)';
            }
        }

        function refreshAnalytics() {
            loadEnhancedIndividualAdAnalytics();
        }

        function showDownloadOptions() {
            document.getElementById('download-modal').style.display = 'block';
        }

        function hideDownloadOptions() {
            document.getElementById('download-modal').style.display = 'none';
        }

        function downloadReport(format) {
            const adId = {{ $adId }};
            const startDate = document.getElementById('start-date').value;
            const endDate = document.getElementById('end-date').value;
            
            let url = '';
            if (format === 'safety') {
                url = `/api/analytics/ad/${adId}/safety?start_date=${startDate}&end_date=${endDate}`;
            } else {
                url = `/api/analytics/ad/${adId}/download/${format}?start_date=${startDate}&end_date=${endDate}`;
            }
            
            // Create a temporary link to download the file
            const link = document.createElement('a');
            link.href = url;
            link.download = `ad_${adId}_${format}_report.${format === 'pdf' ? 'pdf' : format === 'excel' ? 'xlsx' : format === 'csv' ? 'csv' : format === 'json' ? 'json' : format === 'chat' ? 'txt' : format === 'safety' ? 'pdf' : 'html'}`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            hideDownloadOptions();
        }

        // User Management Functions
        function manageUser(action) {
            const userId = {{ $ad->user_id }};
            const modalTitle = document.getElementById('moderation-title');
            const actionBtn = document.getElementById('moderation-action-btn');
            const reasonField = document.getElementById('moderation-reason');
            const notifyCheckbox = document.getElementById('notify-user');
            const ticketCheckbox = document.getElementById('create-ticket');
            const modal = document.getElementById('moderation-modal');

            // Set modal content based on action
            switch(action) {
                case 'suspend':
                    modalTitle.textContent = 'Suspend User';
                    actionBtn.textContent = 'Suspend User';
                    actionBtn.style.backgroundColor = '#f59e0b';
                    reasonField.placeholder = 'Enter reason for suspending user...';
                    notifyCheckbox.parentElement.style.display = 'block';
                    ticketCheckbox.parentElement.style.display = 'block';
                    break;
                case 'ban':
                    modalTitle.textContent = 'Ban User';
                    actionBtn.textContent = 'Ban User';
                    actionBtn.style.backgroundColor = '#ef4444';
                    reasonField.placeholder = 'Enter reason for banning user...';
                    notifyCheckbox.parentElement.style.display = 'block';
                    ticketCheckbox.parentElement.style.display = 'block';
                    break;
                case 'unban':
                    modalTitle.textContent = 'Unban User';
                    actionBtn.textContent = 'Unban User';
                    actionBtn.style.backgroundColor = '#10b981';
                    reasonField.placeholder = 'Enter reason for unbanning user...';
                    notifyCheckbox.parentElement.style.display = 'block';
                    ticketCheckbox.parentElement.style.display = 'none';
                    break;
            }

            // Store the action type for the execute function
            modal.dataset.action = action;
            modal.style.display = 'block';
        }

        function showUserAppeals() {
            const userId = {{ $ad->user_id }};
            loadUserAppeals(userId);
        }

        async function loadUserAppeals(userId) {
            try {
                const response = await fetch(`/api/analytics/user/${userId}/appeals`);
                const data = await response.json();

                if (data.success) {
                    updateUserAppealsTable(data.data);
                }
            } catch (error) {
                console.error('Error loading user appeals:', error);
                alert('Error loading user appeals. Please try again.');
            }
        }

        function updateUserAppealsTable(appeals) {
            const tableBody = document.getElementById('appeals-table');
            tableBody.innerHTML = '';

            if (appeals && appeals.length > 0) {
                appeals.forEach(appeal => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td style="font-weight: 600;">${appeal.appeal_type}</td>
                        <td><span class="status-badge ${appeal.status}">${appeal.status}</span></td>
                        <td style="max-width: 200px; overflow: hidden; text-overflow: ellipsis;">${appeal.appeal_reason}</td>
                        <td>${new Date(appeal.created_at).toLocaleString()}</td>
                        <td>
                            ${appeal.status === 'pending' ? `
                                <button onclick="reviewAppeal(${appeal.id}, 'approved')" style="padding: 4px 8px; background: #10b981; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 0.75rem; margin-right: 5px;">Approve</button>
                                <button onclick="reviewAppeal(${appeal.id}, 'rejected')" style="padding: 4px 8px; background: #ef4444; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 0.75rem;">Reject</button>
                            ` : `
                                <span style="font-size: 0.75rem; color: var(--text-secondary);">${appeal.resolution_notes || 'No notes'}</span>
                            `}
                        </td>
                    `;
                    tableBody.appendChild(row);
                });
            } else {
                const row = document.createElement('tr');
                row.innerHTML = '<td colspan="5" style="text-align: center; color: var(--text-secondary);">No appeals found</td>';
                tableBody.appendChild(row);
            }
        }

        function reviewAppeal(appealId, status) {
            const modalTitle = document.getElementById('moderation-title');
            const actionBtn = document.getElementById('moderation-action-btn');
            const reasonField = document.getElementById('moderation-reason');
            const notifyCheckbox = document.getElementById('notify-user');
            const ticketCheckbox = document.getElementById('create-ticket');
            const modal = document.getElementById('moderation-modal');

            modalTitle.textContent = `Review Appeal - ${status.toUpperCase()}`;
            actionBtn.textContent = 'Submit Review';
            actionBtn.style.backgroundColor = status === 'approved' ? '#10b981' : '#ef4444';
            reasonField.placeholder = 'Enter resolution notes...';
            notifyCheckbox.parentElement.style.display = 'block';
            ticketCheckbox.parentElement.style.display = 'none';

            // Store appeal data for the execute function
            modal.dataset.appealId = appealId;
            modal.dataset.appealStatus = status;
            modal.style.display = 'block';
        }

        async function executeModerationAction() {
            const adId = {{ $adId }};
            const reason = document.getElementById('moderation-reason').value;
            const notifyUser = document.getElementById('notify-user').checked;
            const createTicket = document.getElementById('create-ticket').checked;
            const modal = document.getElementById('moderation-modal');
            const action = modal.dataset.action;
            const appealId = modal.dataset.appealId;
            const appealStatus = modal.dataset.appealStatus;

            if (!reason.trim()) {
                alert('Please provide a reason for the action.');
                return;
            }

            try {
                if (appealId) {
                    // Handle appeal review
                    const response = await fetch(`/api/analytics/appeal/${appealId}/review`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                        },
                        body: JSON.stringify({
                            status: appealStatus,
                            resolution_notes: reason,
                            notify_user: notifyUser
                        })
                    });

                    const result = await response.json();

                    if (result.success) {
                        alert(`Appeal ${appealStatus}ed successfully!`);
                        hideModerationModal();
                        showUserAppeals();
                    } else {
                        alert(`Error: ${result.message}`);
                    }
                } else {
                    // Handle user management actions
                    const userId = {{ $ad->user_id }};
                    let endpoint = '';
                    let method = 'POST';

                    switch(action) {
                        case 'suspend':
                            endpoint = `/api/analytics/user/${userId}/suspend`;
                            break;
                        case 'ban':
                            endpoint = `/api/analytics/user/${userId}/ban`;
                            break;
                        case 'unban':
                            endpoint = `/api/analytics/user/${userId}/unban`;
                            break;
                        default:
                            alert('Invalid action');
                            return;
                    }

                    const response = await fetch(endpoint, {
                        method: method,
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                        },
                        body: JSON.stringify({
                            reason: reason,
                            notify_user: notifyUser,
                            create_ticket: createTicket
                        })
                    });

                    const result = await response.json();

                    if (result.success) {
                        alert(`User ${action}ed successfully!`);
                        hideModerationModal();
                        loadEnhancedIndividualAdAnalytics();
                    } else {
                        alert(`Error: ${result.message}`);
                    }
                }

            } catch (error) {
                console.error('Error executing action:', error);
                alert('Error executing action. Please try again.');
            }
        }

        // Close modals when clicking outside
        window.onclick = function(event) {
            const downloadModal = document.getElementById('download-modal');
            const moderationModal = document.getElementById('moderation-modal');
            
            if (event.target === downloadModal) {
                hideDownloadOptions();
            }
            if (event.target === moderationModal) {
                hideModerationModal();
            }
        }
    </script>

    <style>
        .enhanced-individual-ad-analytics {
            animation: fadeIn 0.5s ease-in;
        }

        .safety-section {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            padding: 24px;
            margin-bottom: 24px;
        }

        .safety-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 16px;
        }

        .risk-level {
            padding: 8px 16px;
            border-radius: 20px;
            color: white;
            font-weight: 600;
            font-size: 0.875rem;
        }

        .safety-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 16px;
        }

        .safety-card {
            background: var(--bg-color);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 16px;
            text-align: center;
        }

        .safety-icon {
            font-size: 2rem;
            margin-bottom: 8px;
        }

        .safety-title {
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 4px;
        }

        .safety-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--primary-color);
            margin-bottom: 4px;
        }

        .safety-description {
            font-size: 0.75rem;
            color: var(--text-secondary);
        }

        .moderation-section {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            padding: 16px;
            margin-bottom: 24px;
        }

        .moderation-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
        }

        .ad-status {
            padding: 8px 16px;
            border-radius: 20px;
            color: white;
            font-weight: 600;
            font-size: 0.875rem;
        }

        .moderation-actions {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }

        .status-badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .status-badge.pending { background-color: #f59e0b; color: white; }
        .status-badge.resolved { background-color: #10b981; color: white; }
        .status-badge.rejected { background-color: #ef4444; color: white; }

        .credibility-badge.high { background-color: #10b981; color: white; }
        .credibility-badge.medium { background-color: #f59e0b; color: white; }
        .credibility-badge.low { background-color: #ef4444; color: white; }

        .risk-badge.TRUSTED { background-color: #10b981; color: white; }
        .risk-badge.NEUTRAL { background-color: #f59e0b; color: white; }
        .risk-badge.UNTRUSTED { background-color: #ef4444; color: white; }

        .verified { color: #10b981; }
        .not-verified { color: #ef4444; }

        .modal-content {
            background-color: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            width: 600px;
            max-width: 90%;
            box-shadow: 0 10px 25px var(--shadow-color);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px;
            border-bottom: 1px solid var(--border-color);
        }

        .modal-body {
            padding: 20px;
        }

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

        @media (max-width: 768px) {
            .safety-grid {
                grid-template-columns: 1fr;
            }
            
            .moderation-actions {
                flex-direction: column;
            }
        }
    </style>
@endsection
