<?php

namespace App\Http\Controllers;

use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class CategoryController extends Controller
{
    /**
     * Display a listing of all categories.
     */
    public function index(Request $request)
    {
        try {
            $perPage = $request->get('per_page', 15);
            $categories = Category::with('products')->paginate($perPage);

            // Add image URLs to each category
            $categoriesWithLinks = $categories->getCollection()->map(function ($category) {
                return [
                    'id' => $category->id,
                    'name' => $category->name,
                    'slug' => $category->slug,
                    'description' => $category->description,
                    'image' => $category->image ? str_replace('\\', '/', $category->image) : null,
                    'status' => $category->status,
                    'created_at' => $category->created_at,
                    'updated_at' => $category->updated_at,
                    'products' => $category->products->map(function ($product) {
                        $productArray = $product->toArray();
                        $productArray['image'] = $product->image ? str_replace('\\', '/', $product->image) : null;
                        return $productArray;
                    })->all(),
                    'links' => [
                        'show' => url('/api/categories/' . $category->id),
                        'update' => url('/api/categories/' . $category->id),
                        'delete' => url('/api/categories/' . $category->id),
                    ]
                ];
            });

            return response()->json([
                'success' => true,
                'data' => $categoriesWithLinks,
                'pagination' => [
                    'total' => $categories->total(),
                    'per_page' => $categories->perPage(),
                    'current_page' => $categories->currentPage(),
                    'last_page' => $categories->lastPage(),
                    'from' => $categories->firstItem(),
                    'to' => $categories->lastItem(),
                    'has_more' => $categories->hasMorePages(),
                ],
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch categories',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Store a newly created category (Admin only).
     */
    public function store(Request $request)
    {
        // Check if user is admin
        $user = Auth::guard('api')->user();
        if (!$user || !$user->isAdmin()) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized - Admin access required',
            ], 403);
        }

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255|unique:categories',
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:2048',
            'status' => 'nullable|boolean',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors(),
            ], 422);
        }

        try {
            $imagePath = null;

            // Handle image upload
            if ($request->hasFile('image')) {
                $file = $request->file('image');
                $filename = Str::random(10) . '_' . time() . '.' . $file->getClientOriginalExtension();
                $imagePath = $file->storeAs('categories', $filename, 'public');
            }

            $category = Category::create([
                'name' => $request->name,
                'slug' => Str::slug($request->name),
                'description' => $request->description,
                'image' => $imagePath,
                'status' => $request->status ?? true,
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Category created successfully',
                'data' => $category,
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create category',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Display the specified category.
     */
    public function show(Category $category)
    {
        try {
            $category->load('products');

            // Transform category and product images to URLs
            $categoryData = [
                'id' => $category->id,
                'name' => $category->name,
                'slug' => $category->slug,
                'description' => $category->description,
                'image' => $category->image ? str_replace('\\', '/', $category->image) : null,
                'status' => $category->status,
                'created_at' => $category->created_at,
                'updated_at' => $category->updated_at,
                'products' => $category->products->map(function ($product) {
                    $productArray = $product->toArray();
                    $productArray['image'] = $product->image ? str_replace('\\', '/', $product->image) : null;
                    return $productArray;
                })->all(),
            ];

            return response()->json([
                'success' => true,
                'data' => $categoryData,
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch category',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Update the specified category (Admin only).
     */
    public function update(Request $request, Category $category)
    {
        // Check if user is admin
        $user = Auth::guard('api')->user();
        if (!$user || !$user->isAdmin()) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized - Admin access required',
            ], 403);
        }

        $validator = Validator::make($request->all(), [
            'name' => 'nullable|string|max:255|unique:categories,name,' . $category->id,
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:2048',
            'status' => 'nullable|boolean',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors(),
            ], 422);
        }

        try {
            if ($request->has('name')) {
                $category->name = $request->name;
                $category->slug = Str::slug($request->name);
            }

            if ($request->has('description')) {
                $category->description = $request->description;
            }

            if ($request->hasFile('image')) {
                // Delete old image if exists
                if ($category->image && Storage::disk('public')->exists($category->image)) {
                    Storage::disk('public')->delete($category->image);
                }
                // Upload new image
                $file = $request->file('image');
                $filename = Str::random(10) . '_' . time() . '.' . $file->getClientOriginalExtension();
                $imagePath = $file->storeAs('categories', $filename, 'public');
                $category->image = $imagePath;
            }

            if ($request->has('status')) {
                $category->status = $request->status;
            }

            $category->save();

            return response()->json([
                'success' => true,
                'message' => 'Category updated successfully',
                'data' => $category,
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update category',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Remove the specified category (Admin only).
     */
    public function destroy(Category $category)
    {
        // Check if user is admin
        $user = Auth::guard('api')->user();
        if (!$user || !$user->isAdmin()) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized - Admin access required',
            ], 403);
        }

        try {
            $category->delete();

            return response()->json([
                'success' => true,
                'message' => 'Category deleted successfully',
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete category',
                'error' => $e->getMessage(),
            ], 500);
        }
    }
}
