<?php

namespace App\Livewire\Admin\Certificate;

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\Admin\Certificate;
use Livewire\Attributes\Validate;

class Create extends Component
{
    use WithFileUploads;

    #[Validate('required')]
    public $type;

    #[Validate('required')]
    public $file;

    public function save()
    {
        $this->validate();

        $certificate = new Certificate();

        $certificate->type = $this->type;

        if ($this->file) {
            $crtFileName = $this->file->getClientOriginalName();
            $crtFileNameWithoutExtension = pathinfo($crtFileName, PATHINFO_FILENAME);

            $certificate->title = $crtFileNameWithoutExtension;

            $this->file->storeAs('certificates', $crtFileName, 'upload');
            $certificate->file_path = 'upload/certificates/' . $crtFileName;
        }

        $certificate->save();

        activity()->performedOn($certificate)->causedBy(auth()->id())->log('Sertifika oluşturuldu');

        $this->dispatch('showAlert', [
            'title' => 'Başarılı!', 'text' => 'Sertifika oluşturuldu.', 'icon' => 'success'
        ]);

        $this->reset();
    }

    public function saveAndRedirect()
    {
        $this->save();
        return redirect()->route('admin.certificates.index');
    }

    public function render()
    {
        return view('livewire.admin.certificate.create');
    }
}
