@extends('layouts.yellow')
@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12 p-3">
            <div class="card">
                <div class="card-header">
                    <h2>{{ __('view-users.updateDoctor') }}</h2>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-12">
        @if ($errors->any())
            <div class="alert alert-danger">
                <ul class="mb-0">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
                </ul>
            </div>
            @endif
        </div>
        <div class="col-12">
        <div class="container">
  <!-- Estilos integrados -->
  <style>
    :root {
      --primary-blue: #2A4E6D;
      --secondary-blue: #4A90E2;
      --light-bg: #F0F7FF;
      --accent-orange: #FF6B35;
    }
    /* Estilo general del formulario */
    .form-container {
      background: #ffffff;
      border-radius: 12px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
      padding: 1.5rem;
      margin-bottom: 2rem;
    }
    /* Inputs, selects, textarea */
    .form-control {
      border: 2px solid #e0e7f1 !important;
      border-radius: 8px !important;
      padding: 0.75rem 1rem !important;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }
    .form-control:focus {
      border-color: var(--secondary-blue) !important;
      box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.1) !important;
    }
    /* Grupo de radios */
    .radio-group {
      display: flex;
      gap: 1.5rem;
      align-items: center;
    }
    .radio-group label {
      position: relative;
      padding-left: 28px;
      cursor: pointer;
    }
    .radio-group input[type="radio"] {
      position: absolute;
      opacity: 0;
      width: 0;
      height: 0;
    }
    .radio-group input[type="radio"] + span {
      position: absolute;
      left: 0;
      top: 1px;
      width: 20px;
      height: 20px;
      border: 2px solid var(--primary-blue);
      border-radius: 50%;
    }
    .radio-group input[type="radio"]:checked + span {
      border-color: var(--secondary-blue);
    }
    .radio-group input[type="radio"]:checked + span:after {
      content: '';
      position: absolute;
      width: 12px;
      height: 12px;
      background: var(--secondary-blue);
      border-radius: 50%;
      top: 2px;
      left: 2px;
    }
    /* Fondo para columnas */
    .col-background {
      background: var(--light-bg) !important;
      border-radius: 8px;
      display: flex;
      align-items: center;
      padding: 1rem !important;
    }
    /* Botón de envío */
    .btn-success {
      background: linear-gradient(135deg, var(--secondary-blue), var(--primary-blue));
      border: none;
      padding: 1rem 2.5rem;
      border-radius: 8px;
      font-weight: 600;
      transition: all 0.3s ease;
      color: #fff;
    }
    .btn-success:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(42, 78, 109, 0.3);
    }
    /* Responsive */
    @media (max-width: 768px) {
      .col-background {
        margin-bottom: 1rem;
      }
      .radio-group {
        flex-direction: column;
        align-items: flex-start;
      }
      .form-control {
        padding: 0.6rem 0.8rem !important;
      }
      .btn-success {
        width: 100%;
        padding: 1rem;
      }
    }
    /* Estilos para los tags de especialidades */
    .tag-span {
      background-color: var(--primary-blue);
      color: white;
      padding: 6px 12px;
      border-radius: 20px;
      font-size: 0.85rem;
      display: inline-flex;
      align-items: center;
    }
    .tag-span .remove-tag {
      margin-left: 8px;
      cursor: pointer;
      font-weight: bold;
      color: #ffdddd;
    }
    .tag-span .remove-tag:hover {
      color: #ffffff;
    }
  </style>

  <!-- Inicio del Formulario basado en updateDoctor -->
  <form name="UpdateDoctor" id="UpdateDoctor" class="form-container" action="{{ URL::route('/admin/update-doctor') }}" method="POST">
    @csrf
    <input type="hidden" name="id" value={{$userProfile->id}}>
    <!-- Datos Generales: Género -->
    <div class="container-fluid mb-3">
      <div class="row align-items-center">
        <div class="col-12 col-lg-10 col-md-10">
          <div class="mb-2">
            <b><label for="gender">{{ __("com-form-identity.gender") }}</label></b>
          </div>
          <div class="radio-group">
            @if(isset($userProfile->gender))
              @php $gender = strtoupper($userProfile->gender); @endphp
              <label>
                <input type="radio" name="gender" value="F" {{ $gender === 'F' ? 'checked' : '' }}>
                <span></span>{{ __("common.genderFemale") }}
              </label>
              <label>
                <input type="radio" name="gender" value="M" {{ $gender === 'M' ? 'checked' : '' }}>
                <span></span>{{ __("common.genderMale") }}
              </label>
              <label>
                <input type="radio" name="gender" value="O" {{ $gender !== 'F' && $gender !== 'M' ? 'checked' : '' }}>
                <span></span>{{ __("common.genderOther") }}
              </label>
            @else
              <label>
                <input type="radio" name="gender" value="F">
                <span></span>{{ __("common.genderFemale") }}
              </label>
              <label>
                <input type="radio" name="gender" value="M">
                <span></span>{{ __("common.genderMale") }}
              </label>
              <label>
                <input type="radio" name="gender" value="O">
                <span></span>{{ __("common.genderOther") }}
              </label>
            @endif
          </div>
        </div>
      </div>
    </div>
    
    <!-- Campos de Identidad -->
    <div class="container-fluid mb-3">
      <!-- Nombre -->
      <div class="row p-2">
        <div class="col-12 col-lg-4 col-md-4 col-background">
          <b><label for="firstname">{{ __("com-form-identity.firstname") }}</label></b>
        </div>
        <div class="col-12 col-lg-8 col-md-8">
          <input placeholder="{{ __('com-form-identity.firstname') }}" id="firstname" name="firstname" value="{{ $userProfile->firstname }}" type="text" class="form-control">
        </div>
      </div>
      <!-- Apellido -->
      <div class="row p-2">
        <div class="col-12 col-lg-4 col-md-4 col-background">
          <b><label for="lastname">{{ __("com-form-identity.lastname") }}</label></b>
        </div>
        <div class="col-12 col-lg-8 col-md-8">
          <input placeholder="{{ __('com-form-identity.lastname') }}" id="lastname" name="lastname" value="{{ $userProfile->lastname }}" type="text" class="form-control">
        </div>
      </div>
          <!-- Email -->
      <div class="row p-2">
        <div class="col-12 col-lg-4 col-md-4 col-background">
          <b><label for="email">{{ __("com-form-identity.email") }}</label></b>
        </div>
        <div class="col-12 col-lg-8 col-md-8">
          <input placeholder="{{ __('com-form-identity.email') }}" id="email" name="email" value="{{ $userProfile->email }}" type="text" class="form-control">
        </div>
      </div>
      <!-- Especialidades -->
      <div class="row p-2">
        <div class="col-12 col-lg-4 col-md-4 col-background">
          <b><label for="especiality" class="form-label">{{ __("com-form-appointment.especiality") }}</label></b>
        </div>
        <div class="col-12 col-lg-8 col-md-8">
          <!-- Campo oculto para almacenar las especialidades seleccionadas -->
          <input type="hidden" name="especialities_selected" id="especialities_selected" 
       value="{{ old('especialities_selected', isset($userProfile->especialities) ? implode(',', $userProfile->especialities->pluck('id')->toArray()) : '') }}">

          <!-- Contenedor visual de tags -->
          <div class="form-group mb-2">
            <div id="especialityTags" class="mb-2 d-flex flex-wrap gap-2"></div>
          </div>
          <!-- Select para agregar especialidades -->
          <div class="form-group">
            <select id="especialitySelect" name="especialitySelect" class="form-control">
              <option value="">{{ __('com-form-appointment.selectValue') }}</option>
              @foreach($especialities as $key => $option)
                <option value="{{ $key }}">{{ $option }}</option>
              @endforeach
            </select>
          </div>
        </div>
      </div>
      <!-- Fecha de Nacimiento -->
      <div class="row p-2">
        <div class="col-12 col-lg-4 col-md-4 col-background">
          <b><label for="birthday">{{ __("com-form-identity.birthday") }}</label></b>
        </div>
        <div class="col-12 col-lg-8 col-md-8">
          <input placeholder="{{ __('com-form-identity.birthday') }}" id="birthday" name="birthday" value="{{ $userProfile->birthday }}" type="text" class="form-control">
        </div>
      </div>
      <!-- Edad (calculada) -->
      <div class="row p-2">
        <div class="col-12 col-lg-4 col-md-4 col-background">
          <b><label for="age">{{ __("com-form-identity.age") }}</label></b>
        </div>
        <div class="col-12 col-lg-8 col-md-8">
          <input placeholder="{{ __('com-form-identity.age') }}" id="age" name="age" value="{{ $userProfile->age }}" type="text" class="form-control" readonly>
        </div>
      </div>
      <!-- Teléfono -->
      <div class="row p-2">
        <div class="col-12 col-lg-4 col-md-4 col-background">
          <b><label for="phone">{{ __("com-form-identity.phone") }}</label></b>
        </div>
        <div class="col-12 col-lg-8 col-md-8">
          <input placeholder="{{ __('com-form-identity.phone') }}" id="phone" name="phone" value="{{ $userProfile->phone }}" type="text" class="form-control">
        </div>
      </div>
      <!-- Dirección -->
      <div class="row p-2">
        <div class="col-12 col-lg-4 col-md-4 col-background">
          <b><label for="address">{{ __("com-form-identity.address") }}</label></b>
        </div>
        <div class="col-12 col-lg-8 col-md-8">
          <textarea placeholder="{{ __('com-form-identity.address') }}" id="address" name="address" class="form-control">{{ $userProfile->address }}</textarea>
        </div>
      </div>
    </div>
    
    <!-- Botón de Envío -->
    <div class="container-fluid p-3">
      <div class="row">
        <div class="col-12 text-center">
          <button type="submit" class="btn btn-success">
            {{ __('com-form-user.btnSubmitUpdate') }}
          </button>
        </div>
      </div>
    </div>
  </form>


