<?php

namespace App\Http\Controllers\Admin\ItemTemplate;

use App\Http\Controllers\Controller;
use App\Models\ItemTemplate;
use Illuminate\Http\Request;
use Inertia\Inertia;

class ItemTemplateController extends Controller
{
    /**
     * Display item templates management page
     */
    public function index(Request $request)
    {
        $perPage = $request->input('per_page', 10);
        
        $templates = ItemTemplate::orderBy('created_at', 'desc')
            ->paginate($perPage);

        $masks = $this->getMasksForSelect();

        return Inertia::render('admin/manage/item-templates/index', [
            'templates' => $templates,
            'masks' => $masks,
        ]);
    }

    /**
     * Store a new item template
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'item_id' => 'required|integer|min:1',
            'item_name' => 'nullable|string|max:255',
            'count' => 'required|integer|min:1',
            'proctype' => 'nullable|integer',
            'octet' => 'nullable|string',
            'mask' => 'nullable|integer',
            'protect_type' => 'nullable|integer',
            'is_active' => 'boolean',
        ]);

        // Auto-fetch item name if not provided
        if (empty($validated['item_name'])) {
            $validated['item_name'] = $this->getItemNameById($validated['item_id']);
        }

        $validated['is_active'] = $request->boolean('is_active', true);

        ItemTemplate::create($validated);

        return back()->with('success', 'Item template created successfully.');
    }

    /**
     * Update an item template
     */
    public function update(Request $request, int $id)
    {
        $template = ItemTemplate::findOrFail($id);

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'item_id' => 'required|integer|min:1',
            'item_name' => 'nullable|string|max:255',
            'count' => 'required|integer|min:1',
            'proctype' => 'nullable|integer',
            'octet' => 'nullable|string',
            'mask' => 'nullable|integer',
            'protect_type' => 'nullable|integer',
            'is_active' => 'boolean',
        ]);

        // Auto-fetch item name if not provided
        if (empty($validated['item_name'])) {
            $validated['item_name'] = $this->getItemNameById($validated['item_id']);
        }

        $validated['is_active'] = $request->boolean('is_active', true);

        $template->update($validated);

        return back()->with('success', 'Item template updated successfully.');
    }

    /**
     * Delete an item template
     */
    public function destroy(int $id)
    {
        $template = ItemTemplate::findOrFail($id);
        $template->delete();

        return back()->with('success', 'Item template deleted successfully.');
    }

    /**
     * Toggle item template active status
     */
    public function toggleStatus(int $id)
    {
        $template = ItemTemplate::findOrFail($id);
        $template->is_active = !$template->is_active;
        $template->save();

        return back()->with('success', 'Item template status updated.');
    }

    /**
     * Get all active templates for dropdown
     */
    public function getAll()
    {
        $templates = ItemTemplate::active()
            ->orderBy('name')
            ->get(['id', 'name', 'item_id', 'item_name', 'count', 'proctype', 'octet', 'mask', 'protect_type']);

        return response()->json($templates);
    }

    /**
     * Get item by ID
     */
    public function getItem(Request $request)
    {
        $itemId = $request->query('item_id');
        
        if ($itemId === null) {
            return response()->json(['error' => 'Item ID required'], 400);
        }

        $itemName = $this->getItemNameById($itemId);
        
        if ($itemName) {
            return response()->json([
                'id' => (int)$itemId,
                'name' => $itemName,
            ]);
        }

        return response()->json(['error' => 'Item not found'], 404);
    }

    /**
     * Get item name by ID from RAE_Exported_Table.tab
     */
    private function getItemNameById($itemId)
    {
        $filePath = public_path('img/RAE_Exported_Table.tab');
        
        if (!file_exists($filePath)) {
            return null;
        }

        $file = fopen($filePath, 'r');
        
        while (($line = fgets($file)) !== false) {
            $parts = explode("\t", trim($line));
            
            if (count($parts) >= 3) {
                $id = trim($parts[0]);
                $name = trim($parts[2]);
                
                if ($id == $itemId && !empty($name)) {
                    fclose($file);
                    return $name;
                }
            }
        }
        
        fclose($file);
        return null;
    }

    /**
     * Get masks formatted for select dropdown
     */
    private function getMasksForSelect()
    {
        $masks = config('masks');
        $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;
    }
}
