<?php

namespace App\Livewire\Results;

use Livewire\Component;
use App\Services\ViewResultsService;
use App\Traits\HasNotifications;

class ViewResults extends Component
{
    use HasNotifications;

    public $classId = '';
    public $batchId = '';
    public $sessionId = '';
    public $studentSearch = '';
    public $selectedStudent = null;
    public $filteredStudentId = null;
    public $classes = [];
    public $batches = [];
    public $sessions = [];
    public $studentsData = null;
    public $selectedStudentData = null;
    public $loading = false;

    public function mount()
    {
        try {
            $viewResultsService = new ViewResultsService();
            $this->classes = $viewResultsService->getClassesForUser(auth()->user());
            $this->sessions = $viewResultsService->getActiveSessions();
            
            // Set active session by default
            $activeSession = \App\Models\SchoolSession::where('is_active', true)->first();
            if ($activeSession) {
                $this->sessionId = $activeSession->id;
            }
        } catch (\Exception $e) {
            $this->classes = collect();
            $this->sessions = collect();
        }
    }

    public function updatedClassId()
    {
        try {
            if ($this->classId) {
                $viewResultsService = new ViewResultsService();
                $this->batches = $viewResultsService->getBatchesByClass($this->classId);
                $this->batchId = '';
                $this->studentsData = null;
            } else {
                $this->batches = [];
                $this->batchId = '';
                $this->studentsData = null;
            }
        } catch (\Exception $e) {
            $this->batches = [];
            $this->batchId = '';
            $this->studentsData = null;
        }
    }

    public function updatedBatchId()
    {
        $this->studentSearch = '';
        $this->filteredStudentId = null;
        $this->studentsData = null;
    }

    public function updatedStudentSearch()
    {
        if ($this->filteredStudentId) {
            $this->filteredStudentId = null;
            $this->selectedStudent = null;
            $this->studentsData = null;
        }
    }

    public function updatedSessionId()
    {
        $this->studentsData = null;
    }

    public function loadStudents()
    {
        if (!$this->classId || !$this->batchId || !$this->sessionId) {
            $this->showError('Please select class, batch, and session.');
            return;
        }

        $this->loading = true;

        try {
            $viewResultsService = new ViewResultsService();
            
            if ($this->filteredStudentId) {
                // Check if selected student has approved results
                $approval = \App\Models\ResultApproval::where('student_id', $this->filteredStudentId)
                    ->where('session_id', $this->sessionId)
                    ->first();
                
                if ($approval) {
                    // Student has approved results, get their data
                    $allStudentsData = $viewResultsService->getStudentsWithResultStatus($this->batchId, $this->sessionId);
                    $this->studentsData = collect($allStudentsData)->filter(function($data) {
                        return $data['student']->id == $this->filteredStudentId;
                    })->values()->toArray();
                } else {
                    // Student has no approved results, return empty array to show info card
                    $this->studentsData = [];
                }
            } else {
                // No specific student selected, get all students with approved results
                $this->studentsData = $viewResultsService->getStudentsWithResultStatus($this->batchId, $this->sessionId);
            }
        } catch (\Exception $e) {
            $this->showError('Error loading students data.');
            $this->studentsData = null;
        } finally {
            $this->loading = false;
        }
    }

    public function viewStudentResult($studentId)
    {
        try {
            $viewResultsService = new ViewResultsService();
            $this->selectedStudentData = $viewResultsService->getStudentCompleteResult($studentId, $this->sessionId);
            
            if (!$this->selectedStudentData) {
                $this->showError('Student result not found.');
            }
        } catch (\Exception $e) {
            $this->showError('Error loading student result.');
        }
    }

    public function closeStudentResult()
    {
        $this->selectedStudentData = null;
    }

    public function unapproveResult($studentId)
    {
        try {
            $student = \App\Models\User::find($studentId);
            if (!$student) {
                $this->showError('Student not found.');
                return;
            }

            // Update ALL results for this student and session as unapproved
            \App\Models\Result::where('student_id', $studentId)
                ->where('session_id', $this->sessionId)
                ->update([
                    'approved' => false,
                    'approved_at' => null,
                    'approved_by' => null,
                ]);

            $approval = \App\Models\ResultApproval::where('student_id', $studentId)
                ->where('session_id', $this->sessionId)
                ->first();

            if ($approval) {
                $approval->delete();
            }
            
            $this->showSuccess("Result approval for {$student->name} has been removed.");
            $this->loadStudents(); // Refresh the data
        } catch (\Exception $e) {
            $this->showError('Error removing result approval.');
        }
    }

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

    public function selectStudent($studentId)
    {
        $this->selectedStudent = \App\Models\User::with('batch.schoolClass')->find($studentId);
        $this->filteredStudentId = $studentId;
        
        if ($this->selectedStudent && $this->selectedStudent->batch) {
            // Update class dropdown first
            $this->classId = $this->selectedStudent->batch->school_class_id;
            
            // Trigger the updatedClassId method to load batches
            $this->updatedClassId();
            
            // Then update batch dropdown
            $this->batchId = $this->selectedStudent->batch_id;
            
            // Load students data
            $this->loadStudents();
        }
    }
    
    public function clearFilter()
    {
        $this->studentSearch = '';
        $this->filteredStudentId = null;
        $this->selectedStudent = null;
        $this->loadStudents();
    }
    
    public function getStudentsForSearch()
    {
        $user = auth()->user();
        
        if ($user->isAdmin() || $user->isHeadTeacher()) {
            return \App\Models\User::whereHas('batch')
                ->whereDoesntHave('roles')
                ->where(function($q) {
                    $q->where('firstname', 'like', '%' . $this->studentSearch . '%')
                      ->orWhere('middlename', 'like', '%' . $this->studentSearch . '%')
                      ->orWhere('surname', 'like', '%' . $this->studentSearch . '%')
                      ->orWhere('student_id', 'like', '%' . $this->studentSearch . '%');
                })
                ->with('batch.schoolClass')
                ->orderBy('firstname')
                ->limit(10)
                ->get();
        }
        
        if ($user->isTeacher()) {
            $classIds = $user->classes()->pluck('school_classes.id');
            
            return \App\Models\User::whereHas('batch', function($q) use ($classIds) {
                    $q->whereIn('school_class_id', $classIds);
                })
                ->whereDoesntHave('roles')
                ->where(function($q) {
                    $q->where('firstname', 'like', '%' . $this->studentSearch . '%')
                      ->orWhere('middlename', 'like', '%' . $this->studentSearch . '%')
                      ->orWhere('surname', 'like', '%' . $this->studentSearch . '%')
                      ->orWhere('student_id', 'like', '%' . $this->studentSearch . '%');
                })
                ->with('batch.schoolClass')
                ->orderBy('firstname')
                ->limit(10)
                ->get();
        }
        
        return collect();
    }
    
    public function canUnapprove()
    {
        $user = auth()->user();
        
        if ($user->isAdmin()) {
            return \App\Models\Setting::get('allow_admin_unapprove_results', false);
        }
        
        if ($user->isHeadTeacher()) {
            return \App\Models\Setting::get('allow_head_teacher_unapprove_results', false);
        }
        
        if ($user->isTeacher()) {
            return \App\Models\Setting::get('allow_teacher_unapprove_results', false);
        }
        
        return false;
    }
}
