<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\PrescriptionItemList;
use Illuminate\Http\Request;

class PrescriptionItemListController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $type = $request->get('type', 'quantity');
        $items = PrescriptionItemList::where('type', $type)
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get();
        
        return view('admin.prescription-items.index', compact('items', 'type'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(Request $request)
    {
        $type = $request->get('type', 'quantity');
        return view('admin.prescription-items.create', compact('type'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'type' => 'required|in:quantity,frequency,instruction,duration',
            'name' => 'required|string|max:255',
            'sort_order' => 'nullable|integer|min:0',
            'is_active' => 'boolean',
        ]);

        $validated['is_active'] = $request->has('is_active');
        $validated['sort_order'] = $validated['sort_order'] ?? 0;

        PrescriptionItemList::create($validated);

        return redirect()->route('admin.prescription-items.index', ['type' => $validated['type']])
            ->with('success', 'Item created successfully.');
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        $item = PrescriptionItemList::findOrFail($id);
        return view('admin.prescription-items.edit', compact('item'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        $item = PrescriptionItemList::findOrFail($id);

        $validated = $request->validate([
            'type' => 'required|in:quantity,frequency,instruction,duration',
            'name' => 'required|string|max:255',
            'sort_order' => 'nullable|integer|min:0',
            'is_active' => 'boolean',
        ]);

        $validated['is_active'] = $request->has('is_active');
        $validated['sort_order'] = $validated['sort_order'] ?? 0;

        $item->update($validated);

        return redirect()->route('admin.prescription-items.index', ['type' => $validated['type']])
            ->with('success', 'Item updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        $item = PrescriptionItemList::findOrFail($id);
        $type = $item->type;
        $item->delete();

        return redirect()->route('admin.prescription-items.index', ['type' => $type])
            ->with('success', 'Item deleted successfully.');
    }
}
