<?php

namespace App\Livewire\Results;

use Livewire\Component;
use App\Models\User;
use App\Models\SchoolSession;
use App\Models\Result;
use App\Services\ResultService;
use App\Traits\HasNotifications;
use Illuminate\Support\Facades\Auth;

class ApprovalForm extends Component
{
    use HasNotifications;

    public $selectedClass = '';
    public $selectedBatch = '';
    public $selectedStudents = [];
    public $selectedSession = '';
    public $classes = [];
    public $batches = [];
    public $students = [];
    public $sessions = [];
    public $studentResults = [];
    
    // Affective Traits
    public $punctuality = 4.0;
    public $mental_alertness = 4.0;
    public $attentiveness = 4.0;
    public $respect = 4.0;
    public $neatness = 4.0;
    public $politeness = 4.0;
    public $honesty = 4.0;
    public $relationship_with_peers = 4.0;
    public $attitude_to_school = 4.0;
    public $teamwork = 4.0;
    public $completes_school_work_promptly = 4.0;
    
    // Psychomotor Skills
    public $reading = 4.0;
    public $verbal_fluency_diction = 4.0;
    public $handwriting = 4.0;
    public $musical_skills = 4.0;
    public $creative_arts = 4.0;
    public $physical_education = 4.0;
    public $general_reasoning = 4.0;
    
    public $principal_remarks = 'Impressive result, keep it up!';

    public function mount()
    {
        $user = Auth::user();
        
        // Check if user can approve results based on settings
        if (!$user->canApproveResults()) {
            abort(403, 'You do not have permission to approve results.');
        }
        
        $resultService = new ResultService();
        $this->classes = $resultService->getClassesForUser($user);
        $this->sessions = SchoolSession::orderBy('start_year', 'desc')->orderBy('name')->get();
        
        // Auto-select the currently active session
        $activeSession = $this->sessions->where('is_active', true)->first();
        if ($activeSession) {
            $this->selectedSession = $activeSession->id;
        }
    }

    public function updatedSelectedSession()
    {
        $this->selectedClass = '';
        $this->selectedBatch = '';
        $this->batches = [];
        $this->students = collect();
        $this->selectedStudents = [];
        $this->studentResults = [];
    }

    public function updatedSelectedClass()
    {
        $this->selectedBatch = '';
        $this->batches = [];
        $this->students = collect();
        $this->selectedStudents = [];
        $this->studentResults = [];
        
        if ($this->selectedClass) {
            $this->loadBatches();
        }
    }
    
    public function loadBatches()
    {
        $this->batches = \App\Models\Batch::where('school_class_id', $this->selectedClass)
            ->where('is_active', true)
            ->where('graduated', false)
            ->orderBy('name')
            ->get();
    }
    
    public function updatedSelectedBatch()
    {
        $this->students = collect();
        $this->selectedStudents = [];
        $this->studentResults = [];
        
        if ($this->selectedBatch && $this->selectedSession) {
            $resultService = new ResultService();
            $allStudents = $resultService->getStudentsByBatch($this->selectedBatch)->sortBy('firstname');
            
            // Include students with unapproved results for this session
            $this->students = $allStudents->filter(function($student) {
                $hasResults = Result::where('student_id', $student->id)
                    ->where('session_id', $this->selectedSession)
                    ->exists();
                
                if (!$hasResults) {
                    return false; // No results at all
                }
                
                // Check if there's an active (non-soft-deleted) approval record
                $hasActiveApproval = \App\Models\ResultApproval::where('student_id', $student->id)
                    ->where('session_id', $this->selectedSession)
                    ->exists();
                
                return !$hasActiveApproval; // Include only if no active approval
            });
        }
    }

    public function updatedSelectedStudents()
    {
        $this->studentResults = [];
    }

