<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\ControlHistory;
use App\Models\History;
use App\Models\ControlSectionHistory;
use App\Models\ControlPhysicalExam;
use App\Models\Especiality;
use DateTime;
use Illuminate\Support\Facades\DB;
use Throwable;
use App\Exceptions\GlobalException;
use App\Models\SectionType;
use App\Helper\Helper;
use App\Models\HistoryConfiguration;
use App\PhysicalTest\PhysicalTest;


class ControlHistoryController extends Controller
{
    /**
     * 
     */
    public function create(Request $request){
        try {
         $data = $request->all();
         $model = new ControlHistory();
         if(!($request->method() === "POST")){
             $especialityId = $request->get('especiality_id');
             $configuration = null;

             // Obtener la configuración según la especialidad seleccionada
             if ($especialityId) {
                 $configuration = HistoryConfiguration::where('especiality_id', $especialityId)->first();
             } elseif (isset($data['especiality']) && $data['especiality'] !== 'SELECT') {
                 $configuration = HistoryConfiguration::where('especiality_id', $data['especiality'])->first();
             } elseif (isset($data['historyId'])) {
                 // Si no hay especialidad pero sí historyId, intentar obtener la especialidad de la historia
                 $history = History::find($data['historyId']);
                 if ($history && $history->especiality) {
                     $configuration = HistoryConfiguration::where('especiality_id', $history->especiality)->first();
                 }
             }

             return view("create-control-history",[
                 "model"=>$model,
                 "history"=>History::find($data["historyId"]),
                 "especialities" => Especiality::all(),
                 "sectionTypes" => SectionType::where("section_type_id", NULL)->get(),
                 "physicalTest" => new PhysicalTest(),
                 "configuration" => $configuration
             ]);
         }

        // Recopilar todos los campos que tengan el prefijo "cie-"
        $cieCodes = [];
        foreach ($data as $key => $value) {
            if (strpos($key, 'cie-') === 0) {
                $cieCodes[] = $value;
            }
        }
        // Almacenar los códigos en el campo cie_code, separados por coma
        $model->cie_code = implode(',', $cieCodes);

         //create control history
         $model->history_id     = $data["historyId"];
         $model->title          = $data["title"];
         $model->summary        = $data["summary"];
         $model->especiality    = $data["especiality"];
         $model->diagnosis     = $data["diagnosis"];

         DB::beginTransaction();
            $model->save();

            //create backgrounds
            if(isset($data["backgrounds"])){
                // Verificar si hay una configuración para esta especialidad
                $configuration = HistoryConfiguration::where('especiality_id', $model->especiality)->first();
                
                foreach($data["backgrounds"] as $key => $title){
                    // Si existe configuración, verificar que esta sección esté permitida
                    if ($configuration && !empty($configuration->section_types)) {
                        if (!in_array($key, $configuration->section_types)) {
                            continue; // Omitir esta sección si no está en la configuración
                        }
                    }
                    
                    if(isset($title["value"]) && (trim($title["value"])!== "")){
                        $id                    = new DateTime();
                        $id                    = md5($id->getTimestamp() . $title["value"] .$key); 
                        $controlSectionHistory = new ControlSectionHistory();
                        $controlSectionHistory->id = $id;
                        $controlSectionHistory->control_history_id = $model->id;
                        $controlSectionHistory->section_type_id = $key;
                        $sectionType = SectionType::where("id","=",$controlSectionHistory->section_type_id)->first();
                        $controlSectionHistory->title   =  __("backgrounds.". $sectionType->value);
                        $controlSectionHistory->summary = $title["value"];
                       $controlSectionHistory->save();
                    }
                }
            }
            //create exam physical
            if(isset($data["phisycalExams"])){
                // Verificar si hay una configuración para esta especialidad
                $configuration = HistoryConfiguration::where('especiality_id', $model->especiality)->first();
                
                // Si hay configuración, filtrar los exámenes permitidos
                if ($configuration && !empty($configuration->medical_exams)) {
                    $filteredExams = [];
                    foreach ($data["phisycalExams"] as $key => $value) {
                        if (in_array($key, $configuration->medical_exams)) {
                            $filteredExams[$key] = $value;
                        }
                    }
                    $examData = $filteredExams;
                } else {
                    $examData = $data["phisycalExams"];
                }
                
                // Solo guardar si hay exámenes después del filtrado
                if (!empty($examData)) {
                    $id = new DateTime();
                    $id = md5($id->getTimestamp()); 
                    $physicalExam = new ControlPhysicalExam();
                    $physicalExam->id = $id;
                    $physicalExam->control_history_id = $model->id;
                    $physicalExam->value = json_encode($examData);
                    $physicalExam->save();
                }
            }
            if ($request->has('fileuploads')) {
                $this->validate($request, [
                    'fileuploads' => 'required',
                    'fileuploads.*' => 'mimes:doc,docx,pdf,png,jpg,jpeg'
                ]);
                $files = $request->file('fileuploads');
                Helper::processFileUploadHistoryAndControl($files,'fileuploads',$model->history_id, $model->id);
            }
        DB::commit();
            return redirect()->route("/admin/detail-history",[
                "id"=>$model->history_id
            ]);
        } catch (Throwable $th) {
            DB::rollback();
            throw  new GlobalException($th->getMessage());
        }
     }


     
}
