<?php

namespace App\Http\Controllers\Admin;

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

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $categories = Category::withCount('products')->orderBy('sort_order')->paginate(15);
        return view('admin.categories.index', compact('categories'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $services = Service::orderBy('sort_order')->orderBy('name')->get();
        return view('admin.categories.create', compact('services'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'sort_order' => 'integer|min:0',
            'show_on_menu' => 'sometimes|boolean',
            'featured' => 'sometimes|boolean',
            'seo_title' => 'nullable|string|max:255',
            'seo_description' => 'nullable|string',
            'seo_keywords' => 'nullable|string|max:255',
            'services' => 'nullable|array',
            'services.*' => 'exists:services,id',
            'service_override_price' => 'nullable|array',
            'service_override_price.*' => 'nullable|numeric|min:0',
        ]);

        $data = $request->only(['name', 'description', 'sort_order', 'seo_title', 'seo_description', 'seo_keywords', 'show_on_menu', 'featured']);
        $data['slug'] = Str::slug($request->name);
        $data['is_active'] = $request->boolean('is_active', true);

        // Handle image upload
        if ($request->hasFile('image')) {
            try {
                $data['image'] = StorageService::upload($request->file('image'), 'categories');
            } catch (\Exception $e) {
                return redirect()->back()
                    ->with('error', 'Image upload failed: ' . $e->getMessage())
                    ->withInput();
            }
        }

        Category::create($data);

        $category = Category::where('slug', $data['slug'])->first();
        $this->syncCategoryServices($category, $request->input('services', []), $request);

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

    /**
     * Display the specified resource.
     */
    public function show(Category $category)
    {
        $category->load('products');
        return view('admin.categories.show', compact('category'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Category $category)
    {
        $services = Service::orderBy('sort_order')->orderBy('name')->get();
        $selectedServices = $category->services()->get()->keyBy('id');
        return view('admin.categories.edit', compact('category', 'services', 'selectedServices'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Category $category)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'sort_order' => 'integer|min:0',
            'show_on_menu' => 'sometimes|boolean',
            'featured' => 'sometimes|boolean',
            'seo_title' => 'nullable|string|max:255',
            'seo_description' => 'nullable|string',
            'seo_keywords' => 'nullable|string|max:255',
            'services' => 'nullable|array',
            'services.*' => 'exists:services,id',
            'service_override_price' => 'nullable|array',
            'service_override_price.*' => 'nullable|numeric|min:0',
        ]);

        $data = $request->only(['name', 'description', 'sort_order', 'seo_title', 'seo_description', 'seo_keywords', 'show_on_menu', 'featured']);
        $data['slug'] = Str::slug($request->name);
        $data['is_active'] = $request->boolean('is_active', true);

        // Handle image upload
        if ($request->hasFile('image')) {
            // Delete old image
            if ($category->image) {
                StorageService::delete($category->image);
            }
            try {
                $data['image'] = StorageService::upload($request->file('image'), 'categories');
            } catch (\Exception $e) {
                return redirect()->back()
                    ->with('error', 'Image upload failed: ' . $e->getMessage())
                    ->withInput();
            }
        }

        $category->update($data);

        $this->syncCategoryServices($category, $request->input('services', []), $request);

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

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Category $category)
    {
        // Check if category has products
        if ($category->products()->count() > 0) {
            return redirect()->route('admin.categories.index')
                            ->with('error', 'Cannot delete category with products.');
        }

        // Delete image
        if ($category->image) {
            StorageService::delete($category->image);
        }

        $category->delete();

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

    /**
     * Toggle the active status of the category.
     */
    public function toggleStatus(Category $category)
    {
        $category->update(['is_active' => !$category->is_active]);

        $status = $category->is_active ? 'activated' : 'deactivated';
        
        return redirect()->back()
                        ->with('success', "Category {$status} successfully.");
    }

    /**
     * Sync services for a category.
     */
    private function syncCategoryServices(Category $category, array $serviceIds, Request $request = null)
    {
        $syncData = [];
        foreach ($serviceIds as $serviceId) {
            $overridePrice = $request ? $request->input("service_override_price.{$serviceId}") : null;
            $syncData[$serviceId] = [
                'override_price' => $overridePrice !== null && $overridePrice !== '' ? $overridePrice : null,
            ];
        }
        $category->services()->sync($syncData);
    }
}
