<div class="container-xxl flex-grow-1 container-p-y">
              <h4 class="py-3 mb-4"><span class="text-muted fw-light">Edit Profile</h4>
              
  <div class="row"><div class="col-md-6">
      <div class="card mb-4">
          <form method="post" action="#" id="inputform" enctype="multipart/form-data">
        <div class="card-body">
            
            <div class="mb-3">
                <label for="name" class="form-label"> Name</label>
                <input
                  type="text"
                  class="form-control"
                  id="name"
                  name="name"
                  placeholder="Name" required value="<?=$profile[0]['name']?>"/>
              </div>
              
              <div class="mb-3">
                <label for="mobile" class="form-label"> Mobile</label>
                <input
                  type="tel"
                  class="form-control"
                  id="mobile"
                  name="mobile"
                  required autofocus  maxlength="10" pattern="[0-9]{10}" placeholder="Mobile" oninput="this.value = this.value.replace(/[^0-9]/g, '')" value="<?=$profile[0]['mobile']?>" disabled/>
              </div>
              
              <div class="mb-3">
                <label for="email" class="form-label"> Email</label>
                <input
                  type="email"
                  class="form-control"
                  id="email"
                  name="email"
                  placeholder="Email" required value="<?=$profile[0]['email']?>" disabled/>
              </div>
              
              <div class="mb-3">
                <label for="logo" class="form-label"> Logo</label>
                <input
                  type="file"
                  class="form-control"
                  id="logo"
                  name="logo"
                  placeholder="Logo"/>
              </div>
              <p style="color:red">please upload only jpg,jpeg or png format files</p>
          <img src="<?php echo $this->config->item('bharosa_base_url').$profile[0]['logo'];?>" alt="banner" width="60" height="60">
              
             <div class="mb-3">
                <label for="cat_id" class="form-label"> Categories</label>
                <select class="form-select" id="cat_id" name="cat_id" placeholder="Category" required onchange="get_specialities(this.value)" disabled>
                    <option value="">Select Category</option>
                    <?php if(!empty($categories)){ 
                        foreach($categories as $row){ ?>
                        <option value="<?=$row['id']?>" <?php if($row['id']==$profile[0]['cat_id']){echo 'selected="selected"';}?>><?=$row['name']?></option>
                    <?php } } ?>
                </select>
             </div>
             
             <?php 
             
             // Get all specialities for the hospital
                $specialities = $this->registermodel->common_fetch(
                    'specialities',
                    ['cat_id' => $profile[0]['cat_id'], 'status' => 1, 'delete_status' => 1]
                );
                
                // Get speciality IDs already linked to this hospital (main_data_id)
                $selected_specialities = $this->registermodel->common_fetch(
                    'main_data_specialities',
                    ['main_data_id' => $profile[0]['id'], 'status' => 1, 'delete_status' => 1]
                );
                
                // Extract the IDs into an array
                $selected_ids = array_column($selected_specialities, 'speciality_id');

             ?>
             
             <div class="mb-3">
              <label for="speciality_id" class="form-label">Specialities</label>
              <select class="form-select" id="speciality_id" name="speciality_id[]" multiple>
                <?php if (!empty($specialities)) {
                    foreach ($specialities as $row) {
                        $isSelected = in_array($row['id'], $selected_ids);
                        echo '<option value="' . $row['id'] . '" ' . ($isSelected ? 'selected disabled' : '') . '>' . $row['name'] . '</option>';
                    }
                } ?>
              </select>
            </div>

            
            <div class="mb-3">
                <label for="pharmacy" class="form-label"> Pharmacy</label>
                <select class="form-select" id="pharmacy" name="pharmacy" placeholder="Pharmacy" required >
                    <option value="">Select Status</option>
                    <option value="yes" <?php if($profile[0]['pharmacy']=='yes'){echo 'selected="selected"';}?>>Yes</option>
                    <option value="no" <?php if($profile[0]['pharmacy']=='no'){echo 'selected="selected"';}?>>No</option>
                </select>
            </div>
            
            <div class="mb-3">
                <label for="diagnostic" class="form-label"> Diagnostic</label>
                <select class="form-select" id="diagnostic" name="diagnostic" placeholder="Diagnostic" required>
                    <option value="">Select Status</option>
                    <option value="yes" <?php if($profile[0]['diagnostic']=='yes'){echo 'selected="selected"';}?>>Yes</option>
                    <option value="no" <?php if($profile[0]['diagnostic']=='no'){echo 'selected="selected"';}?>>No</option>
                </select>
            </div>
            
            <div class="mb-3">
                <label for="home_delivery" class="form-label"> Home Delivery</label>
                <select class="form-select" id="home_delivery" name="home_delivery" placeholder="Home Delivery" required>
                    <option value="">Select Status</option>
                    <option value="yes" <?php if($profile[0]['home_delivery']=='yes'){echo 'selected="selected"';}?>>Yes</option>
                    <option value="no" <?php if($profile[0]['home_delivery']=='no'){echo 'selected="selected"';}?>>No</option>
                </select>
            </div>
            
            <div class="mb-3">
                <label for="location" class="form-label"> Location</label>
                <textarea class="form-control" id="location" name="location" placeholder="Location" rows="4" cols="10" required ><?=$profile[0]['location']?></textarea>
            </div>
            
            <div class="mb-3">
                <label for="latitude" class="form-label"> Latitude</label>
                <input
                  type="text"
                  class="form-control"
                  id="latitude"
                  name="lat"
                  placeholder="Latitude"
                  required
                  pattern="^-?\d+\.\d+$"
                  title="Enter a valid latitude (positive or negative decimal)" value="<?=$profile[0]['lat']?>"/>
              </div>
              
              <div class="mb-3">
                <label for="longitude" class="form-label"> Longitude</label>
                <input
                  type="text"
                          class="form-control"
                          id="longitude"
                          name="lon"
                          placeholder="Longitude"
                          required
                          pattern="^-?\d+\.\d+$"
                          title="Enter a valid longitude (positive or negative decimal)" value="<?=$profile[0]['lon']?>"/>
              </div>
            
            <div class="mb-3">
                <label for="description" class="form-label"> Description</label>
                <textarea class="form-control" id="description" name="description" placeholder="Description" rows="4" cols="10" required><?=$profile[0]['description']?></textarea>
            </div>
              
             <div class="mb-3">
              <label for="open_time" class="form-label">Open Time</label>
              <select class="form-control" id="open_time" name="open_time">
                <!-- Options populated via JS -->
              </select>
            </div>
            
            <div class="mb-3">
              <label for="close_time" class="form-label">Close Time</label>
              <select class="form-control" id="close_time" name="close_time">
                <!-- Options populated via JS -->
              </select>
            </div>
          
          <input
                  type="hidden"
                  class="form-control"
                  id="logo"
                  name="logo"
                  placeholder="Logo" required value="<?=$profile[0]['logo']?>"/>
        </div>
      </div>
       <button type="button" name="sub" value="sub" class="btn btn-success" id="saveBtn">Submit</button>
      </form>
      
    </div></div>
