@extends('admin.layouts.app')

@section('title', 'Safety Center')

@section('content')
<div style="max-width: 1400px; margin: 0 auto;">
    
    <!-- Header & Actions -->
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
        <div>
            <h2 style="font-size: 1.5rem; font-weight: 700; color: var(--text-primary); margin: 0;">Safety Center</h2>
            <p style="color: var(--text-secondary); margin: 4px 0 0 0;">Monitor and manage ad reports and platform safety.</p>
        </div>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#settingsModal" style="background: var(--primary-color); border: none; padding: 10px 20px; border-radius: 8px; font-weight: 600;">
            ⚙️ Safety Settings
        </button>
    </div>

    <!-- KPI Cards -->
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 20px; margin-bottom: 32px;">
        <div class="card" style="padding: 20px; border-left: 4px solid var(--warning-color);">
            <div style="font-size: 0.875rem; color: var(--text-secondary); font-weight: 600; text-transform: uppercase;">Pending Reports</div>
            <div style="font-size: 2rem; font-weight: 700; color: var(--text-primary); margin-top: 8px;">{{ $stats['total_pending'] }}</div>
            <div style="font-size: 0.875rem; color: var(--warning-color); margin-top: 4px;">Action Required</div>
        </div>
        <div class="card" style="padding: 20px; border-left: 4px solid var(--danger-color);">
            <div style="font-size: 0.875rem; color: var(--text-secondary); font-weight: 600; text-transform: uppercase;">High Risk Issues</div>
            <div style="font-size: 2rem; font-weight: 700; color: var(--text-primary); margin-top: 8px;">{{ $stats['high_risk'] }}</div>
            <div style="font-size: 0.875rem; color: var(--danger-color); margin-top: 4px;">Immediate Attention</div>
        </div>
        <div class="card" style="padding: 20px; border-left: 4px solid var(--success-color);">
            <div style="font-size: 0.875rem; color: var(--text-secondary); font-weight: 600; text-transform: uppercase;">Resolved Today</div>
            <div style="font-size: 2rem; font-weight: 700; color: var(--text-primary); margin-top: 8px;">{{ $stats['resolved_today'] }}</div>
             <div style="font-size: 0.875rem; color: var(--success-color); margin-top: 4px;">Good Job!</div>
        </div>
    </div>

    <!-- Filters & Table -->
    <div class="card" style="padding: 0; overflow: hidden;">
        <!-- Filter Toolbar -->
        <div style="padding: 20px; border-bottom: 1px solid var(--border-color); background: var(--bg-color); display: flex; gap: 16px; flex-wrap: wrap; align-items: center;">
            <form method="GET" action="{{ route('admin.safety.reports') }}" style="display: contents;">
                <div style="flex: 1; min-width: 250px; position: relative;">
                    <span style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: var(--text-secondary);">🔍</span>
                    <input type="text" name="search" value="{{ request('search') }}" placeholder="Search reports, ads, or users..." 
                           style="width: 100%; padding: 10px 10px 10px 36px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 0.9rem;">
                </div>
                
                <select name="status" onchange="this.form.submit()" style="padding: 10px 16px; border: 1px solid var(--border-color); border-radius: 8px; background: white; cursor: pointer; min-width: 140px;">
                    <option value="">All Status</option>
                    <option value="pending" {{ request('status') == 'pending' ? 'selected' : '' }}>Pending</option>
                    <option value="reviewed" {{ request('status') == 'reviewed' ? 'selected' : '' }}>Reviewed</option>
                    <option value="resolved" {{ request('status') == 'resolved' ? 'selected' : '' }}>Resolved</option>
                    <option value="rejected" {{ request('status') == 'rejected' ? 'selected' : '' }}>Dismissed</option>
                </select>
                
                <button type="submit" style="display: none;">Filter</button>
                @if(request()->hasAny(['search', 'status']))
                    <a href="{{ route('admin.safety.reports') }}" style="color: var(--text-secondary); text-decoration: none; font-size: 0.9rem;">Clear Filters</a>
                @endif
            </form>
        </div>

        <div class="table-responsive">
            <table class="table" style="margin: 0;">
                <thead>
                    <tr style="background: var(--bg-color);">
                        <th style="padding: 16px; font-weight: 600; color: var(--text-secondary);">Risk Level</th>
                        <th style="padding: 16px; font-weight: 600; color: var(--text-secondary);">Reported Item</th>
                        <th style="padding: 16px; font-weight: 600; color: var(--text-secondary);">Reason & Details</th>
                        <th style="padding: 16px; font-weight: 600; color: var(--text-secondary);">Reporter</th>
                        <th style="padding: 16px; font-weight: 600; color: var(--text-secondary);">Status</th>
                        <th style="padding: 16px; font-weight: 600; color: var(--text-secondary); text-align: right;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($reports as $report)
                    <tr style="border-bottom: 1px solid var(--border-color);">
                        <td style="padding: 16px; vertical-align: top;">
                            @php
                                $riskLabel = $report->risk_label;
                                $riskClass = match($riskLabel) {
                                    'High' => 'bg-red-100 text-red-800',
                                    'Medium' => 'bg-yellow-100 text-yellow-800',
                                    'Low' => 'bg-green-100 text-green-800',
                                };
                                $riskColor = match($riskLabel) {
                                    'High' => '#fee2e2; color: #991b1b',
                                    'Medium' => '#fef3c7; color: #92400e',
                                    'Low' => '#dcfce7; color: #166534',
                                };
                            @endphp
                            <span class="badge" style="background: {{ explode(';', $riskColor)[0] }}; {{ explode(';', $riskColor)[1] }}; padding: 6px 10px; border-radius: 999px; font-weight: 600; font-size: 12px; display: inline-flex; align-items: center; gap: 4px;">
                                {{ $report->risk_score }}% {{ $riskLabel }}
                            </span>
                        </td>
                        <td style="padding: 16px; vertical-align: top;">
                            @if($report->ad)
                                <div style="display: flex; gap: 12px; align-items: flex-start;">
                                    @if($report->ad->images && count($report->ad->images) > 0)
                                        <img src="{{ $report->ad->images[0] }}" style="width: 48px; height: 48px; border-radius: 6px; object-fit: cover;" alt="Ad Image">
                                    @else
                                        <div style="width: 48px; height: 48px; border-radius: 6px; background: #eee; display: flex; align-items: center; justify-content: center; font-size: 20px;">🖼️</div>
                                    @endif
                                    <div>
                                        <a href="{{ route('admin.ads.index') }}?id={{ $report->ad->id }}" target="_blank" style="font-weight: 600; color: var(--text-primary); text-decoration: none; display: block; margin-bottom: 2px;">
                                            {{ Str::limit($report->ad->title, 40) }}
                                        </a>
                                        <small style="color: var(--text-secondary);">ID: #{{ $report->ad->id }} • {{ $report->ad->user->name ?? 'Unknown User' }}</small>
                                    </div>
                                </div>
                            @else
                                <span class="badge" style="background: #f3f4f6; color: #6b7280;">Ad Deleted</span>
                            @endif
                        </td>
                        <td style="padding: 16px; vertical-align: top;">
                            <div style="font-weight: 600; margin-bottom: 4px; color: var(--text-primary);">{{ ucfirst($report->reason) }}</div>
                            <div style="font-size: 0.875rem; color: var(--text-secondary); max-width: 300px; line-height: 1.4;">
                                {{ Str::limit($report->description, 100) }}
                            </div>
                        </td>
                        <td style="padding: 16px; vertical-align: top;">
                            @if($report->reporter)
                                <div style="display: flex; align-items: center; gap: 8px;">
                                    <div style="width: 24px; height: 24px; background: var(--primary-color); border-radius: 50%; color: white; display: flex; align-items: center; justify-content: center; font-size: 10px;">{{ substr($report->reporter->name, 0, 1) }}</div>
                                    <span style="font-size: 0.9rem;">{{ $report->reporter->name }}</span>
                                </div>
                            @else
                                <span style="font-style: italic; color: var(--text-secondary);">Anonymous Guest</span>
                            @endif
                            <div style="font-size: 11px; color: var(--text-secondary); margin-top: 4px;">{{ $report->created_at->diffForHumans() }}</div>
                        </td>
                        <td style="padding: 16px; vertical-align: top;">
                            @php
                                $statusColor = match($report->status) {
                                    'pending' => '#fee2e2; color: #ef4444',
                                    'reviewed' => '#fef3c7; color: #d97706',
                                    'resolved' => '#dcfce7; color: #166534',
                                    'rejected' => '#f3f4f6; color: #6b7280',
                                    default => '#f3f4f6; color: #6b7280'
                                };
                            @endphp
                            <span class="badge" style="background: {{ explode(';', $statusColor)[0] }}; {{ explode(';', $statusColor)[1] }}; padding: 4px 8px; border-radius: 6px; font-weight: 600; font-size: 11px; text-transform: uppercase;">
                                {{ $report->status }}
                            </span>
                            @if($report->action_taken)
                                <div style="margin-top: 6px; font-size: 11px; font-weight: 600; color: var(--primary-color);">
                                    Action: {{ ucfirst(str_replace('_', ' ', $report->action_taken)) }}
                                </div>
                            @endif
                        </td>
                        <td style="padding: 16px; text-align: right; vertical-align: top;">
                            @if($report->status === 'pending' || $report->status === 'reviewed')
                                <div class="dropdown">
                                    <button class="btn btn-sm" type="button" data-bs-toggle="dropdown" style="background: white; border: 1px solid var(--border-color); padding: 6px 12px; border-radius: 6px; font-weight: 500;">
                                        ⚡ Take Action
                                    </button>
                                    <ul class="dropdown-menu dropdown-menu-end" style="border: 1px solid var(--border-color); box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);">
                                        <li><a class="dropdown-item action-btn" href="#" data-action="suspend_ad" data-id="{{ $report->id }}" style="color: #dc2626;">🚫 Suspend Ad</a></li>
                                        <li><a class="dropdown-item action-btn" href="#" data-action="ban_user" data-id="{{ $report->id }}" style="color: #dc2626;">🔨 Ban User</a></li>
                                        <li><a class="dropdown-item action-btn" href="#" data-action="needs_edit" data-id="{{ $report->id }}" style="color: #d97706;">✏️ Request Edit</a></li>
                                        <li><hr class="dropdown-divider"></li>
                                        <li><a class="dropdown-item action-btn" href="#" data-action="dismiss" data-id="{{ $report->id }}" style="color: #6b7280;">✓ Dismiss (Safe)</a></li>
                                    </ul>
                                </div>
                            @else
                                <span style="font-size: 0.9rem; color: var(--text-secondary);">—</span>
                            @endif
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="6" style="text-align: center; padding: 40px;">
                            <div style="font-size: 48px; margin-bottom: 16px;">🛡️</div>
                            <h3 style="margin: 0 0 8px 0; color: var(--text-primary);">All Clear!</h3>
                            <p style="color: var(--text-secondary);">No reports found matching your criteria.</p>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        
        @if($reports->hasPages())
        <div style="padding: 20px; border-top: 1px solid var(--border-color);">
            {{ $reports->links() }}
        </div>
        @endif
    </div>
