<?php

namespace App\Repositories;

use App\Models\Illustration;
use App\Repositories\Interfaces\IllustrationInterface;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class IllustrationRepository implements IllustrationInterface
{
    public function list(Request $request)
    {
        $query = Illustration::where('is_delete', 0)
            ->with(['category', 'artist']);

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where('name_en', 'like', "%{$search}%");
        }

        if ($request->filled('artist_id')) {
            $query->where('artist_id', $request->artist_id);
        }

        if ($request->filled('illustration_category_id')) {
            $query->where('illustration_category_id', $request->illustration_category_id);
        }

        return $query->orderBy('id', 'desc')->paginate(10);
    }

    public function find($id)
    {
        return Illustration::where('is_delete', 0)->with('images')->find($id);
    }

    public function store(Request $request)
    {
        $illustration = new Illustration();
        $illustration->name_en = $request->name_en;
        $illustration->description = $request->description;
        $illustration->illustration_category_id = $request->illustration_category_id;
        $illustration->artist_id = $request->artist_id;
        $illustration->status = $request->status ?? 1;
        $illustration->slug = Str::slug($request->name_en);
        $illustration->save();
        return $illustration;
    }

    public function update($id, array $data)
    {
        $illustration = $this->find($id);
        if (!$illustration) return null;

        if (isset($data['name_en'])) {
            $data['slug'] = Str::slug($data['name_en']);
        }

        $illustration->update($data);
        return $illustration;
    }

    public function delete($id)
    {
        $illustration = $this->find($id);
        if (!$illustration) return null;
        $illustration->update(['is_delete' => 1]);
        return $illustration;
    }
}
