<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ProductColor;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class ProductColorController extends Controller
{
    public function index(Request $request)
    {
        $search = trim((string) $request->query('search'));
        $colors = ProductColor::query()
            ->when($search, function ($query) use ($search) {
                $query->where('name', 'like', "%{$search}%")
                    ->orWhere('code', 'like', "%{$search}%");
            })
            ->latest()
            ->paginate(config('default_pagination'))
            ->withQueryString();

        return view('admin-views.color.index', compact('colors'));
    }

    public function store(Request $request)
    {
        $data = $this->validatedData($request);
        ProductColor::create($data);

        Toastr::success(translate('messages.color_added_successfully'));

        return back();
    }

    public function edit(ProductColor $color)
    {
        return view('admin-views.color.edit', compact('color'));
    }

    public function update(Request $request, ProductColor $color)
    {
        $data = $this->validatedData($request, $color->id);
        $color->update($data);

        Toastr::success(translate('messages.color_updated_successfully'));

        return redirect()->route('admin.color.index');
    }

    public function status(ProductColor $color, int $status)
    {
        $color->update(['status' => (bool) $status]);

        Toastr::success(translate('messages.status_updated'));

        return back();
    }

    public function destroy(ProductColor $color)
    {
        $color->delete();

        Toastr::success(translate('messages.color_deleted_successfully'));

        return back();
    }

    private function validatedData(Request $request, ?int $ignoreId = null): array
    {
        $request->merge([
            'code' => '#'.ltrim(strtoupper((string) $request->input('code')), '#'),
        ]);

        $data = $request->validate([
            'name' => [
                'required',
                'string',
                'max:100',
                Rule::unique('product_colors', 'name')->ignore($ignoreId),
            ],
            'code' => [
                'required',
                'string',
                'max:20',
                'regex:/^#?[0-9A-Fa-f]{6}$/',
                Rule::unique('product_colors', 'code')->ignore($ignoreId),
            ],
        ]);

        return $data;
    }
}