</div>


<script>
$(document).ready(function () {
    $('#saveBtn').on('click', function () {
        let isValid = true;

        // Validate required fields
        $('#inputform [required]').each(function () {
            let value = $(this).val();
            if (Array.isArray(value)) {
                value = value.join('');
            }
            value = value ? value.toString().trim() : '';

            if (value === '') {
                isValid = false;
                $(this).addClass('is-invalid').removeClass('is-valid');
                showToast('Error', `${$(this).attr('placeholder')} is required`, 'error');
            } else {
                $(this).removeClass('is-invalid').addClass('is-valid');
            }
        });
        
    
        if (isValid) {
            
            // Name Validation (should not start with special character)
            const nameField = $('input[name="name"]');
            const name = nameField.val().trim();
            const namePattern = /^[A-Za-z0-9]/;
            
            if (!namePattern.test(name)) {
                isValid = false;
                nameField.addClass('is-invalid').removeClass('is-valid');
                showToast('Error', 'Name must start with a letter or number (no special characters at the beginning)', 'error');
                $('html, body').animate({ scrollTop: nameField.offset().top - 100 }, 500);
                return;
            } else {
                nameField.removeClass('is-invalid').addClass('is-valid');
            }
            
            // Latitude Validation (must be decimal, can be negative)
            const latField = $('#latitude');
            const latitude = latField.val().trim();
            const latPattern = /^-?\d+\.\d+$/;
            
            if (!latPattern.test(latitude)) {
                isValid = false;
                latField.addClass('is-invalid').removeClass('is-valid');
                showToast('Error', 'Latitude must be a decimal number (e.g., 12.345 or -45.67)', 'error');
                $('html, body').animate({ scrollTop: latField.offset().top - 100 }, 500);
                return;
            } else {
                latField.removeClass('is-invalid').addClass('is-valid');
            }
            
            // Longitude Validation (must be decimal, can be negative)
            const lonField = $('#longitude');
            const longitude = lonField.val().trim();
            const lonPattern = /^-?\d+\.\d+$/;
            
            if (!lonPattern.test(longitude)) {
                isValid = false;
                lonField.addClass('is-invalid').removeClass('is-valid');
                showToast('Error', 'Longitude must be a decimal number (e.g., 78.123 or -90.456)', 'error');
                $('html, body').animate({ scrollTop: lonField.offset().top - 100 }, 500);
                return;
            } else {
                lonField.removeClass('is-invalid').addClass('is-valid');
            }
            
            // Description Validation (minimum 3 characters)
            const descField = $('#description');
            const description = descField.val().trim();
            
            if (description.length < 3) {
                isValid = false;
                descField.addClass('is-invalid').removeClass('is-valid');
                showToast('Error', 'Description must be at least 3 characters', 'error');
                $('html, body').animate({ scrollTop: descField.offset().top - 100 }, 500);
                return;
            } else {
                descField.removeClass('is-invalid').addClass('is-valid');
            }
            const form = $('#inputform')[0];
            const formData = new FormData(form);

            $.ajax({
                url: '<?= base_url("admin/register/profile_data"); ?>',
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function (response) {
                    const res = JSON.parse(response);
                    if (res.success) {
                        showToast('Success', res.message, 'success');
                        window.location.href = '<?= base_url("admin/register/") ?>';
                    } else {
                        showToast('Error', res.message, 'error');
                    }
                },
                error: function () {
                    showToast('Error', 'An unexpected error occurred.', 'error');
                }
            });
        } else {
            $('html, body').animate({
                scrollTop: $('.is-invalid:first').offset().top - 100
            }, 500);
        }
    });

    // Remove validation feedback on input/change
    $('#inputform .form-control').on('input change', function () {
        if ($(this).val().trim() !== '') {
            $(this).removeClass('is-invalid').addClass('is-valid');
        } else {
            $(this).removeClass('is-valid').addClass('is-invalid');
        }
    });
});
</script>

