<?php

namespace App\Livewire\Results;

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\SchoolClass;
use App\Models\Batch;
use App\Models\SchoolSession;
use App\Services\OfflineResultService;
use App\Services\ResultService;
use App\Traits\HasNotifications;
use Illuminate\Support\Facades\Storage;

class OfflineUpload extends Component
{
    use WithFileUploads, HasNotifications;
    
    public $selectedClass = '';
    public $selectedBatch = '';
    public $selectedSession = '';
    public $uploadFile;
    public $uploadProgress = 0;
    public $isUploading = false;
    public $uploadResults = null;
    
    public $classes = [];
    public $batches = [];
    public $sessions = [];
    
    protected $rules = [
        'selectedClass' => 'required',
        'selectedBatch' => 'required', 
        'selectedSession' => 'required',
        'uploadFile' => 'required|file|mimes:xlsx,xls|max:10240'
    ];
    
    public function mount()
    {
        $resultService = new ResultService();
        $this->classes = $resultService->getClassesForUser(auth()->user());
        $this->sessions = SchoolSession::orderBy('created_at', 'desc')->get();
    }
    
    public function updatedSelectedClass()
    {
        $this->selectedBatch = '';
        $this->batches = [];
        
        if ($this->selectedClass) {
            $this->batches = Batch::where('school_class_id', $this->selectedClass)
                ->where('is_active', true)
                ->where('graduated', false)
                ->orderBy('name')
                ->get();
        }
    }
    
    public function downloadTemplate()
    {
        $this->validate([
            'selectedClass' => 'required',
            'selectedBatch' => 'required',
            'selectedSession' => 'required'
        ]);
        
        try {
            $service = new OfflineResultService();
            $template = $service->generateTemplate($this->selectedBatch, $this->selectedSession);
            
            return response()->download($template['filepath'], $template['filename'])->deleteFileAfterSend();
        } catch (\Exception $e) {
            $this->showToast('error', 'Error generating template: ' . $e->getMessage());
        }
    }
    
    public function processUpload()
    {

        $this->validate();
        
        $this->isUploading = true;
        $this->uploadProgress = 0;
        
        try {
            if (!$this->uploadFile) {
                throw new \Exception('No file selected');
            }
            
            $filePath = $this->uploadFile->store('temp');
            
            if (!Storage::exists($filePath)) {
                throw new \Exception('File upload failed');
            }
            
            $fullPath = Storage::path($filePath);
            
            $this->uploadProgress = 50;
            
            $service = new OfflineResultService();
            $this->uploadResults = $service->processUpload($fullPath, $this->selectedBatch, $this->selectedSession);
            
            $this->uploadProgress = 100;
            
            // Clean up
            Storage::delete($filePath);
            
            $this->showToast('success', 'Upload completed successfully!');
            
        } catch (\Exception $e) {
            $this->showToast('error', 'Error processing upload: ' . $e->getMessage());
            \Log::error('Upload error: ' . $e->getMessage());
        } finally {
            $this->isUploading = false;
            $this->uploadFile = null;
        }
    }
    
    public function resetUpload()
    {
        $this->uploadResults = null;
        $this->uploadFile = null;
        $this->uploadProgress = 0;
    }
    
    public function render()
    {
        return view('livewire.results.offline-upload');
    }
}