<?php

namespace App\Livewire;

use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\Attributes\On;
use Livewire\Attributes\Validate;
use App\Models\FotoKegiatan as PM;
use Illuminate\Support\Facades\DB;

class FotoKegiatan extends Component
{
    use WithFileUploads;
    public $id, $iter = 0;
    #[Validate(['file.*' => 'required|image|mimes:png,jpg,jpeg|max:12288'])]
    public $file = [];
    protected $messages = [
        'file.*.required' => 'Tidak Boleh Kosong',
        'file.*.image' => 'Harus Gambar',
        'file.*.max' => 'Maksimal :max kb',
        'file.*.mimes' => 'Harus Berformat :values'
    ];

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

    public function store()
    {
        $this->validate();
        try {
            DB::beginTransaction();
            foreach($this->file as $file){
                PM::create(['album_id' => $this->id, 'file' => $file->store('album_kegiatan', 'public')]);
            }
            DB::commit();
            $this->reset_fields();
            $this->success();
        } catch (\Throwable $th) {
            DB::rollBack();
            $this->error();
        }
    }

    #[On('destroy')]
    public function destroy($id)
    {
        try {
            $data = PM::find($id);
            hapus_file($data->file);
            $data->delete();
            $this->resetValidation();
            $this->success();
        } catch (\Throwable $th) {
            $this->error();
        }
    }

    public function reset_fields()
    {
        $this->reset('file');
        $this->resetValidation();
        $this->iter++;
    }

    public function success()
    {
        $this->dispatch('swal:modal', [
            'type' => 'success',
            'message' => 'Berhasil Simpan Data!',
            'toast' => 'true',
            'position' => 'top-end'
        ]);
    }

    public function error($msg = null)
    {
        $this->dispatch('swal:modal', [
            'type' => 'error',
            'message' => 'Operasi Gagal! ' . $msg,
            'toast' => 'true',
            'position' => 'top-end'
        ]);
    }

    public function confirm($id)
    {
        $this->dispatch('swal:confirm', [
            'type' => 'warning',
            'message' => 'Hapus Data?',
            'text' => 'Data Tidak Dapat Dikembalikan!',
            'id' => $id
        ]);
    }

    public function remove()
    {
        $this->dispatch('swal:modal', [
            'type' => 'success',
            'message' => 'Data Berhasil Dihapus!',
            'toast' => 'true',
            'position' => 'top-end'
        ]);
    }

    public function render()
    {
        $data = PM::where('album_id', $this->id)->get();
        return view('livewire.foto-kegiatan', compact('data'));
    }
}
