<?php

namespace App\Http\Controllers\Warehouse\FixedAssets;

use App\Http\Controllers\Controller;
use App\Models\Warehouse\FixedAssets\FixedAssetCategory;
use Illuminate\Http\Request;

class FixedAssetCategoryController extends Controller
{
    public function __construct()
    {
        $this->middleware('warehouse.access');
        $this->middleware('warehouse.permission:warehouse.fixed-assets.view')->only(['index']);
        $this->middleware('warehouse.permission:warehouse.fixed-assets.create')->only(['store']);
        $this->middleware('warehouse.permission:warehouse.fixed-assets.edit')->only(['update']);
        $this->middleware('warehouse.permission:warehouse.fixed-assets.delete')->only(['destroy']);
    }

    public function index(Request $request)
    {
        $categories = FixedAssetCategory::withCount('assets')->orderBy('category_name')->get();

        if ($request->expectsJson() || $request->ajax()) {
            return response()->json(['success' => true, 'data' => $categories]);
        }

        return view('warehouse.fixed-assets.categories.index', compact('categories'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'category_code' => 'required|string|max:10|unique:fixed_asset_categories,category_code',
            'category_name' => 'required|string|max:100',
            'status' => 'nullable|in:active,inactive',
            'description' => 'nullable|string|max:1000',
        ]);

        $validated['category_code'] = strtoupper($validated['category_code']);
        $validated['status'] = $validated['status'] ?? 'active';

        try {
            $category = FixedAssetCategory::create($validated);

            if ($request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'success' => true,
                    'data' => $category,
                    'message' => 'Asset category created successfully.'
                ], 201);
            }

            return redirect()->route('warehouse.fixed-assets.categories.index')
                ->with('success', 'Asset category created successfully.');
        } catch (\Exception $e) {
            \Log::error('FixedAssetCategoryController@store error: ' . $e->getMessage());

            if ($request->expectsJson() || $request->ajax()) {
                return response()->json(['success' => false, 'message' => $e->getMessage()], 400);
            }

            return back()->withErrors(['error' => $e->getMessage()])->withInput();
        }
    }

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

        $validated = $request->validate([
            'category_code' => 'required|string|max:10|unique:fixed_asset_categories,category_code,' . $id,
            'category_name' => 'required|string|max:100',
            'status' => 'required|in:active,inactive',
            'description' => 'nullable|string|max:1000',
        ]);

        $validated['category_code'] = strtoupper($validated['category_code']);

        try {
            $category->update($validated);

            if ($request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'success' => true,
                    'data' => $category->fresh(),
                    'message' => 'Asset category updated successfully.'
                ]);
            }

            return redirect()->route('warehouse.fixed-assets.categories.index')
                ->with('success', 'Asset category updated successfully.');
        } catch (\Exception $e) {
            \Log::error('FixedAssetCategoryController@update error: ' . $e->getMessage());

            if ($request->expectsJson() || $request->ajax()) {
                return response()->json(['success' => false, 'message' => $e->getMessage()], 400);
            }

            return back()->withErrors(['error' => $e->getMessage()])->withInput();
        }
    }

    public function destroy($id)
    {
        $category = FixedAssetCategory::findOrFail($id);

        $assetCount = $category->assets()->count();
        if ($assetCount > 0) {
            return response()->json([
                'success' => false,
                'message' => "Cannot delete this category because it has {$assetCount} asset(s) associated with it."
            ], 422);
        }

        try {
            $category->delete();

            return response()->json([
                'success' => true,
                'message' => 'Asset category deleted successfully.'
            ]);
        } catch (\Exception $e) {
            \Log::error('FixedAssetCategoryController@destroy error: ' . $e->getMessage());

            return response()->json(['success' => false, 'message' => $e->getMessage()], 400);
        }
    }
}