</div>

        </div>
    </div>

      <!-- Scripts para funcionalidades -->
  <script>
    // Función para formatear la fecha de cumpleaños y calcular la edad
    function buildRulesBirthday() {
      // Se asume que se ha cargado la librería jQuery y su plugin mask
      $('[name="birthday"]').mask('00/00/0000');

      const validateFormatAge = (date) => {
        const regex = /^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[0-2])\/\d{4}$/;
        return regex.test(date);
      };

      const calcuteAge = (date) => {
        const partsOfDate = date.split("/");
        const day = parseInt(partsOfDate[0], 10);
        const month = parseInt(partsOfDate[1], 10) - 1; // Meses 0-11 en JS
        const year = parseInt(partsOfDate[2], 10);
        const birthday = new Date(year, month, day);
        const currentDate = new Date();
        let age = currentDate.getFullYear() - birthday.getFullYear();
        const currentMonth = currentDate.getMonth();
        const currentDay = currentDate.getDate();
        if (currentMonth < month || (currentMonth === month && currentDay < day)) {
          age--;
        }
        return age;
      };

      $('[name="birthday"]').on("input", function() {
        let input = $(this).val();
        if (validateFormatAge(input)) {
          let age = calcuteAge(input);
          $('#age').val(age).trigger('input');
        } else {
          $('#age').val('');
        }
      });
    }

    // Función para manejar la selección y visualización de especialidades
    function buildEventsEspeciality() {
      const select = document.getElementById('especialitySelect');
      const tagsContainer = document.getElementById('especialityTags');
      const hiddenInput = document.getElementById('especialities_selected');

      let selectedEspecialities = [];

      function updateHiddenInput() {
        hiddenInput.value = selectedEspecialities.join(',');
      }

      function createTag(value, label) {
        const tag = document.createElement('span');
        tag.classList.add('tag-span');
        tag.setAttribute('data-value', value);
        tag.innerHTML = `${label} <span class="remove-tag">&times;</span>`;

        tag.querySelector('.remove-tag').addEventListener('click', () => {
          tag.remove();
          selectedEspecialities = selectedEspecialities.filter(item => item !== value);
          updateHiddenInput();
        });

        tagsContainer.appendChild(tag);
      }

      select.addEventListener('change', function () {
        const selectedValue = this.value;
        const selectedText = this.options[this.selectedIndex].text;
        if (selectedValue && !selectedEspecialities.includes(selectedValue)) {
          selectedEspecialities.push(selectedValue);
          createTag(selectedValue, selectedText);
          updateHiddenInput();
        }
        // Reset select
        this.value = '';
      });

      // Si existen especialidades precargadas (modo edición)
      const preloaded = hiddenInput.value.split(',').filter(v => v);
      preloaded.forEach(val => {
        const option = select.querySelector(`option[value="${val}"]`);
        const label = option ? option.textContent : val;
        if (!selectedEspecialities.includes(val)) {
          selectedEspecialities.push(val);
          createTag(val, label);
        }
      });
    }

    document.addEventListener('DOMContentLoaded', function () {
      buildRulesBirthday();
      buildEventsEspeciality();
    });





    $(document).ready(function(){
    /**
     * 
     * @returns 
     */
    $.fn.validations = function(){
        return [
            {
                "name":"noEmpty",
                "message":window.translations["create-user"].fieldRequired,
                "run":function (field){
                    if(field.key === "especialitySelect") return true;

                    if((field.key === "date") || (field.key === "user_id")) 
                        return true;
                    return ((field.value != undefined) && (field.value.trim() !== "")); 
                }
            },
            {
                "name":"noEquals",
                "message":window.translations["create-user"].passwordRepeatValid,
                "run":function (field){
                    if(field.key === "password"){
                        return (field.value === document.querySelector("[name='passwordRepeat']").value);
                    } 
                    return true; 
                }
            }
        ];
    }
    $("#UpdateDoctor").on("submit",function(e){
        let form    = document.querySelector("#UpdateDoctor");
        let data    = $.fn.getDataForm.call(this,form);
        let valid   = $.fn.runValidations(data,$.fn.validations());
        if(!valid.valid)
            e.preventDefault();
    });
})
  </script>
</div>
@endsection