<?php

namespace App\Livewire;

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

class PaymentRequestForm extends Component
{
    use HasNotifications;

    public $title = '';
    public $description = '';
    public $amount = '';
    public $currency = 'NGN';
    public $target_type = 'student';
    public $target_id = '';
    
    // Student selection
    public $student_search = '';
    public $selected_class_id = '';
    public $selected_batch_id = '';

    public $students = [];
    public $classes = [];
    public $batches = [];
    public $search_results = [];
    public $batch_students = [];
    public $show_search_results = false;

    protected $rules = [
        'title' => 'required|string|max:255',
        'description' => 'required|string',
        'amount' => 'required|numeric|min:0.01',
        'currency' => 'required|string|size:3',
        'target_type' => 'required|in:student,class,batch,all_students',
        'target_id' => 'nullable|integer|min:1',
    ];

    public function mount()
    {
        $this->loadData();
    }

    public function updatedTargetType()
    {
        $this->target_id = '';
        $this->student_search = '';
        $this->selected_class_id = '';
        $this->selected_batch_id = '';
        $this->search_results = [];
        $this->batch_students = [];
    }
    
    public function updatedStudentSearch()
    {
        if (strlen($this->student_search) >= 2) {
            $this->search_results = User::whereNull('deleted_at')
                ->whereDoesntHave('roles')
                ->where(function($query) {
                    $query->where('firstname', 'like', '%' . $this->student_search . '%')
                          ->orWhere('middlename', 'like', '%' . $this->student_search . '%')
                          ->orWhere('surname', 'like', '%' . $this->student_search . '%')
                          ->orWhere('student_id', 'like', '%' . $this->student_search . '%');
                })
                ->with('batch.schoolClass')
                ->orderBy('firstname')
                ->limit(20)
                ->get(['id', 'firstname', 'middlename', 'surname', 'student_id', 'batch_id']);
            $this->show_search_results = true;
        } else {
            $this->search_results = [];
            $this->show_search_results = false;
        }
    }
    
    public function selectStudentFromSearch($studentId)
    {
        $student = User::with('batch.schoolClass')->find($studentId);
        if ($student && $student->batch) {
            $this->student_search = $student->name;
            $this->show_search_results = false;
            
            // Set class and batch first
            $this->selected_class_id = $student->batch->school_class_id;
            // Load batches for the class
            $this->batches = Batch::where('school_class_id', $this->selected_class_id)
                ->orderBy('name')
                ->get(['id', 'name', 'school_class_id']);
            
            $this->selected_batch_id = $student->batch_id;
            $this->loadBatchStudents();
            
            // Use JavaScript to set the value after DOM update
            $this->js("setTimeout(() => { document.getElementById('target_id').value = '{$studentId}'; }, 100);");
            $this->target_id = $studentId;
        }
    }
    
    public function updatedSelectedClassId()
    {
        $this->selected_batch_id = '';
        $this->target_id = '';
        $this->batch_students = [];
        
        if ($this->selected_class_id) {
            // Load batches for the selected class
            $this->batches = Batch::where('school_class_id', $this->selected_class_id)
                ->orderBy('name')
                ->get(['id', 'name', 'school_class_id']);
        }
    }
    
    public function updatedSelectedBatchId()
    {
        $this->target_id = '';
        $this->loadBatchStudents();
    }
    
    public function updatedTargetId()
    {
        if ($this->target_id) {
            $student = User::find($this->target_id);
            if ($student) {
                $this->student_search = $student->name;
            }
        }
    }
    
    private function loadBatchStudents()
    {
        if ($this->selected_batch_id) {
            $this->batch_students = User::whereNull('deleted_at')
                ->whereDoesntHave('roles')
                ->where('batch_id', $this->selected_batch_id)
                ->orderBy('firstname')
                ->get(['id', 'firstname', 'middlename', 'surname', 'student_id']);
        }
    }

    public function loadData()
    {
        $this->classes = SchoolClass::orderBy('order')->get(['id', 'name', 'alias']);
        $this->batches = Batch::with('schoolClass')->orderBy('name')->get(['id', 'name', 'school_class_id']);
    }

    public function save()
    {
        // Custom validation for target_id based on target_type
        $rules = $this->rules;
        if ($this->target_type === 'all_students') {
            $rules['target_id'] = 'nullable';
        } else {
            $rules['target_id'] = 'required|integer|min:1';
        }
        
        $this->validate($rules);

        try {
            $paymentService = new PaymentService();
            $paymentService->createPaymentRequest([
                'title' => $this->title,
                'description' => $this->description,
                'amount' => $this->amount,
                'currency' => $this->currency,
                'target_type' => $this->target_type,
                'target_id' => $this->target_type === 'all_students' ? null : $this->target_id,
            ]);

            session()->flash('toast', [
                'type' => 'success',
                'message' => 'Payment request created successfully!'
            ]);

            return redirect()->route('payment-requests.index');
        } catch (\Exception $e) {
            $this->showToast('error', 'Error: ' . $e->getMessage(), 'Payment Request');
        }
    }

    public function render()
    {
        return view('livewire.payment-request-form');
    }
}
