<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PatientCustomField;
use App\Models\PatientCustomFieldValue;
use App\Exceptions\GlobalException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class PatientCustomFieldController extends Controller
{
    /**
     * Display the custom fields configuration page
     *
     * @return \Illuminate\View\View
     */
    public function index()
    {
        try {
            $fields = PatientCustomField::orderBy('order', 'asc')->get();
            $fieldTypes = PatientCustomField::getAvailableTypes();
            
            return view('patient-custom-fields.index', [
                'fields' => $fields,
                'fieldTypes' => $fieldTypes
            ]);
        } catch (\Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }
    
    /**
     * Store a new custom field
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:255',
                'type' => 'required|string|in:' . implode(',', array_keys(PatientCustomField::getAvailableTypes())),
                'placeholder' => 'nullable|string|max:255',
                'required' => 'boolean',
                'options' => 'nullable|string',
            ]);
            
            if ($validator->fails()) {
                return redirect()->back()
                    ->withErrors($validator)
                    ->withInput();
            }
            
            // Convert options string to array for select/radio/checkbox types
            $options = null;
            if (in_array($request->type, ['select', 'radio', 'checkbox']) && !empty($request->options)) {
                $optionsArray = array_map('trim', explode(',', $request->options));
                $options = array_filter($optionsArray, function($value) {
                    return !empty($value);
                });
            }
            
            // Get the highest order to place new field at the end
            $maxOrder = PatientCustomField::max('order') ?? 0;
            
            PatientCustomField::create([
                'name' => $request->name,
                'type' => $request->type,
                'placeholder' => $request->placeholder,
                'required' => $request->has('required'),
                'options' => $options,
                'order' => $maxOrder + 1,
                'active' => true,
                'created_by' => Auth::id()
            ]);
            
            return redirect()->route('patient-custom-fields.index')
                ->with('success', __('patient-custom-fields.field_created'));
        } catch (\Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }
    
    /**
     * Update a custom field
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, $id)
    {
        try {
            $field = PatientCustomField::findOrFail($id);
            
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:255',
                'type' => 'required|string|in:' . implode(',', array_keys(PatientCustomField::getAvailableTypes())),
                'placeholder' => 'nullable|string|max:255',
                'required' => 'boolean',
                'options' => 'nullable|string',
                'active' => 'boolean',
            ]);
            
            if ($validator->fails()) {
                return redirect()->back()
                    ->withErrors($validator)
                    ->withInput();
            }
            
            // Convert options string to array for select/radio/checkbox types
            $options = null;
            if (in_array($request->type, ['select', 'radio', 'checkbox']) && !empty($request->options)) {
                $optionsArray = array_map('trim', explode(',', $request->options));
                $options = array_filter($optionsArray, function($value) {
                    return !empty($value);
                });
            }
            
            $field->update([
                'name' => $request->name,
                'type' => $request->type,
                'placeholder' => $request->placeholder,
                'required' => $request->has('required'),
                'options' => $options,
                'active' => $request->has('active'),
            ]);
            
            return redirect()->route('patient-custom-fields.index')
                ->with('success', __('patient-custom-fields.field_updated'));
        } catch (\Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }
    
    /**
     * Delete a custom field
     *
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy($id)
    {
        try {
            $field = PatientCustomField::findOrFail($id);
            
            // Delete all associated values
            PatientCustomFieldValue::where('field_id', $id)->delete();
            
            // Delete the field
            $field->delete();
            
            return redirect()->route('patient-custom-fields.index')
                ->with('success', __('patient-custom-fields.field_deleted'));
        } catch (\Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }
    
    /**
     * Update field order
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateOrder(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'fields' => 'required|array',
                'fields.*' => 'required|integer|exists:patient_custom_fields,id',
            ]);
            
            if ($validator->fails()) {
                return response()->json(['error' => $validator->errors()->first()], 400);
            }
            
            $fields = $request->fields;
            
            foreach ($fields as $order => $fieldId) {
                PatientCustomField::where('id', $fieldId)->update(['order' => $order + 1]);
            }
            
            return response()->json(['success' => true]);
        } catch (\Throwable $th) {
            return response()->json(['error' => $th->getMessage()], 500);
        }
    }
}
