<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\MedicalService;
use App\Models\Currencies;
use Illuminate\Http\Request;

class MedicalServiceController extends Controller
{
    public function index()
    {
        $services = MedicalService::with('currency')->get();
        return view('view-medical-services', compact('services'));
    }

    public function create()
    {
        $currencies = Currencies::all();
        return view('create-medical-services', compact('currencies'));
    }

    public function store(Request $request)
    {

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'cost' => 'required|numeric|min:0',
            'currency_id' => 'required|exists:currencies,id',
            'is_active' => 'boolean'
        ]);
        
        $id = md5(uniqid(rand(), true));

        $validated['id'] = $id;

        MedicalService::create($validated);

        return redirect()->route('/admin/view-medical-services')
            ->with('success', 'Servicio médico creado exitosamente');
    }

    public function edit(MedicalService $medicalService)
    {
        $currencies = Currencies::all();
        return view('edit-medical-services', compact('medicalService', 'currencies'));
    }

    public function update(Request $request, MedicalService $medicalService)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'cost' => 'required|numeric|min:0',
            'currency_id' => 'required|exists:currencies,id',
            'is_active' => 'boolean'
        ]);

        $medicalService->update($validated);

        return redirect()->route('/admin/view-medical-services')
            ->with('success', 'Servicio médico actualizado exitosamente');
    }

    public function destroy(Request $request)
    {
        $medicalService = MedicalService::findOrFail($request->id);
        $medicalService->delete();
        return redirect()->route('/admin/view-medical-services')
            ->with('success', 'Servicio médico eliminado exitosamente');
    }
} 