</div>

<!-- Safety Settings Modal (Kept functionality, updated styling slightly) -->
<div class="modal fade" id="settingsModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content" style="border-radius: 12px; border: none; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);">
            <div class="modal-header" style="border-bottom: 1px solid var(--border-color); padding: 20px;">
                <h5 class="modal-title" style="font-weight: 700;">Safety Automation Settings</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="{{ route('admin.safety.settings.update') }}" method="POST">
                @csrf
                <div class="modal-body" style="padding: 24px;">
                    <div class="mb-4">
                        <label class="form-label" style="font-weight: 600;">Auto-Suspend Threshold</label>
                        <input type="number" name="auto_suspend_threshold" class="form-control" value="{{ \App\Models\Setting::where('key', 'safety.auto_suspend_threshold')->value('value') ?? 5 }}" style="padding: 10px; border-radius: 8px;">
                        <small class="text-muted d-block mt-2">Ads receiving this many unique reports will be automatically suspended.</small>
                    </div>
                    <div class="mb-4">
                        <label class="form-label" style="font-weight: 600;">Auto-Ban User Threshold</label>
                        <input type="number" name="auto_ban_threshold" class="form-control" value="{{ \App\Models\Setting::where('key', 'safety.auto_ban_threshold')->value('value') ?? 10 }}" style="padding: 10px; border-radius: 8px;">
                        <small class="text-muted d-block mt-2">Users with this many confirmed violations will be banned.</small>
                    </div>
                    <div class="mb-4 form-check form-switch ps-0">
                        <div style="display: flex; align-items: center; gap: 12px;">
                            <input class="form-check-input ms-0" type="checkbox" name="ai_enabled" value="true" id="aiCheck" style="width: 2.5em; height: 1.5em;" {{ (\App\Models\Setting::where('key', 'safety.ai_enabled')->value('value') === 'true') ? 'checked' : '' }}>
                            <label class="form-check-label" for="aiCheck" style="font-weight: 600;">Enable AI Risk Analysis</label>
                        </div>
                        <input type="hidden" name="ai_enabled" value="false" disabled class="hidden-ai-input"> <!-- Fallback handling logic in JS if needed or standard HTML form behavior -->
                    </div>
                    <div class="mb-0">
                        <label class="form-label" style="font-weight: 600;">Scam Keywords</label>
                        <textarea name="scam_keywords" class="form-control" rows="3" style="border-radius: 8px; padding: 12px;">{{ \App\Models\Setting::where('key', 'safety.scam_keywords')->value('value') ?? 'western union,bank transfer,paytm only' }}</textarea>
                        <small class="text-muted d-block mt-2">Comma separated list of keywords that trigger high risk alerts.</small>
                    </div>
                </div>
                <div class="modal-footer" style="padding: 20px; border-top: 1px solid var(--border-color);">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" style="border-radius: 8px; font-weight: 600;">Close</button>
                    <button type="submit" class="btn btn-primary" style="border-radius: 8px; font-weight: 600; background: var(--primary-color); border: none;">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const actionBtns = document.querySelectorAll('.action-btn');
    
    // Fix for the checkbox value issue
    const aiCheck = document.getElementById('aiCheck');
    if(aiCheck) {
        aiCheck.addEventListener('change', function() {
            // Logic handled by server (checked sends value, unchecked sends nothing so we might need hidden input if we want strict false, but controller usually checks has() or 'true')
             // For strict processing:
             if (!this.checked) {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'ai_enabled';
                input.value = 'false';
                this.parentNode.appendChild(input);
             }
        });
    }

    actionBtns.forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const action = this.dataset.action;
            const reportId = this.dataset.id;
            
            if (!confirm('Are you sure you want to perform: ' + action.replace('_', ' ') + '?')) {
                return;
            }
            
            // Show loading state
            const originalText = this.innerHTML;
            this.innerHTML = 'Wait...';
            this.style.pointerEvents = 'none';
            
            fetch(`/admin/safety/reports/${reportId}/handle`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },
                body: JSON.stringify({
                    action: action,
                    notes: 'Manual action via Safety Dashboard'
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Show success feedback
                    alert('✅ Action successful');
                    location.reload();
                } else {
                    alert('❌ Error: ' + data.message);
                    this.innerHTML = originalText;
                    this.style.pointerEvents = 'auto';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('❌ An error occurred');
                this.innerHTML = originalText;
                this.style.pointerEvents = 'auto';
            });
        });
    });
});
</script>
@endsection
    
    <!-- Safety Settings Modal -->
    <div class="modal fade" id="settingsModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Safety Automation Settings</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form action="{{ route('admin.safety.settings.update') }}" method="POST">
                    @csrf
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Auto-Suspend Threshold (Reports)</label>
                            <input type="number" name="auto_suspend_threshold" class="form-control" value="{{ \App\Models\Setting::where('key', 'safety.auto_suspend_threshold')->value('value') ?? 5 }}">
                            <small class="text-muted">Ads receiving this many unique reports will be automatically suspended.</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Auto-Ban User Threshold (Confirmed Reports)</label>
                            <input type="number" name="auto_ban_threshold" class="form-control" value="{{ \App\Models\Setting::where('key', 'safety.auto_ban_threshold')->value('value') ?? 10 }}">
                            <small class="text-muted">Users with this many confirmed violations will be banned.</small>
                        </div>
                        <div class="mb-3 form-check form-switch">
                            <input type="hidden" name="ai_enabled" value="false">
                            <input class="form-check-input" type="checkbox" name="ai_enabled" value="true" id="aiCheck" {{ (\App\Models\Setting::where('key', 'safety.ai_enabled')->value('value') === 'true') ? 'checked' : '' }}>
                            <label class="form-check-label" for="aiCheck">Enable AI Risk Analysis</label>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Scam Keywords (Comma separated)</label>
                            <textarea name="scam_keywords" class="form-control" rows="2">{{ \App\Models\Setting::where('key', 'safety.scam_keywords')->value('value') ?? 'western union,bank transfer,paytm only' }}</textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">Save Changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="card-body">
        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Ad</th>
                        <th>Reporter</th>
                        <th>Risk Score (AI)</th>
                        <th>Reason</th>
                        <th>Status</th>
                        <th>Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($reports as $report)
                    <tr>
                        <td>{{ $report->id }}</td>
                        <td>
                            @if($report->ad)
                                <a href="{{ route('admin.ads.index') }}?id={{ $report->ad->id }}" target="_blank">
                                    {{ Str::limit($report->ad->title, 30) }}
                                </a>
                                <br>
                                <small class="text-muted">ID: {{ $report->ad->id }}</small>
                            @else
                                <span class="text-danger">Ad Deleted</span>
                            @endif
                        </td>
                        <td>
                            @if($report->reporter)
                                {{ $report->reporter->name }}
                                <br>
                                <small class="text-muted">{{ $report->reporter->email }}</small>
                            @else
                                <span class="text-muted">Guest</span>
                            @endif
                        </td>
                        <td>
                            @php
                                $riskScore = 0;
                                if ($report->reason === 'scam') $riskScore += 50;
                                if ($report->reporter_id === null) $riskScore += 10;
                                if (Str::contains(strtolower($report->description ?? ''), ['bank', 'money', 'transfer', 'western', 'paytm'])) $riskScore += 30;
                                
                                $riskClass = $riskScore >= 60 ? 'danger' : ($riskScore >= 30 ? 'warning' : 'success');
                                $riskLabel = $riskScore >= 60 ? 'High' : ($riskScore >= 30 ? 'Medium' : 'Low');
                            @endphp
                            <span class="badge bg-{{ $riskClass }}">
                                {{ $riskLabel }} 
                                <span class="badge bg-light text-dark ms-1">{{ $riskScore }}%</span>
                            </span>
                        </td>
                        <td>
                            <span class="badge bg-warning text-dark">{{ ucfirst($report->reason) }}</span>
                            @if($report->description)
                                <div class="mt-1 small">{{ Str::limit($report->description, 50) }}</div>
                            @endif
                        </td>
                        <td>
                            <span class="badge bg-{{ $report->status === 'pending' ? 'danger' : ($report->status === 'resolved' ? 'success' : 'secondary') }}">
                                {{ ucfirst($report->status) }}
                            </span>
                            @if($report->action_taken)
                                <div class="mt-1 small text-info">{{ ucfirst(str_replace('_', ' ', $report->action_taken)) }}</div>
                            @endif
                        </td>
                        <td>{{ $report->created_at->format('M d, Y H:i') }}</td>
                        <td>
                            @if($report->status === 'pending' || $report->status === 'reviewed')
                                <div class="btn-group">
                                    <button type="button" class="btn btn-sm btn-danger dropdown-toggle" data-bs-toggle="dropdown">
                                        Action
                                    </button>
                                    <ul class="dropdown-menu">
                                        <li><a class="dropdown-item text-danger action-btn" href="#" data-action="suspend_ad" data-id="{{ $report->id }}">Suspend Ad</a></li>
                                        <li><a class="dropdown-item text-danger action-btn" href="#" data-action="ban_user" data-id="{{ $report->id }}">Ban User & Suspend Ad</a></li>
                                        <li><a class="dropdown-item text-warning action-btn" href="#" data-action="needs_edit" data-id="{{ $report->id }}">Request Edit</a></li>
                                        <li><hr class="dropdown-divider"></li>
                                        <li><a class="dropdown-item text-secondary action-btn" href="#" data-action="dismiss" data-id="{{ $report->id }}">Dismiss (Reject Report)</a></li>
                                    </ul>
                                </div>
                            @else
                                <span class="text-muted">No actions</span>
                            @endif
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="7" class="text-center">No reports found.</td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        
        <div class="mt-4">
            {{ $reports->links() }}
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const actionBtns = document.querySelectorAll('.action-btn');
    
    actionBtns.forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const action = this.dataset.action;
            const reportId = this.dataset.id;
            
            if (!confirm('Are you sure you want to perform: ' + action.replace('_', ' ') + '?')) {
                return;
            }
            
            fetch(`/admin/safety/reports/${reportId}/handle`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },
                body: JSON.stringify({
                    action: action,
                    notes: 'Manual action via Safety Dashboard'
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Action successful');
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred');
            });
        });
    });
});
</script>
@endsection
