<?php

namespace App\Http\Controllers\Warehouse;

use App\Http\Controllers\Controller;
use App\Models\Warehouse\ItemType;
use Illuminate\Http\Request;

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

    public function index(Request $request)
    {
        if ($request->expectsJson()) {
            return $this->getDataForTable($request);
        }

        $itemTypes = ItemType::latest()->paginate(10);
        return view('warehouse.item-types.index', compact('itemTypes'));
    }

    public function create()
    {
        return view('warehouse.item-types.create');
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'type_name' => 'required|string|max:255|unique:item_types,type_name',
            'description' => 'nullable|string|max:1000',
            'status' => 'required|in:active,inactive',
        ]);

        // Auto-generate type code from type name (first 3 letters + number for uniqueness)
        $baseCode = strtoupper(substr(preg_replace('/[^A-Za-z0-9]/', '', $validatedData['type_name']), 0, 3));
        $counter = 1;
        $typeCode = $baseCode;

        while (ItemType::where('type_code', $typeCode)->exists()) {
            $typeCode = $baseCode . $counter;
            $counter++;
        }

        $validatedData['type_code'] = $typeCode;

        try {
            $itemType = ItemType::create($validatedData);

            if ($request->expectsJson()) {
                return response()->json([
                    'success' => true,
                    'data' => $itemType,
                    'message' => 'Item type created successfully'
                ], 201);
            }

            return redirect()->route('warehouse.item-types.index')
                           ->with('success', 'Item type created successfully');

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

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

    public function show($id)
    {
        $itemType = ItemType::with(['items'])->findOrFail($id);

        if (request()->expectsJson()) {
            return response()->json($itemType);
        }

        return view('warehouse.item-types.show', compact('itemType'));
    }

    public function edit($id)
    {
        $itemType = ItemType::findOrFail($id);
        return view('warehouse.item-types.edit', compact('itemType'));
    }

    public function update(Request $request, $id)
    {
        $itemType = ItemType::findOrFail($id);

        $validatedData = $request->validate([
            'type_name' => 'required|string|max:255|unique:item_types,type_name,' . $id,
            'description' => 'nullable|string|max:1000',
            'status' => 'required|in:active,inactive',
        ]);

        // Keep existing type_code (don't regenerate on update)
        $validatedData['type_code'] = $itemType->type_code;

        try {
            $itemType->update($validatedData);

            if ($request->expectsJson()) {
                return response()->json([
                    'success' => true,
                    'data' => $itemType,
                    'message' => 'Item type updated successfully'
                ]);
            }

            return redirect()->route('warehouse.item-types.index')
                           ->with('success', 'Item type updated successfully');

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

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

    public function destroy($id)
    {
        $itemType = ItemType::findOrFail($id);

        try {
            // Check if there are items using this type
            if ($itemType->items()->count() > 0) {
                return response()->json([
                    'success' => false,
                    'message' => 'Cannot delete item type. It is being used by ' . $itemType->items()->count() . ' item(s).'
                ], 400);
            }

            $itemType->delete();

            return response()->json([
                'success' => true,
                'message' => 'Item type deleted successfully'
            ]);

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

    /**
     * Get data for DataTables.
     */
    protected function getDataForTable(Request $request)
    {
        try {
            $search = $request->input('search.value');

            $query = ItemType::withCount('items');

            if (!empty($search)) {
                $query->search($search);
            }

            $totalRecords = $query->count();

            // Apply ordering
            if ($request->has('order')) {
                $orderColumn = $request->input('columns.' . $request->input('order.0.column') . '.data');
                $orderDirection = $request->input('order.0.dir');

                if ($orderColumn === 'type_name') {
                    $query->orderBy('type_name', $orderDirection);
                } elseif ($orderColumn === 'type_code') {
                    $query->orderBy('type_code', $orderDirection);
                } elseif ($orderColumn === 'status') {
                    $query->orderBy('status', $orderDirection);
                } else {
                    $query->orderBy('created_at', $orderDirection);
                }
            } else {
                $query->orderBy('created_at', 'desc');
            }

            // Apply pagination
            $start = $request->input('start', 0);
            $length = $request->input('length', 10);

            if ($length != -1) {
                $query->skip($start)->take($length);
            }

            $itemTypes = $query->get();

            return response()->json([
                'draw' => $request->input('draw', 1),
                'recordsTotal' => $totalRecords,
                'recordsFiltered' => $totalRecords,
                'data' => $itemTypes->map(function ($itemType) {
                    return [
                        'id' => $itemType->id,
                        'type_name' => $itemType->type_name,
                        'type_code' => $itemType->type_code,
                        'description' => $itemType->description ?: '-',
                        'status' => $itemType->status,
                        'items_count' => $itemType->items_count,
                        'created_at' => $itemType->created_at->format('M d, Y'),
                        'actions' => $this->getActionButtons($itemType),
                    ];
                })->toArray()
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'error' => $e->getMessage(),
                'draw' => $request->input('draw', 1),
                'recordsTotal' => 0,
                'recordsFiltered' => 0,
                'data' => []
            ], 400);
        }
    }

    private function getActionButtons($itemType)
    {
        $buttons = [];

        $buttons[] = '<a href="' . route('warehouse.item-types.show', $itemType->id) . '" class="btn btn-sm btn-info" title="View"><i class="fa fa-eye"></i></a>';

        if (auth()->user()->can('warehouse.items.edit')) {
            $buttons[] = '<a href="' . route('warehouse.item-types.edit', $itemType->id) . '" class="btn btn-sm btn-primary" title="Edit"><i class="fa fa-edit"></i></a>';
        }

        if (auth()->user()->can('warehouse.items.delete')) {
            $buttons[] = '<button onclick="deleteItemType(' . $itemType->id . ')" class="btn btn-sm btn-danger" title="Delete"><i class="fa fa-trash"></i></button>';
        }

        return implode(' ', $buttons);
    }

    /**
     * Get item types for dropdown
     */
    public function dropdown(Request $request)
    {
        $itemTypes = ItemType::active()->orderBy('type_name')->get();

        return response()->json([
            'success' => true,
            'data' => $itemTypes
        ]);
    }
}