<?php

namespace App\Livewire;

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

class PromotionByBatch extends Component
{
    use HasNotifications;
    
    public $batchId = '';
    public $toClassId = '';
    public $toBatchId = '';
    public $createNewBatch = true;
    public $onlyEligible = false;
    public $selectedBatch = null;
    public $batchSearch = '';
    public $availableBatches = [];
    public $eligibleCount = 0;
    public $demotionWarning = '';
    
    protected $promotionService;
    
    public function boot(PromotionService $promotionService)
    {
        $this->promotionService = $promotionService;
    }
    
    public function updatedBatchId()
    {
        if ($this->batchId) {
            $this->selectedBatch = Batch::with('schoolClass', 'students')->find($this->batchId);
            $this->calculateEligibleCount();
        } else {
            $this->selectedBatch = null;
            $this->eligibleCount = 0;
        }
    }
    
    public function updatedOnlyEligible()
    {
        $this->calculateEligibleCount();
    }
    
    private function calculateEligibleCount()
    {
        if ($this->selectedBatch && $this->onlyEligible) {
            $students = $this->selectedBatch->students;
            $eligible = $this->promotionService->filterEligibleStudents($students);
            $this->eligibleCount = $eligible->count();
        } else {
            $this->eligibleCount = 0;
        }
    }
    
    public function updatedToClassId()
    {
        $this->loadAvailableBatches();
        $this->toBatchId = '';
        $this->checkForDemotion();
    }
    
    public function updatedCreateNewBatch()
    {
        if ($this->createNewBatch) {
            $this->toBatchId = '';
        }
    }
    
    public function selectBatch($batchId)
    {
        $this->batchId = $batchId;
        $this->selectedBatch = Batch::with('schoolClass', 'students')->find($batchId);
        $this->batchSearch = '';
        $this->calculateEligibleCount();
        $this->checkForDemotion();
    }
    
    private function checkForDemotion()
    {
        $this->demotionWarning = '';
        
        if ($this->selectedBatch && $this->toClassId) {
            $fromClass = $this->selectedBatch->schoolClass;
            $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.";
            }
        }
    }
    
    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 = [
            'batchId' => 'required|exists:batches,id',
            'toClassId' => 'required|exists:school_classes,id'
        ];
        
        if (!$this->createNewBatch) {
            $rules['toBatchId'] = 'required|exists:batches,id';
        }
        
        $this->validate($rules);
        
        $batch = Batch::with('schoolClass')->find($this->batchId);
        $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 batch '{$batch->name}' to {$toClass->display_name}?",
            'Yes, Promote!',
            'Cancel'
        );
    }
    
    #[\Livewire\Attributes\On('action-confirmed')]
    public function promote()
    {
        try {
            $result = $this->promotionService->promoteStudentsByBatch(
                $this->batchId,
                $this->toClassId,
                $this->onlyEligible,
                $this->createNewBatch ? null : $this->toBatchId
            );
            
            $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(['batchId', 'toClassId', 'toBatchId', 'onlyEligible', 'selectedBatch', 'batchSearch']);
            $this->createNewBatch = true;
            $this->availableBatches = [];
            
        } catch (\Exception $e) {
            $this->showToast('error', 'Error promoting students: ' . $e->getMessage(), 'Promotion Error');
        }
    }
    
    public function render()
    {
        // Search results for clickable list
        $searchResults = collect();
        if ($this->batchSearch) {
            $searchResults = Batch::with('schoolClass')
                ->where('is_active', true)
                ->where('graduated', false)
                ->where('name', 'like', '%' . $this->batchSearch . '%')
                ->orderBy('name')
                ->limit(20)
                ->get();
        }
        
        // All batches for dropdown
        $allBatches = Batch::with('schoolClass')
            ->where('is_active', true)
            ->where('graduated', false)
            ->orderBy('name')
            ->get();
            
        $classes = SchoolClass::where('is_active', true)->orderBy('order')->get();
        
        return view('livewire.promotion-by-batch', [
            'searchResults' => $searchResults,
            'batches' => $allBatches,
            'classes' => $classes
        ]);
    }
}