<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Repositories\Interfaces\ArtistInterface;
use App\Repositories\Interfaces\ArtTagInterface;
use App\Traits\FileUploadTrait;
use Illuminate\Http\Request;

class ArtistController extends Controller
{
    use FileUploadTrait;

    protected $artistRepo;
    protected $tagRepo;
    private $profileCategoryId = 3; // Must exist in file_categories with prefix ART_

    public function __construct(ArtistInterface $artistRepo, ArtTagInterface $tagRepo)
    {
        $this->artistRepo = $artistRepo;
        $this->tagRepo = $tagRepo;
    }

    public function index(Request $request)
    {
        $artists = $this->artistRepo->list($request);
        $allTags = $this->tagRepo->getAllActive();
        $baseImgPath = $this->getBasePath();
        return view('Admin.Artist.list', compact('artists', 'allTags', 'baseImgPath'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'artist_name' => 'required|string|max:255',
            'address'     => 'nullable|string|max:255',
            'profile_pic' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'description' => 'nullable|string',
            'art_work'    => 'nullable|integer',
            'exhibitions' => 'nullable|integer',
            'awards'      => 'nullable|integer',
            'facebook'    => 'nullable|url',
            'instagram'   => 'nullable|url',
            'youtube'     => 'nullable|url',
            'twitter'     => 'nullable|url',
            'status'      => 'nullable|in:0,1'
        ]);

        // Process tags: prevent duplicates
        $tagNames = $request->tag_names ?? [];
        $tagIds = [];
        foreach ($tagNames as $name) {
            $name = trim($name);
            if (is_numeric($name)) {
                $tagIds[] = (int)$name;
            } else {
                // Check if tag already exists (case-insensitive)
                $existingTag = $this->tagRepo->findByName($name);
                if ($existingTag) {
                    $tagIds[] = $existingTag->id;
                } else {
                    $newTag = $this->tagRepo->store(['name_en' => $name, 'status' => 1]);
                    $tagIds[] = $newTag->id;
                }
            }
        }
        $tagIdsString = implode(',', $tagIds);

        // Upload profile picture
        $profilePic = null;
        if ($request->hasFile('profile_pic')) {
            $profilePic = $this->uploadFile($this->profileCategoryId, $request->file('profile_pic'));
        }

        $artist = $this->artistRepo->store($request, $profilePic, $tagIdsString);
        return response()->json(['success' => true, 'artist' => $artist]);
    }

    public function edit($id)
    {
        $artist = $this->artistRepo->find($id);
        if (!$artist) {
            return response()->json(['success' => false, 'message' => 'Artist not found'], 404);
        }
        $artist->tag_ids_array = $artist->tag_ids ? explode(',', $artist->tag_ids) : [];
        $artist->profile_pic_url = $artist->profile_pic ? $this->getBasePath() . $artist->profile_pic : null;
        return response()->json(['success' => true, 'artist' => $artist]);
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'artist_name' => 'required|string|max:255',
            'address'     => 'nullable|string|max:255',
            'profile_pic' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'description' => 'nullable|string',
            'art_work'    => 'nullable|integer',
            'exhibitions' => 'nullable|integer',
            'awards'      => 'nullable|integer',
            'facebook'    => 'nullable|url',
            'instagram'   => 'nullable|url',
            'youtube'     => 'nullable|url',
            'twitter'     => 'nullable|url',
            'status'      => 'nullable|in:0,1'
        ]);

        // Same tag processing as store
        $tagNames = $request->tag_names ?? [];
        $tagIds = [];
        foreach ($tagNames as $name) {
            $name = trim($name);
            if (is_numeric($name)) {
                $tagIds[] = (int)$name;
            } else {
                $existingTag = $this->tagRepo->findByName($name);
                if ($existingTag) {
                    $tagIds[] = $existingTag->id;
                } else {
                    $newTag = $this->tagRepo->store(['name_en' => $name, 'status' => 1]);
                    $tagIds[] = $newTag->id;
                }
            }
        }
        $tagIdsString = implode(',', $tagIds);

        $data = $request->except('profile_pic', '_token', '_method', 'tag_names');
        $data['tag_ids'] = $tagIdsString;

        if ($request->hasFile('profile_pic')) {
            $data['profile_pic'] = $this->uploadFile($this->profileCategoryId, $request->file('profile_pic'));
        }

        $artist = $this->artistRepo->update($id, $data);
        return response()->json(['success' => true, 'artist' => $artist]);
    }

    public function destroy($id)
    {
        $result = $this->artistRepo->delete($id);
        if ($result) {
            return response()->json(['success' => true]);
        }
        return response()->json(['success' => false, 'message' => 'Artist not found'], 404);
    }

    public function createTag(Request $request)
    {
        $request->validate(['name' => 'required|string|max:255']);
        // Prevent duplicate tag creation from this endpoint too
        $existing = $this->tagRepo->findByName($request->name);
        if ($existing) {
            return response()->json(['id' => $existing->id, 'text' => $existing->name_en]);
        }
        $tag = $this->tagRepo->store(['name_en' => $request->name, 'status' => 1]);
        return response()->json(['id' => $tag->id, 'text' => $tag->name_en]);
    }
}
