<?php

namespace App\Repositories\Admin;

use App\Models\Category;
use App\Models\Genre;
use App\Repositories\Interfaces\Admin\GenreInterface;
use Carbon\Carbon;
use App\Traits\ImageTrait;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Str;

class GenreRepository implements GenreInterface
{
    use ImageTrait;

    public function all()
    {
        return Genre::get();
    }

    public function store($request) {
        try {
            if (isset($request['icon']) && $request['icon'] instanceof UploadedFile) {
                $requestImage = $request['icon'];
                $response = $this->saveImage($requestImage, '_genre_');
                $request['icon'] = $response['images'];
            }
            $data = [
                'name' => $request['name'],
                'slug' => Str::slug($request['name']),
                'description' => $request['description'],
                'status' => $request['status'],
                'featured' => $request['featured'],
                'icon' => isset($request['icon']) ? json_encode($request['icon']) : '',
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ];
            return Genre::create($data);
        } catch (\Exception $e) {
            return false;
        }
    }

    public function update($request, $id) {
        try {
            $genre = Genre::where('id', $id)->first();
            if (isset($request['icon']) && $request['icon'] instanceof UploadedFile) {
                $requestImage = $request['icon'];
                $this->imageDelete($id, 'genre', 'icon');
                $response = $this->saveImage($requestImage, '_genre_');
                $request['icon'] = $response['images'];
            }
            $data = [
                'name' => $request['name'],
                'slug' => Str::slug($request['name']),
                'description' => $request['description'],
                'status' => $request['status'],
                'featured' => $request['featured'],
                'icon' => isset($request['icon']) ? json_encode($request['icon']) : $genre->icon,
                'updated_at' => Carbon::now(),
            ];
            return Genre::where('id', $id)->update($data);
        } catch (\Exception $e) {
            return false;
        }
    }
}