<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Service;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

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

        if ($request->filled('search')) {
            $query->where('title', 'like', '%' . $request->search . '%');
        }
        if ($request->filled('status')) {
            $query->where('is_active', $request->status === 'active');
        }

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

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

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

    public function store(Request $request)
    {
        $data = $this->validateData($request);
        $data['slug'] = Str::slug($data['title']);
        $data['features'] = $this->parseFeatures($request->features);

        if ($request->hasFile('icon_image')) {
            $data['icon_image'] = $request->file('icon_image')->store('services', 'public');
        }
        if ($request->hasFile('cover_image')) {
            $data['cover_image'] = $request->file('cover_image')->store('services', 'public');
        }

        Service::create($data);

        cache()->forget('nav.services');

        return redirect()->route('admin.services.index')
            ->with('success', 'Үйлчилгээ амжилттай нэмэгдлээ.');
    }

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

    public function update(Request $request, Service $service)
    {
        $data = $this->validateData($request, $service->id);
        $data['features'] = $this->parseFeatures($request->features);

        if ($request->hasFile('icon_image')) {
            if ($service->icon_image) Storage::disk('public')->delete($service->icon_image);
            $data['icon_image'] = $request->file('icon_image')->store('services', 'public');
        }
        if ($request->hasFile('cover_image')) {
            if ($service->cover_image) Storage::disk('public')->delete($service->cover_image);
            $data['cover_image'] = $request->file('cover_image')->store('services', 'public');
        }

        $service->update($data);
        cache()->forget('nav.services');

        return redirect()->route('admin.services.index')
            ->with('success', 'Үйлчилгээ амжилттай шинэчлэгдлээ.');
    }

    public function destroy(Service $service)
    {
        if ($service->icon_image) Storage::disk('public')->delete($service->icon_image);
        if ($service->cover_image) Storage::disk('public')->delete($service->cover_image);
        $service->delete();
        cache()->forget('nav.services');

        if (request()->wantsJson()) {
            return response()->json(['success' => true, 'message' => 'Устгагдлаа.']);
        }
        return back()->with('success', 'Үйлчилгээ устгагдлаа.');
    }

    /**
     * Идэвхтэй / идэвхгүй болгох (AJAX).
     */
    public function toggle(Service $service)
    {
        $service->update(['is_active' => ! $service->is_active]);
        cache()->forget('nav.services');

        return response()->json([
            'success'   => true,
            'is_active' => $service->is_active,
            'message'   => $service->is_active ? 'Идэвхжүүллээ.' : 'Идэвхгүй боллоо.',
        ]);
    }

    /**
     * Sort order шинэчлэх (drag-drop, AJAX).
     */
    public function reorder(Request $request)
    {
        $request->validate(['order' => 'required|array']);

        foreach ($request->order as $index => $id) {
            Service::where('id', $id)->update(['sort_order' => $index]);
        }
        cache()->forget('nav.services');

        return response()->json(['success' => true]);
    }

    private function validateData(Request $request, ?int $id = null): array
    {
        return $request->validate([
            'title'             => 'required|string|max:255',
            'icon'              => 'nullable|string|max:120',
            'short_description' => 'nullable|string|max:500',
            'description'       => 'nullable|string',
            'full_content'      => 'nullable|string',
            'icon_image'        => 'nullable|image|max:2048',
            'cover_image'       => 'nullable|image|max:4096',
            'sort_order'        => 'nullable|integer',
            'is_active'         => 'nullable|boolean',
            'show_on_home'      => 'nullable|boolean',
            'meta_title'        => 'nullable|string|max:255',
            'meta_description'  => 'nullable|string|max:500',
        ]);
    }

    private function parseFeatures($input): array
    {
        if (is_array($input)) return array_values(array_filter($input));
        if (is_string($input)) {
            return array_values(array_filter(array_map('trim', explode("\n", $input))));
        }
        return [];
    }
}