    public function loadStudentResults()
    {
        $this->studentResults = [];
        
        if (!$this->selectedClass) return;
        
        $resultService = new ResultService();
        $allSubjects = $resultService->getSubjectsByClass($this->selectedClass);
        
        foreach ($this->selectedStudents as $studentId) {
            $student = User::find($studentId);
            if (!$student) continue;
            
            $results = Result::with(['subject'])
                ->where('student_id', $studentId)
                ->where('session_id', $this->selectedSession)
                ->get()
                ->keyBy('subject_id');
            
            $subjectResults = [];
            $totalScore = 0;
            
            foreach ($allSubjects as $subject) {
                if (isset($results[$subject->id])) {
                    $result = $results[$subject->id];
                    $subjectResults[] = [
                        'subject' => $subject,
                        'ca_score' => $result->ca_score,
                        'exam_score' => $result->exam_score,
                        'total_score' => $result->total_score,
                        'has_result' => true
                    ];
                    $totalScore += $result->total_score;
                } else {
                    $subjectResults[] = [
                        'subject' => $subject,
                        'ca_score' => 'N/A',
                        'exam_score' => 'N/A',
                        'total_score' => 'N/A',
                        'has_result' => false
                    ];
                }
            }
            
            $this->studentResults[$studentId] = [
                'student' => $student,
                'results' => $subjectResults,
                'total' => $totalScore
            ];
        }
    }

    public function approveResults()
    {
        $this->validate([
            'selectedStudents' => 'required|array|min:1',
            'selectedSession' => 'required',
            'punctuality' => 'required|numeric|min:0|max:5',
            'mental_alertness' => 'required|numeric|min:0|max:5',
            'attentiveness' => 'required|numeric|min:0|max:5',
            'respect' => 'required|numeric|min:0|max:5',
            'neatness' => 'required|numeric|min:0|max:5',
            'politeness' => 'required|numeric|min:0|max:5',
            'honesty' => 'required|numeric|min:0|max:5',
            'relationship_with_peers' => 'required|numeric|min:0|max:5',
            'attitude_to_school' => 'required|numeric|min:0|max:5',
            'teamwork' => 'required|numeric|min:0|max:5',
            'completes_school_work_promptly' => 'required|numeric|min:0|max:5',
            'reading' => 'required|numeric|min:0|max:5',
            'verbal_fluency_diction' => 'required|numeric|min:0|max:5',
            'handwriting' => 'required|numeric|min:0|max:5',
            'musical_skills' => 'required|numeric|min:0|max:5',
            'creative_arts' => 'required|numeric|min:0|max:5',
            'physical_education' => 'required|numeric|min:0|max:5',
            'general_reasoning' => 'required|numeric|min:0|max:5',
            'principal_remarks' => 'required|string',
        ]);

        $approvalData = [
            'punctuality' => $this->punctuality,
            'mental_alertness' => $this->mental_alertness,
            'attentiveness' => $this->attentiveness,
            'respect' => $this->respect,
            'neatness' => $this->neatness,
            'politeness' => $this->politeness,
            'honesty' => $this->honesty,
            'relationship_with_peers' => $this->relationship_with_peers,
            'attitude_to_school' => $this->attitude_to_school,
            'teamwork' => $this->teamwork,
            'completes_school_work_promptly' => $this->completes_school_work_promptly,
            'reading' => $this->reading,
            'verbal_fluency_diction' => $this->verbal_fluency_diction,
            'handwriting' => $this->handwriting,
            'musical_skills' => $this->musical_skills,
            'creative_arts' => $this->creative_arts,
            'physical_education' => $this->physical_education,
            'general_reasoning' => $this->general_reasoning,
            'principal_remarks' => $this->principal_remarks,
        ];

        $resultService = new ResultService();
        $resultService->approveResults(
            $this->selectedStudents,
            $this->selectedSession,
            $approvalData,
            Auth::id()
        );

        $this->showToast('success', 'Results approved successfully!', 'Results Approval');
        
        // Refresh students list to exclude newly approved students
        $this->updatedSelectedBatch();
        
        // Clear student results and selected students
        $this->selectedStudents = [];
        $this->studentResults = [];
    }
    
    public function disapproveResults()
    {
        $this->validate([
            'selectedStudents' => 'required|array|min:1',
            'selectedSession' => 'required',
        ]);

        $resultService = new ResultService();
        $resultService->disapproveResults(
            $this->selectedStudents,
            $this->selectedSession,
            Auth::id()
        );

        $this->showToast('warning', 'Results disapproved successfully!', 'Results Disapproval');
        
        // Refresh students list
        $this->updatedSelectedBatch();
        
        // Clear student results and selected students
        $this->selectedStudents = [];
        $this->studentResults = [];
    }

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