<script>
    function get_specialities(cat_id) {
        $.ajax({
            url: '<?= base_url("admin/register/get_specialities/"); ?>' + cat_id,
            type: 'POST',
            dataType: 'json',
            success: function (res) {
                if (res.success) {
                    $('#speciality_id').html(res.data); // will be blank if no specialities
                }
            },
            error: function () {
                showToast('Error', 'An unexpected error occurred.', 'error');
            }
        });
    }

</script>

<script>
const selectedOpenTime = "<?= $profile[0]['open_time'] ?>";   // e.g. "09:00 AM"
const selectedCloseTime = "<?= $profile[0]['close_time'] ?>"; // e.g. "06:00 PM"

// Time options in 12-hour format (1-hour intervals)
const timeSlots = [
  '12:00 AM', '01:00 AM', '02:00 AM', '03:00 AM', '04:00 AM', '05:00 AM',
  '06:00 AM', '07:00 AM', '08:00 AM', '09:00 AM', '10:00 AM', '11:00 AM',
  '12:00 PM', '01:00 PM', '02:00 PM', '03:00 PM', '04:00 PM', '05:00 PM',
  '06:00 PM', '07:00 PM', '08:00 PM', '09:00 PM', '10:00 PM', '11:00 PM'
];

function generateTimeOptions(selectedTime, selectId) {
  let options = '';

  if (selectedTime) {
    options += `<option value="${selectedTime}" selected>${selectedTime}</option>`;
  } else {
    options += `<option value="">Select Time</option>`;
  }

  for (let time of timeSlots) {
    if (time === selectedTime) continue; // skip if already selected
    options += `<option value="${time}">${time}</option>`;
  }

  document.getElementById(selectId).innerHTML = options;
}

// Populate open and close dropdowns
generateTimeOptions(selectedOpenTime, 'open_time');
generateTimeOptions(selectedCloseTime, 'close_time');
</script>



<!-- Toastr CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet">
<!-- Toastr JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

<script>
// Show toast using jQuery
function showToast(title, message, type) {
    toastr.options = {
        closeButton: true,
        progressBar: true,
        positionClass: "toast-top-right",
        timeOut: "3000",
    };

    if (type === 'success') {
        toastr.success(message, title);
    } else if (type === 'error') {
        toastr.error(message, title);
    } else if (type === 'info') {
        toastr.info(message, title);
    } else if (type === 'warning') {
        toastr.warning(message, title);
    }
}


</script>
            