@extends('layouts.app')

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <h1 class="mb-4">Performance Analysis Dashboard</h1>
            
            <!-- Period Filter -->
            <div class="card mb-4">
                <div class="card-body">
                    <form method="GET" class="row">
                        <div class="col-md-3">
                            <label>Period Type</label>
                            <select name="period" class="form-control">
                                <option value="monthly" {{ $periodType == 'monthly' ? 'selected' : '' }}>Monthly</option>
                                <option value="quarterly" {{ $periodType == 'quarterly' ? 'selected' : '' }}>Quarterly</option>
                                <option value="half_yearly" {{ $periodType == 'half_yearly' ? 'selected' : '' }}>Half Yearly</option>
                                <option value="yearly" {{ $periodType == 'yearly' ? 'selected' : '' }}>Yearly</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label>Year</label>
                            <select name="year" class="form-control">
                                @for($y = 2024; $y <= date('Y'); $y++)
                                    <option value="{{ $y }}" {{ $year == $y ? 'selected' : '' }}>{{ $y }}</option>
                                @endfor
                            </select>
                        </div>
                        <div class="col-md-3 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary">Filter</button>
                        </div>
                    </form>
                </div>
            </div>
            
            <!-- AI Recommendations -->
        <div class="card mb-4 bg-light">
            <div class="card-header bg-primary text-white">
                <h4>
                    @if($recommendations['recommendations']['provider'] ?? '' == 'DeepSeek')
                        🤖 DeepSeek AI-Powered Recommendations
                        <small class="text-light">(Powered by DeepSeek AI)</small>
                    @elseif($recommendations['recommendations']['type'] == 'deepseek_ai')
                        🤖 DeepSeek AI Analysis
                    @else
                        📊 System Recommendations
                    @endif
                </h4>
            </div>
            <div class="card-body">
                @if(isset($recommendations['recommendations']['type']) && $recommendations['recommendations']['type'] == 'deepseek_ai')
                    <!-- DeepSeek AI Response -->
                    <div class="alert alert-success">
                        <strong>✓ AI Analysis Complete</strong> - Generated by DeepSeek AI at {{ $recommendations['recommendations']['generated_at'] }}
                    </div>
                    
                    @if(!empty($recommendations['recommendations']['sections']))
                        @foreach($recommendations['recommendations']['sections'] as $sectionTitle => $sectionContent)
                            <div class="mb-4">
                                <h5>{{ ucwords(str_replace('_', ' ', $sectionTitle)) }}</h5>
                                <div class="well well-sm p-3 bg-white rounded">
                                    {!! nl2br(e($sectionContent)) !!}
                                </div>
                            </div>
                        @endforeach
                    @else
                        <div class="recommendation-content">
                            {!! nl2br(e($recommendations['recommendations']['raw_content'])) !!}
                        </div>
                    @endif
                    
                @elseif(isset($recommendations['recommendations']['content']['urgent_actions']))
                    <!-- Rule-based recommendations -->
                    <h5>🚨 Urgent Actions Required:</h5>
                    <ul>
                        @foreach($recommendations['recommendations']['content']['urgent_actions'] as $action)
                            <li>
                                <strong>{{ $action['station'] }}</strong> ({{ $action['current_rate'] }}%): 
                                {{ $action['action'] }}
                                <span class="badge badge-danger">{{ $action['priority'] }}</span>
                                @if(isset($action['deadline']))
                                    <small class="text-muted">Deadline: {{ $action['deadline'] }}</small>
                                @endif
                            </li>
                        @endforeach
                    </ul>
                    
                    <h5 class="mt-4">📋 Improvement Plans:</h5>
                    @foreach($recommendations['recommendations']['content']['improvement_plans'] as $plan)
                        <div class="card mb-2">
                            <div class="card-body">
                                <h6>{{ $plan['station'] }}</h6>
                                <p><strong>Target:</strong> {{ $plan['target'] }}</p>
                                <ul>
                                    @foreach($plan['actions'] as $action)
                                        <li>{{ $action }}</li>
                                    @endforeach
                                </ul>
                                @if(isset($plan['resources_needed']))
                                    <p><strong>Resources Needed:</strong> {{ implode(', ', $plan['resources_needed']) }}</p>
                                @endif
                            </div>
                        </div>
                    @endforeach
                    
                    <h5 class="mt-4">⭐ Best Practices to Adopt:</h5>
                    @foreach($recommendations['recommendations']['content']['best_practices'] as $practice)
                        <div class="alert alert-info">
                            <strong>{{ $practice['station'] }}</strong> ({{ $practice['rate'] }}%): 
                            {{ $practice['practice'] }}
                            @if(isset($practice['actions_to_copy']))
                                <ul class="mt-2 mb-0">
                                    @foreach($practice['actions_to_copy'] as $action)
                                        <li>{{ $action }}</li>
                                    @endforeach
                                </ul>
                            @endif
                        </div>
                    @endforeach
                    
                    <h5 class="mt-4">🎯 Targets for Next Quarter:</h5>
                    <ul>
                        @foreach($recommendations['recommendations']['content']['targets'] as $key => $target)
                            @if(!is_array($target))
                                <li><strong>{{ ucwords(str_replace('_', ' ', $key)) }}:</strong> {{ $target }}</li>
                            @endif
                        @endforeach
                    </ul>
                    
                    @if(isset($recommendations['recommendations']['content']['action_plan_summary']))
                        <h5 class="mt-4">📅 Action Plan Timeline:</h5>
                        <ul>
                            @foreach($recommendations['recommendations']['content']['action_plan_summary'] as $period => $action)
                                <li><strong>{{ $period }}:</strong> {{ $action }}</li>
                            @endforeach
                        </ul>
                    @endif
                    
                    @if(isset($recommendations['recommendations']['note']))
                        <div class="alert alert-warning mt-3">
                            <small>ℹ️ {{ $recommendations['recommendations']['note'] }}</small>
                        </div>
                    @endif
                @endif
                
                <!-- Summary -->
                <div class="alert alert-success mt-3">
                    <h5>📊 Summary Verdict:</h5>
                    <p>{{ $recommendations['summary']['verdict'] }}</p>
                    <p><strong>Key Finding:</strong> {{ $recommendations['summary']['key_finding'] }}</p>
                    <p><strong>Recommended Action:</strong> {{ $recommendations['summary']['recommended_action'] }}</p>
                    @if(isset($recommendations['summary']['quick_wins']))
                        <p><strong>Quick Wins:</strong> {{ $recommendations['summary']['quick_wins'] }}</p>
                    @endif
                </div>
            </div>
        </div>
            
            <!-- Station Performance Table -->
            <div class="card mb-4">
                <div class="card-header">
                    <h4>Station Performance Overview</h4>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead class="thead-dark">
                                <tr>
                                    <th>Rank</th>
                                    <th>Station Name</th>
                                    <th>Average Rate</th>
                                    <th>Trend</th>
                                    <th>Performance Level</th>
                                    <th>Action Priority</th>
                                    <th>Details</th>
                                </tr>
                            </thead>
                            <tbody>
                                @php $rank = 1; @endphp                                @foreach($stationPerformance as $station => $data)
                                    <tr>
                                        <td>{{ $rank++ }}</td>
                                        <td>{{ $station }}</td>
                                        <td>
                                            <span class="badge badge-{{ $data['avg_rate'] >= 80 ? 'success' : ($data['avg_rate'] >= 70 ? 'warning' : 'danger') }} badge-pill">
                                                {{ $data['avg_rate'] }}%
                                            </span>
                                        </td>
                                        <td>{{ $data['trend'] }}</td>
                                        <td>
                                            @if($data['avg_rate'] >= 85)
                                                <span class="badge badge-success">Excellent</span>
                                            @elseif($data['avg_rate'] >= 75)
                                                <span class="badge badge-info">Good</span>
                                            @elseif($data['avg_rate'] >= 65)
                                                <span class="badge badge-warning">Average</span>
                                            @else
                                                <span class="badge badge-danger">Poor</span>
                                            @endif
                                        </td>
                                        <td>
                                            @if($data['avg_rate'] < 70)
                                                <span class="badge badge-danger">High</span>
                                            @elseif($data['avg_rate'] < 80)
                                                <span class="badge badge-warning">Medium</span>
                                            @else
                                                <span class="badge badge-success">Low</span>
                                            @endif
                                        </td>
                                        <td>
                                            <a href="{{ route('successrate.station.details', $station) }}" class="btn btn-sm btn-info">
                                                View Details
                                            </a>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- Overall Averages -->
            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h5>Overall Monthly Averages</h5>
                        </div>
                        <div class="card-body">
                            <canvas id="monthlyChart"></canvas>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h5>Quarterly Performance Summary</h5>
                        </div>
                        <div class="card-body">
                            <table class="table">
                                <thead>
                                    <tr><th>Quarter</th><th>Overall Average</th></tr>
                                </thead>
                                <tbody>
                                    @foreach($overallQuarterly as $quarter)
                                        <tr>
                                            <td>Q{{ $quarter->quarter }} {{ $quarter->year }}</td>
                                            <td>{{ number_format($quarter->overall_avg, 2) }}%</td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Include Chart.js for visualizations -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    var ctx = document.getElementById('monthlyChart').getContext('2d');
    var monthlyData = @json($overallMonthly);
    var chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: monthlyData.map(m => m.month + '/' + m.year),
            datasets: [{
                label: 'Overall Success Rate',
                data: monthlyData.map(m => m.overall_avg),
                borderColor: 'rgb(75, 192, 192)',
                tension: 0.1
            }]
        }
    });
</script>
@endsection