<?php

namespace App\Livewire\Results;

use Livewire\Component;
use App\Services\AnnualResultService;
use App\Traits\HasNotifications;
use App\Models\SchoolSession;
use App\Models\Subject;

class AnnualResults extends Component
{
    use HasNotifications;

    public $year;
    public $classId;
    public $batchId;
    public $classes = [];
    public $batches = [];
    public $years = [];
    public $annualData = [];
    public $selectedYear;
    public $selectedClass;
    public $selectedBatch;
    public $sessions = [];
    public $subjects = [];
    public $classStats = [];

    protected $annualResultService;

    public function boot(AnnualResultService $annualResultService)
    {
        $this->annualResultService = $annualResultService;
    }

    public function mount()
    {
        $this->classes = $this->annualResultService->getClassesForUser(auth()->user());
        $this->years = $this->annualResultService->getAvailableYears();
    }

    public function updatedClassId()
    {
        $this->batchId = null;
        $this->batches = [];
        $this->annualData = [];
        $this->sessions = [];
        $this->subjects = [];
        $this->classStats = [];

        if ($this->classId) {
            $this->batches = \App\Models\Batch::where('school_class_id', $this->classId)
                ->where('is_active', true)
                ->orderBy('name')
                ->get();
        }
    }

    public function loadAnnualResults()
    {
        if (!$this->year || !$this->classId) {
            $this->showError('Please select both year and class');
            return;
        }

        $data = $this->annualResultService->getAnnualResultData($this->year, $this->classId, $this->batchId);

        if (!$data) {
            $this->showError('No data found for the selected criteria');
            return;
        }

        $this->annualData = $data['annualData'];
        $this->selectedYear = $data['year'];
        $this->selectedClass = $data['class'];
        $this->selectedBatch = $data['batch'];
        $this->sessions = $data['sessions'] ?? [];
        $this->subjects = $data['subjects'] ?? [];
        $this->classStats = $this->calculateClassStats();

        $this->dispatch('initClassGradeChart', $this->getChartData());
        $this->showSuccess('Annual results loaded successfully');
    }

    private function calculateClassStats()
    {
        if (empty($this->annualData)) {
            return [];
        }

        $totalStudents = count($this->annualData);
        $totalAnnualScore = array_sum(array_column($this->annualData, 'annual_grand_total'));
        $totalPossibleScore = array_sum(array_column($this->annualData, 'total_possible_score'));
        $averagePercentage = $totalPossibleScore > 0 ? round(($totalAnnualScore / $totalPossibleScore) * 100, 2) : 0;
        
        $passPercentage = settings('annual_pass_percentage', 50);
        $passedStudents = collect($this->annualData)->filter(function($student) use ($passPercentage) {
            return $student['annual_average'] >= $passPercentage;
        })->count();

        $gradeDistribution = ['A' => 0, 'B' => 0, 'C' => 0, 'D' => 0, 'E' => 0, 'F' => 0];
        foreach ($this->annualData as $student) {
            foreach ($student['annual_grades'] as $grade => $count) {
                $gradeDistribution[$grade] += $count;
            }
        }

        return [
            'total_students' => $totalStudents,
            'total_sessions' => count($this->sessions),
            'class_average' => $averagePercentage,
            'passed_students' => $passedStudents,
            'failed_students' => $totalStudents - $passedStudents,
            'grade_distribution' => $gradeDistribution
        ];
    }

    private function getChartData()
    {
        if (empty($this->annualData)) {
            return [];
        }

        $studentNames = [];
        $annualAverages = [];
        
        foreach ($this->annualData as $student) {
            $studentNames[] = $student['student']->firstname . ' ' . substr($student['student']->surname ?? '', 0, 1) . '.';
            $annualAverages[] = $student['annual_average'];
        }

        return [
            'labels' => $studentNames,
            'data' => $annualAverages
        ];
    }

    public function getPrintUrl()
    {
        if (!$this->selectedYear || !$this->selectedClass) {
            return null;
        }

        return route('results.print-class-annual', [
            'class' => $this->selectedClass->id,
            'year' => $this->selectedYear,
            'batch' => $this->selectedBatch ? $this->selectedBatch->id : null
        ]);
    }

    public function render()
    {
        return view('livewire.results.annual-results');
    }
}