<?php

namespace App\Livewire;

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

class PromotionByClass extends Component
{
    use HasNotifications;
    
    public $fromClassId = '';
    public $toClassId = '';
    public $onlyEligible = false;
    public $candidates = [];
    public $showCandidates = false;
    public $demotionWarning = '';
    
    protected $promotionService;
    
    public function boot(PromotionService $promotionService)
    {
        $this->promotionService = $promotionService;
    }
    
    public function updatedFromClassId()
    {
        $this->showCandidates = false;
        $this->candidates = [];
        $this->checkForDemotion();
        
        if ($this->fromClassId) {
            $this->loadCandidates();
        }
    }
    
    public function updatedToClassId()
    {
        $this->checkForDemotion();
    }
    
    private function checkForDemotion()
    {
        $this->demotionWarning = '';
        
        if ($this->fromClassId && $this->toClassId) {
            $fromClass = SchoolClass::find($this->fromClassId);
            $toClass = SchoolClass::find($this->toClassId);
            
            if ($fromClass && $toClass && $toClass->order < $fromClass->order) {
                $this->demotionWarning = "Warning: Moving students from {$fromClass->display_name} to {$toClass->display_name} is a demotion to a lower class.";
            }
        }
    }
    
    public function loadCandidates()
    {
        if (!$this->fromClassId) {
            return;
        }
        
        $this->candidates = $this->promotionService->getPromotionCandidates($this->fromClassId);
        $this->showCandidates = true;
    }
    
    public function confirmPromotion()
    {
        $this->validate([
            'fromClassId' => 'required|exists:school_classes,id',
            'toClassId' => 'required|exists:school_classes,id|different:fromClassId'
        ]);
        
        $fromClass = SchoolClass::find($this->fromClassId);
        $toClass = SchoolClass::find($this->toClassId);
        
        $studentsText = $this->onlyEligible ? 'eligible students' : 'all students';
        
        $this->confirmAction(
            'Confirm Promotion',
            "Are you sure you want to promote {$studentsText} from {$fromClass->display_name} to {$toClass->display_name}?",
            'Yes, Promote!',
            'Cancel'
        );
    }
    
    #[\Livewire\Attributes\On('action-confirmed')]
    public function promote()
    {
        
        try {
            $result = $this->promotionService->promoteStudentsByClass(
                $this->fromClassId,
                $this->toClassId,
                $this->onlyEligible
            );
            
            $message = "Promotion completed! {$result['promoted_count']} students promoted successfully.";
            
            if ($result['failed_count'] > 0) {
                $message .= " {$result['failed_count']} students failed to promote.";
            }
            
            if (!empty($result['warnings'])) {
                foreach ($result['warnings'] as $warning) {
                    $this->showToast('warning', $warning, 'Promotion Warning');
                }
            }
            
            $this->showToast('success', $message, 'Promotion Complete');
            
            $this->reset(['fromClassId', 'toClassId', 'onlyEligible', 'candidates', 'showCandidates']);
            
        } catch (\Exception $e) {
            $this->showToast('error', 'Error promoting students: ' . $e->getMessage(), 'Promotion Error');
        }
    }
    
    public function render()
    {
        $classes = SchoolClass::where('is_active', true)->orderBy('order')->get();
        
        return view('livewire.promotion-by-class', [
            'classes' => $classes
        ]);
    }
}