<?php

    namespace App\Livewire\Departments;

    use App\Http\Controllers\DepartmentsController;
    use App\Models\MailAccount;
    use Illuminate\Support\Facades\Auth;
    use Illuminate\Support\{Str,Carbon};
    use Livewire\Attributes\Rule;
    use Livewire\Component;
    use Filament\Notifications\Notification;

    class Create extends Component
    {
        public $isModal = false;

        #[Rule('required', message: "Please enter a name for the department.")]
        public $department_name;
        public $slug = '';

        public $department_description;

        #[Rule('required|email', message: "Please enter a valid email address for this department.")]
        public $department_email;

        public $allows_high_priority;
        public $cc_enabled = '1';
        public $is_public;
        public $is_disabled;
        public $mail_account_id;

        public function save()
        {
            $this->validate();
            if ($this->slug == '') {
                $this->slug = Str::of($this->department_name)->slug('-');
            }
            $this->slug = Str::of($this->slug)->slug('-');
            
            $create_department = DepartmentsController::store([
                'department_name' => $this->department_name,
                'department_description' => $this->department_description,
                'slug' => str_replace(' ', '-', $this->slug),
                'department_email' => $this->department_email,
                'allows_high_priority' => $this->allows_high_priority,
                'cc_enabled' => $this->cc_enabled,
                'is_public' => $this->is_public,
                'is_disabled' => $this->is_disabled,
                'mail_account_id' => $this->mail_account_id ?: null,
            ]);
            if ($create_department) {

                Notification::make()
                    ->title('Created successfully')
                    ->success()
                    ->body('The department has been created.')
                    ->color('success') 
                    ->send();

                $this->redirect('/departments');
            } else {
                return view('livewire.departments.create');
            }
        }
        public function render()
        {
            $mailAccounts = MailAccount::active()->orderBy('is_default', 'desc')->orderBy('name')->get();
            return view('livewire.departments.create', [
                'mailAccounts' => $mailAccounts,
            ]);
        }
    }
