<?php

namespace App\Livewire\Results;

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

class MasterList extends Component
{
    use HasNotifications;

    public $sessionId = '';
    public $classId = '';
    public $batchId = '';
    public $sessions = [];
    public $classes = [];
    public $batches = [];
    public $masterListData = null;

    protected $masterListService;

    public function boot(MasterListService $masterListService)
    {
        $this->masterListService = $masterListService;
    }

    public function mount()
    {
        $this->sessions = $this->masterListService->getActiveSessions();
        $this->classes = $this->masterListService->getClassesForUser(auth()->user());
    }

    public $loading = false;

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

    public function updatedClassId()
    {
        $this->batchId = '';
        $this->batches = [];
        $this->masterListData = null;
        
        if ($this->classId) {
            $this->loadBatches();
        }
    }
    
    public function loadBatches()
    {
        $this->batches = \App\Models\Batch::where('school_class_id', $this->classId)
            ->where('is_active', true)
            ->orderBy('name')
            ->get();
    }
    
    public function updatedBatchId()
    {
        $this->masterListData = null;
    }

    public function getPrintUrl()
    {
        if (!$this->masterListData) {
            return null;
        }
        
        return route('results.print-master-list', [
            'session' => $this->sessionId,
            'class' => $this->classId,
            'batch' => $this->batchId ?: 'all'
        ]);
    }

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

        $this->loading = true;
        
        try {
            $this->masterListData = $this->masterListService->getMasterListData($this->sessionId, $this->classId, $this->batchId ?: null);
            
            if (!$this->masterListData) {
                $this->showError('Invalid session or class selected.');
                $this->masterListData = null;
            }
        } catch (\Exception $e) {
            $this->showError('Error loading master list data.');
            $this->masterListData = null;
        } finally {
            $this->loading = false;
        }
    }

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