<?php

namespace App\Livewire\Training;

use App\Domain\Training\Models\TrainingSession;
use Illuminate\Support\Facades\DB;
use Livewire\Component;

class RescheduleSession extends Component
{
    public TrainingSession $session;
    public bool $showModal = false;
    public string $newDate = '';
    public string $newStartTime = '';
    public string $newEndTime = '';
    public string $reason = '';

    public function mount(TrainingSession $session): void
    {
        $this->session = $session;
        $this->newDate = $session->date;
        $this->newStartTime = $session->start_time;
        $this->newEndTime = $session->end_time;
    }

    public function open(): void
    {
        $this->showModal = true;
    }

    public function reschedule(): void
    {
        $this->validate([
            'newDate' => 'required|date|after_or_equal:today',
            'newStartTime' => 'required',
            'newEndTime' => 'required|after:newStartTime',
            'reason' => 'required|min:3',
        ], [
            'newDate.required' => __('التاريخ مطلوب'),
            'newDate.after_or_equal' => __('لا يمكن الجدولة في الماضي'),
            'newEndTime.after' => __('وقت الانتهاء يجب أن يكون بعد وقت البدء'),
            'reason.required' => __('السبب مطلوب'),
        ]);

        if (!in_array($this->session->status, ['scheduled'])) {
            session()->flash('error', __('لا يمكن إعادة جدولة هذه الحصة'));
            $this->showModal = false;
            return;
        }

        DB::transaction(function () {
            $this->session->update([
                'date' => $this->newDate,
                'start_time' => $this->newStartTime,
                'end_time' => $this->newEndTime,
                'status' => 'rescheduled',
                'notes' => ($this->session->notes ? $this->session->notes . "\n" : '')
                    . __('إعادة جدولة') . ": {$this->reason}",
            ]);

            // Create new session with the rescheduled details
            TrainingSession::create([
                'academy_id' => $this->session->academy_id,
                'training_group_id' => $this->session->training_group_id,
                'date' => $this->newDate,
                'start_time' => $this->newStartTime,
                'end_time' => $this->newEndTime,
                'status' => 'scheduled',
                'notes' => __('حصة معاد جدولتها من') . " {$this->session->date}",
            ]);
        });

        $this->showModal = false;
        session()->flash('success', __('تم إعادة الجدولة بنجاح'));
        $this->dispatch('session-rescheduled');
    }

    public function render()
    {
        return view('livewire.training.reschedule-session');
    }
}
