<?php

namespace App\Http\Controllers;

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

class PatientCustomFieldValueController extends Controller
{
    /**
     * Store or update custom field values for a patient
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $patientId
     * @return \Illuminate\Http\RedirectResponse
     */
    public function storeValues(Request $request, $patientId)
    {
        try {
            $patient = Patients::findOrFail($patientId);
            $fields = PatientCustomField::where('active', true)->orderBy('order')->get();
            
            // Validate all required fields are present
            $requiredFields = $fields->where('required', true)->pluck('id');
            $requiredValidation = [];
            
            foreach ($requiredFields as $fieldId) {
                $requiredValidation["field_{$fieldId}"] = 'required';
            }
            
            $request->validate($requiredValidation);
            
            // Save each field value
            foreach ($fields as $field) {
                $inputName = "field_{$field->id}";
                $value = $request->input($inputName);
                
                // If the value is empty and field is not required, skip it
                if (empty($value) && !$field->required) {
                    continue;
                }
                
                // Format value based on field type
                switch ($field->type) {
                    case 'checkbox':
                        $value = $request->has($inputName) ? '1' : '0';
                        break;
                    case 'date':
                        if (!empty($value)) {
                            $value = date('Y-m-d', strtotime($value));
                        }
                        break;
                }
                
                // Find existing value or create new one
                $fieldValue = PatientCustomFieldValue::firstOrNew([
                    'patient_id' => $patientId,
                    'field_id' => $field->id
                ]);
                
                $fieldValue->value = $value;
                $fieldValue->updated_by = Auth::id();
                $fieldValue->save();
            }
            
            return redirect()->back()->with('success', __('patient-custom-fields.values_saved'));
        } catch (\Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }
    
    /**
     * Delete a specific custom field value
     *
     * @param  int  $patientId
     * @param  int  $fieldId
     * @return \Illuminate\Http\RedirectResponse
     */
    public function deleteValue($patientId, $fieldId)
    {
        try {
            $value = PatientCustomFieldValue::where([
                'patient_id' => $patientId,
                'field_id' => $fieldId
            ])->first();
            
            if ($value) {
                $value->delete();
            }
            
            return redirect()->back()->with('success', __('patient-custom-fields.value_deleted'));
        } catch (\Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }
}
