<?php

namespace App\Repositories;

use App\Models\Artist;
use App\Repositories\Interfaces\ArtistInterface;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ArtistRepository implements ArtistInterface
{
    public function list(Request $request)
    {
        $query = Artist::where('is_delete', 0);

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

        if ($request->filled('tag_id')) {
            $tagId = $request->tag_id;
            $query->whereRaw('FIND_IN_SET(?, tag_ids)', [$tagId]);
        }

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

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

    public function store(Request $request, $profile_pic = null, $tagIdsString = null)
    {
        $artist = new Artist();
        $artist->artist_name = $request->artist_name;
        $artist->tag_ids = $tagIdsString;
        $artist->profile_pic = $profile_pic;
        $artist->address = $request->address;
        $artist->description = $request->description;
        $artist->art_work = $request->art_work ?? 0;
        $artist->exhibitions = $request->exhibitions ?? 0;
        $artist->awards = $request->awards ?? 0;
        $artist->facebook = $request->facebook;
        $artist->instagram = $request->instagram;
        $artist->youtube = $request->youtube;
        $artist->twitter = $request->twitter;
        $artist->role = $request->role ?? 3; // default Both
        $artist->status = $request->status ?? 1;
        $artist->slug = Str::slug($request->artist_name);
        $artist->save();
        return $artist;
    }

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

        if (isset($data['tag_ids']) && is_array($data['tag_ids'])) {
            $data['tag_ids'] = implode(',', $data['tag_ids']);
        }

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

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

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

    public function getAllActive()
    {
        return Artist::where('is_delete', 0)->where('status', 1)->orderBy('artist_name')->get();
    }
}
