<?php

namespace App\Http\Controllers\Admin\Shop;

use App\Http\Controllers\Controller;
use App\Models\PwShop;
use App\Services\ItemDataService;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\Validator;

class ShopController extends Controller
{
    protected ItemDataService $itemDataService;

    public function __construct(ItemDataService $itemDataService)
    {
        $this->itemDataService = $itemDataService;
    }

    /**
     * Display a listing of shop items
     */
    public function index()
    {
        $items = PwShop::orderBy('created_at', 'desc')->get();
        
        // Enrich items with data from RAE file
        $items = $items->map(function ($item) {
            $itemData = $this->itemDataService->getItemData($item->item_id);
            $item->item_name = $itemData['name'];
            $item->item_color = $itemData['color'];
            $item->description = $itemData['description'];
            return $item;
        });

        $masks = $this->getMasksForSelect();

        return Inertia::render('admin/Shop/index', [
            'items' => $items,
            'masks' => $masks,
        ]);
    }

    /**
     * Store a newly created shop item
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'item_id' => 'required|integer',
            'count' => 'required|integer|min:1',
            'octet' => 'nullable|string',
            'mask' => 'required|integer',
            'proctype' => 'required|integer',
            'price' => 'required|integer|min:0',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        PwShop::create([
            'item_id' => $request->item_id,
            'count' => $request->count,
            'octet' => $request->octet,
            'mask' => $request->mask,
            'proctype' => $request->proctype,
            'price' => $request->price,
            'is_active' => true,
        ]);

        return redirect()->route('admin.shop.index')
            ->with('success', 'Shop item created successfully!');
    }

    /**
     * Show the form for editing a shop item
     */
    public function edit($id)
    {
        $item = PwShop::findOrFail($id);
        
        // Enrich with RAE data
        $itemData = $this->itemDataService->getItemData($item->item_id);
        $item->item_name = $itemData['name'];
        $item->item_color = $itemData['color'];
        $item->description = $itemData['description'];
        
        $masks = $this->getMasksForSelect();

        return Inertia::render('admin/Shop/edit', [
            'item' => $item,
            'masks' => $masks,
        ]);
    }

    /**
     * Update the specified shop item
     */
    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'item_id' => 'required|integer',
            'count' => 'required|integer|min:1',
            'octet' => 'nullable|string',
            'mask' => 'required|integer',
            'proctype' => 'required|integer',
            'price' => 'required|integer|min:0',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $item = PwShop::findOrFail($id);

        $item->update([
            'item_id' => $request->item_id,
            'count' => $request->count,
            'octet' => $request->octet,
            'mask' => $request->mask,
            'proctype' => $request->proctype,
            'price' => $request->price,
        ]);

        return redirect()->route('admin.shop.index')
            ->with('success', 'Shop item updated successfully!');
    }

    /**
     * Remove the specified shop item
     */
    public function destroy($id)
    {
        $item = PwShop::findOrFail($id);
        $item->delete();

        return redirect()->route('admin.shop.index')
            ->with('success', 'Shop item deleted successfully!');
    }

    /**
     * Toggle the active status of a shop item
     */
    public function toggleStatus($id)
    {
        $item = PwShop::findOrFail($id);
        $item->is_active = !$item->is_active;
        $item->save();

        $status = $item->is_active ? 'activated' : 'deactivated';
        return redirect()->route('admin.shop.index')
            ->with('success', "Shop item {$status} successfully!");
    }

    /**
     * Get items from RAE_Exported_Table.tab for autocomplete
     */
    public function getItems(Request $request)
    {
        $itemId = $request->query('item_id');

        if ($itemId !== null) {
            $itemData = $this->itemDataService->getItemData($itemId);
            
            if ($itemData['name']) {
                return response()->json([
                    'id' => (int) $itemId,
                    'name' => $itemData['name'],
                    'color' => $itemData['color'],
                    'description' => $itemData['description'],
                ]);
            }
            
            return response()->json(['error' => 'Item not found'], 404);
        }

        return response()->json(['items' => []]);
    }

    /**
     * Get masks formatted for select dropdown
     */
    private function getMasksForSelect()
    {
        $masks = config('masks');
        $formatted = [];

        if (!$masks) {
            return $formatted;
        }

        foreach ($masks as $key => $value) {
            if (is_array($value)) {
                // Group
                $formatted[] = [
                    'label' => $key,
                    'options' => array_map(function ($k, $v) {
                        return ['value' => $k, 'label' => $v];
                    }, array_keys($value), $value)
                ];
            } else {
                // Single option
                $formatted[] = [
                    'value' => $key,
                    'label' => $value
                ];
            }
        }

        return $formatted;
    }
}
