<?php

namespace App\Livewire;

use App\Models\User;
use App\Models\Batch;
use App\Models\SchoolClass;
use App\Services\PromotionService;
use App\Traits\HasNotifications;
use Livewire\Component;

class PromotionIndividual extends Component
{
    use HasNotifications;
    
    public $studentId = '';
    public $toClassId = '';
    public $toBatchId = '';
    public $createNewBatch = true;
    public $selectedStudent = null;
    public $studentSearch = '';
    public $availableBatches = [];
    public $demotionWarning = '';
    
    protected $promotionService;
    
    public function boot(PromotionService $promotionService)
    {
        $this->promotionService = $promotionService;
    }
    
    public function updatedStudentId()
    {
        if ($this->studentId) {
            $this->selectedStudent = User::with('batch.schoolClass')->find($this->studentId);
        } else {
            $this->selectedStudent = null;
        }
        $this->checkForDemotion();
    }
    
    public function updatedToClassId()
    {
        $this->loadAvailableBatches();
        $this->toBatchId = '';
        $this->checkForDemotion();
    }
    
    public function updatedCreateNewBatch()
    {
        if ($this->createNewBatch) {
            $this->toBatchId = '';
        }
    }
    
    public function selectStudent($studentId)
    {
        $this->studentId = $studentId;
        $this->selectedStudent = User::with('batch.schoolClass')->find($studentId);
        $this->studentSearch = '';
        $this->checkForDemotion();
    }
    
    private function checkForDemotion()
    {
        $this->demotionWarning = '';
        
        if ($this->selectedStudent && $this->toClassId) {
            $fromClass = $this->selectedStudent->batch->schoolClass;
            $toClass = SchoolClass::find($this->toClassId);
            
            if ($fromClass && $toClass && $toClass->order < $fromClass->order) {
                $this->demotionWarning = "Warning: Moving student from {$fromClass->display_name} to {$toClass->display_name} is a demotion to a lower class.";
            }
        }
    }
    
    private function loadAvailableBatches()
    {
        if ($this->toClassId) {
            $this->availableBatches = Batch::where('school_class_id', $this->toClassId)
                ->where('is_active', true)
                ->where('graduated', false)
                ->get();
        } else {
            $this->availableBatches = [];
        }
    }
    
    public function confirmPromotion()
    {
        $rules = [
            'studentId' => 'required|exists:users,id',
            'toClassId' => 'required|exists:school_classes,id'
        ];
        
        if (!$this->createNewBatch) {
            $rules['toBatchId'] = 'required|exists:batches,id';
        }
        
        $this->validate($rules);
        
        $student = User::find($this->studentId);
        $toClass = SchoolClass::find($this->toClassId);
        
        $this->confirmAction(
            'Confirm Promotion',
            "Are you sure you want to promote {$student->name} to {$toClass->display_name}?",
            'Yes, Promote!',
            'Cancel'
        );
    }
    
    #[\Livewire\Attributes\On('action-confirmed')]
    public function promote()
    {
        try {
            $result = $this->promotionService->promoteIndividualStudent(
                $this->studentId,
                $this->toClassId,
                $this->createNewBatch ? null : $this->toBatchId
            );
            
            if ($result['success']) {
                $message = 'Student promoted successfully!';
                
                if (!empty($result['warnings'])) {
                    foreach ($result['warnings'] as $warning) {
                        $this->showToast('warning', $warning, 'Promotion Warning');
                    }
                }
                
                $this->showToast('success', $message, 'Promotion Complete');
                
                $this->reset(['studentId', 'toClassId', 'toBatchId', 'selectedStudent', 'studentSearch']);
                $this->createNewBatch = true;
                $this->availableBatches = [];
            } else {
                $this->showToast('error', 'Failed to promote student', 'Promotion Error');
            }
            
        } catch (\Exception $e) {
            $this->showToast('error', 'Error promoting student: ' . $e->getMessage(), 'Promotion Error');
        }
    }
    
    public function render()
    {
        // Search results for clickable list
        $searchResults = collect();
        if ($this->studentSearch) {
            $searchResults = 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 . '%');
                })
                ->orderBy('firstname')
                ->limit(50)
                ->get();
        }
        
        // All students for dropdown
        $allStudents = User::whereHas('batch')
            ->whereDoesntHave('roles')
            ->orderBy('firstname')
            ->get();
        
        $classes = SchoolClass::where('is_active', true)->orderBy('order')->get();
        
        return view('livewire.promotion-individual', [
            'searchResults' => $searchResults,
            'students' => $allStudents,
            'classes' => $classes
        ]);
    }
}