<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Service;
use App\Services\MediaUsageSyncService;
use Illuminate\Http\Request;

class ServiceController extends Controller
{
    public function index(Request $request)
    {
        $query = Service::query();

        $categories = Service::query()
            ->whereNotNull('category')
            ->distinct()
            ->pluck('category')
            ->filter()
            ->values();

        $tags = Service::query()
            ->whereNotNull('tags')
            ->get()
            ->pluck('tags')
            ->flatten()
            ->filter()
            ->unique()
            ->values();

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

        if ($request->filled('tag')) {
            $tag = $request->input('tag');
            $query->whereJsonContains('tags', $tag);
        }

        $services = $query->orderBy('sort_order')->orderBy('title')->paginate(15)->withQueryString();

        return view('admin.services.index', compact('services', 'categories', 'tags'));
    }

    public function create()
    {
        return view('admin.services.create');
    }

    public function store(Request $request, MediaUsageSyncService $mediaUsageSyncService)
    {
        $service = Service::create($this->validatedData($request, null));
        $mediaUsageSyncService->syncForService($service);

        return redirect()->route('admin.services.index')->with('success', 'Service created successfully.');
    }

    public function edit(Service $service)
    {
        return view('admin.services.edit', compact('service'));
    }

    public function update(Request $request, Service $service, MediaUsageSyncService $mediaUsageSyncService)
    {
        $service->update($this->validatedData($request, $service));
        $mediaUsageSyncService->syncForService($service);

        return redirect()->route('admin.services.index')->with('success', 'Service updated successfully.');
    }

    public function destroy(Service $service)
    {
        $service->delete();

        return redirect()->route('admin.services.index')->with('success', 'Service deleted successfully.');
    }

    protected function validatedData(Request $request, ?Service $service): array
    {
        $data = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'required|string|max:255|unique:services,slug,' . ($service?->id ?? 'NULL'),
            'category' => 'nullable|string|max:255',
            'tags' => 'nullable',
            'sort_order' => 'nullable|integer|min:0',
            'short_description' => 'nullable|string|max:255',
            'long_description' => 'nullable|string',
            'hero_title' => 'nullable|string|max:255',
            'benefits' => 'nullable',
            'image' => 'nullable|string|max:255',
            'image_media_id' => 'nullable|integer|exists:media,id',
            'icon' => 'nullable|string|max:255',
            'icon_media_id' => 'nullable|integer|exists:media,id',
            'seo_title' => 'nullable|string|max:255',
            'seo_description' => 'nullable|string',
        ]);

        if (is_string($data['tags'] ?? null) && filled($data['tags'])) {
            $data['tags'] = array_values(array_filter(array_map('trim', explode(',', $data['tags']))));
        } elseif (is_array($data['tags'] ?? null)) {
            $data['tags'] = array_values(array_filter(array_map('trim', $data['tags'])));
        }

        if (is_array($data['benefits'] ?? null)) {
            $data['benefits'] = implode("\n", array_values(array_filter(array_map('trim', $data['benefits']))));
        }

        return $data;
    }
}
