<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\VipCategory;

class VipCategoryController extends Controller
{
    public function index()
    {
        $categories = VipCategory::withCount('products')->latest()->get();
        return view('admin.vip_categories.index', compact('categories'));
    }

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:20|unique:vip_categories,name',
            'display_name' => 'required|string|max:100',
            'description' => 'nullable|string',
            'icon' => 'required|string|in:star,crown',
        ]);

        VipCategory::create($validated);

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

    public function edit($id)
    {
        $category = VipCategory::findOrFail($id);
        return view('admin.vip_categories.form', compact('category'));
    }

    public function update(Request $request, $id)
    {
        $category = VipCategory::findOrFail($id);

        $validated = $request->validate([
            'name' => 'required|string|max:20|unique:vip_categories,name,'.$id,
            'display_name' => 'required|string|max:100',
            'description' => 'nullable|string',
            'is_active' => 'sometimes|boolean',
            'icon' => 'required|string|in:star,crown',
        ]);

        $category->update($validated);

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

    public function destroy($id)
    {
        $category = VipCategory::findOrFail($id);
        
        if ($category->products()->exists()) {
            return redirect()->back()
                ->with('error', 'Cannot delete category with associated products!');
        }

        $category->delete();

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

    public function toggleStatus($id)
    {
        $category = VipCategory::findOrFail($id);
        $category->update(['is_active' => !$category->is_active]);

        return response()->json([
            'success' => true,
            'new_status' => $category->is_active,
            'message' => 'Status updated successfully'
        ]);
    }
}