<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\CategoryServiceOverride;
use App\Models\Product;
use App\Models\ProductServiceLink;
use App\Models\Service;
use Illuminate\Http\Request;

class ServiceController extends Controller
{
    public function index()
    {
        $services = Service::orderBy('sort_order')->orderBy('name')->paginate(20);

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

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'slug' => 'required|string|max:255|unique:services,slug',
            'default_price' => 'required|numeric|min:0',
            'billing_type' => 'required|in:PER_ITEM,PER_ORDER',
            'is_active' => 'boolean',
            'sort_order' => 'integer|min:0',
        ]);

        $validated['is_active'] = $request->has('is_active');

        Service::create($validated);

        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)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'slug' => 'required|string|max:255|unique:services,slug,'.$service->id,
            'default_price' => 'required|numeric|min:0',
            'billing_type' => 'required|in:PER_ITEM,PER_ORDER',
            'is_active' => 'boolean',
            'sort_order' => 'integer|min:0',
        ]);

        $validated['is_active'] = $request->has('is_active');

        $service->update($validated);

        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.');
    }

    public function categoryOverrides(Service $service)
    {
        $overrides = CategoryServiceOverride::where('service_id', $service->id)
            ->with('category')
            ->paginate(20);

        $categories = Category::active()->orderBy('sort_order')->get();

        return view('admin.services.category-overrides', compact('service', 'overrides', 'categories'));
    }

    public function upsertCategoryOverride(Request $request, Service $service)
    {
        $validated = $request->validate([
            'category_id' => 'required|exists:categories,id',
            'override_price' => 'nullable|numeric|min:0',
        ]);

        CategoryServiceOverride::updateOrCreate(
            ['category_id' => $validated['category_id'], 'service_id' => $service->id],
            ['override_price' => $validated['override_price']]
        );

        return redirect()->route('admin.services.category-overrides', $service)
            ->with('success', 'Category override saved successfully.');
    }

    public function destroyCategoryOverride(Service $service, CategoryServiceOverride $categoryOverride)
    {
        $categoryOverride->delete();

        return redirect()->route('admin.services.category-overrides', $service)
            ->with('success', 'Category override removed successfully.');
    }

    public function productLinks(Service $service)
    {
        $links = ProductServiceLink::where('service_id', $service->id)
            ->with('product.category')
            ->paginate(20);

        $products = Product::active()->orderBy('name')->get();

        return view('admin.services.product-links', compact('service', 'links', 'products'));
    }

    public function upsertProductLink(Request $request, Service $service)
    {
        $validated = $request->validate([
            'product_id' => 'required|exists:products,id',
            'override_price' => 'nullable|numeric|min:0',
            'is_enabled' => 'boolean',
        ]);

        ProductServiceLink::updateOrCreate(
            ['product_id' => $validated['product_id'], 'service_id' => $service->id],
            [
                'override_price' => $validated['override_price'],
                'is_enabled' => $request->has('is_enabled'),
            ]
        );

        return redirect()->route('admin.services.product-links', $service)
            ->with('success', 'Product link saved successfully.');
    }

    public function toggleProductLink(Service $service, ProductServiceLink $productLink)
    {
        $productLink->update([
            'is_enabled' => ! $productLink->is_enabled,
        ]);

        return redirect()->route('admin.services.product-links', $service)
            ->with('success', 'Product link status updated successfully.');
    }

    public function destroyProductLink(Service $service, ProductServiceLink $productLink)
    {
        $productLink->delete();

        return redirect()->route('admin.services.product-links', $service)
            ->with('success', 'Product link removed successfully.');
    }
}
