<?php

namespace App\Http\Controllers;

use App\Models\Treatment;
use App\Models\Patient;
use App\Models\FormBuilder\FormSchema;
use App\Services\FormBuilder\CrudIndexService;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\Schema;

class TreatmentController extends Controller
{
    protected CrudIndexService $crudService;

    public function __construct(CrudIndexService $crudService)
    {
        $this->crudService = $crudService;
    }

    public function index()
    {
        // Load configuration dynamically from database
        $config = $this->crudService->getIndexConfig('treatments');

        // Build query with eager loading
        $query = Treatment::query();
        if (!empty($config['eagerLoadRelations'])) {
            $query->with($config['eagerLoadRelations']);
        }
        if (!empty($config['countRelations'])) {
            $query->withCount($config['countRelations']);
        }

        // Get create form with relationship options
        $createForm = null;
        if ($config['createFormId']) {
            $createForm = $this->crudService->getCreateForm($config['createFormId'], $config['relationshipOptions']);
        }

        return Inertia::render('Treatments/Index', [
            'indexData' => $query->get(),
            'columns' => $config['columns'],
            'createForm' => $createForm,
            'titles' => $config['titles'],
            'mainRoute' => $config['mainRoute'],
            'refreshPath' => $config['refreshPath'],
            'formID' => $config['formID'],
            'isFullWidth' => $config['isFullWidth'],
            'editMode' => $config['editMode'],
            'hasActions' => $config['hasActions'],
            'useDeleteButton' => $config['useDeleteButton'],
            'useEditButton' => $config['useEditButton'],
            'widgets' => $config['widgets'],
        ]);
    }

    public function create()
    {
        // Load options for relationship selects
        $relationshipOptions = [
            'patient_id' => Patient::all()->map(fn($item) => ['value' => $item->id, 'label' => $item->name]),
        ];

        $createForm = null;

        return Inertia::render('Treatments/Create', [
            'createForm' => $createForm,
        ]);
    }

    public function store(Request $request)
    {
        /* FORMBUILDER-START:validation */
        $validated = $request->validate([
            'patient_id' => 'required|integer|exists:patients,id',
            'performed_at' => 'required|date',
            'type' => 'nullable|string|max:255',
            'notes' => 'nullable|string',
            'cost' => 'nullable|numeric',
        ]);
        /* FORMBUILDER-END:validation */

        $treatment = Treatment::create($validated);

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

    public function show(Treatment $treatment)
    {
        return response()->json($treatment);
    }

    public function edit(Treatment $treatment)
    {
        // Load options for relationship selects
        $relationshipOptions = [
            'patient_id' => Patient::all()->map(fn($item) => ['value' => $item->id, 'label' => $item->name]),
        ];

        $editForm = null;

        return Inertia::render('Treatments/Edit', [
            'editForm' => $editForm,
            'treatment' => $treatment,
            'titles' => [
                'main' => 'Modificare Treatment',
                'submit' => 'Salvează',
            ],
            'backRoute' => '/treatments',
        ]);
    }

    public function editJson(Treatment $treatment)
    {
        // Load options for relationship selects
        $relationshipOptions = [
            'patient_id' => Patient::all()->map(fn($item) => ['value' => $item->id, 'label' => $item->name]),
        ];

        $editForm = null;

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

    public function update(Request $request, Treatment $treatment)
    {
        /* FORMBUILDER-START:validation */
        $validated = $request->validate([
            'patient_id' => 'required|integer|exists:patients,id',
            'performed_at' => 'required|date',
            'type' => 'nullable|string|max:255',
            'notes' => 'nullable|string',
            'cost' => 'nullable|numeric',
        ]);
        /* FORMBUILDER-END:validation */

        $treatment->update($validated);

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

    public function destroy(Treatment $treatment)
    {
        $treatment->delete();

        return response()->json(['message' => 'Treatment deleted successfully']);
    }

    public function getAll()
    {
        // Load configuration dynamically from database
        $config = $this->crudService->getIndexConfig('treatments');

        // Build query with eager loading
        $query = Treatment::query();
        if (!empty($config['eagerLoadRelations'])) {
            $query->with($config['eagerLoadRelations']);
        }
        if (!empty($config['countRelations'])) {
            $query->withCount($config['countRelations']);
        }

        return response()->json($query->get());
    }
}
