<?php

namespace App\Http\Controllers\Admin\Master;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Master\BarbershopRequest;
use App\Models\Barbershop;
use App\Traits\UploadAttachment;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class BarbershopController extends Controller
{
    use UploadAttachment;

    public function index(): View
    {
        return view('pages.admin.master.barbershop.index', [
            'pageTitle' => 'Barbershop',
            'barbershop' => Barbershop::latest()->get(),
        ]);
    }

    public function create(): View
    {
        return view('pages.admin.master.barbershop.create', [
            'pageTitle' => 'Tambah Barbershop',
        ]);
    }

    public function store(BarbershopRequest $request): RedirectResponse
    {
        $validatedData = $request->validated();

        DB::transaction(function () use ($validatedData) {
            $newBarbershop = Barbershop::create($validatedData);
            $this->uploadAttachment($validatedData['image'], 'barbershop', Barbershop::class, $newBarbershop->id, 'barbeshop');
        });

        notify()->success('Data berhasil ditambahkan', 'Berhasil');

        return redirect('dashboard/master/barbershop');
    }

    public function edit(Barbershop $barbershop): View
    {
        return view('pages.admin.master.barbershop.edit', [
            'pageTitle' => 'Edit Barbershop',
            'barbershop' => $barbershop,
        ]);
    }

    public function update(Barbershop $barbershop, BarbershopRequest $request): RedirectResponse
    {
        $validatedData = $request->validated();

        DB::transaction(function () use ($barbershop, $validatedData) {
            $barbershop->update($validatedData);
            if (isset($validatedData['image'])) {
                $this->uploadAttachment($validatedData['image'], 'barbershop', Barbershop::class, $barbershop->id, 'barbershop');
            }
        });

        notify()->success('Data berhasil diubah', 'Berhasil');

        return redirect('dashboard/master/barbershop');
    }

    public function delete(Barbershop $barbershop): RedirectResponse
    {
        if (Auth::user()->barbershop_id === $barbershop->id) {
            notify()->info('Anda sedang berada di barbershop ini, silakan pilih barbershop lain lalu Anda dapat menghapusnya', 'Informasi');

            return back();
        }
        $barbershop->delete();

        notify()->success('Data berhasil dihapus', 'Berhasil');

        return back();
    }
}
