<link rel="stylesheet" href="https://code.jquery.com/ui/1.14.1/themes/base/jquery-ui.css">
<div class="container-fluid">
   <div class="row">
      <div class="col-sm-12 col-lg-12">
         <div class="iq-card">
            <div class="iq-card-header d-flex justify-content-between">
               <div class="iq-header-title">
                  <h4 class="card-title">Walk-in Booking</h4>
               </div>
               <span class="table-add float-right mb-3 mr-2">
                  <a href="<?php echo base_url(); ?>Booking/" class="btn btn-default pull-right">
                     <i class="fa fa-arrow-left" aria-hidden="true"></i> Back
                  </a>&emsp;
               </span>
            </div>
            <div class="iq-card-body">
               <div class="alert alert-success Add" style="display: none;">
                    <strong>Booking Successful!</strong>
               </div>
               <div class="alert alert-danger Adderror" style="display: none;">
                    <strong>Booking Failed!</strong>
               </div>

               <form role="form" method="post" id="walkinFrm">
                  <div class="row">
                     <!-- Customer Details -->
                     <div class="col-lg-6">
                        <div class="form-group">
                           <label>Name</label>
                           <input type="text" name="name" class="form-control" required placeholder="Customer Name">
                        </div>
                        <div class="form-group">
                           <label>Email</label>
                           <input type="email" name="email" class="form-control" placeholder="Email">
                        </div>
                        <div class="form-group">
                           <label>Mobile</label>
                           <input type="text" name="mobile" class="form-control" required placeholder="Mobile">
                        </div>
                        <div class="form-group">
                           <label>Address</label>
                           <textarea name="address" class="form-control" placeholder="Address"></textarea>
                        </div>
                        <div class="form-group">
                           <label>Payment Type</label>
                           <select name="pay_type" class="form-control" required>
                              <option value="">Select Payment</option>
                              <option value="Cash">Cash</option>
                              <option value="UPI">UPI</option>
                              <option value="Card">Card</option>
                           </select>
                        </div>
                     </div>

                     <!-- Booking Details -->
                     <div class="col-lg-6">
                        <div class="form-group">
                           <label>Select Game</label>
                           <select class="form-control" name="sport_id" id="sport_id" required>
                              <option value="">Select Game</option>
                              <?php foreach ($sports as $s): ?>
                                 <option value="<?= $s->id ?>"><?= $s->name ?></option>
                              <?php endforeach; ?>
                           </select>
                        </div>

                        <div class="form-group">
                           <label>Select Pitch</label>
                           <select class="form-control" name="pitch_id" id="pitch_id" required></select>
                        </div>

                        <div class="form-group">
                           <label>Select Date</label>
                           <input type="text" name="booking_date" id="booking_date" class="form-control" required>
                        </div>

                        <div class="form-group">
                           <label>Available Slots</label>
                           <div id="slots_area" class="border p-2 rounded" style="min-height:60px;"></div>
                           <input type="hidden" name="start_time" id="start_time">
                           <input type="hidden" name="end_time" id="end_time">
                        </div>

                        <div class="form-group">
                           <label>Total Price</label>
                           <input type="text" name="total_price" id="total_price" class="form-control" readonly>
                        </div>
                     </div>

                     <div class="col-lg-12 text-right">
                        <button type="reset" class="btn btn-default">
                           <i class="fa fa-repeat"></i> Reset
                        </button>
                        <button type="submit" class="btn btn-primary addbtn">
                           <i class="fa fa-floppy-o"></i> Save Booking
                        </button>
                        <button class="btn btn-primary addload buttonload" style="display:none;">
                           <i class="fa fa-spinner fa-spin"></i> Please Wait
                        </button>
                     </div>
                  </div>
               </form>
            </div>
         </div>
      </div>
   </div>
</div>
  <script src="https://code.jquery.com/ui/1.14.1/jquery-ui.js"></script>
<script>
$(function(){

  // make loadSlots global so datepicker/onSelect can call it safely
  window.loadSlots = function(){
    let pitch_id = $("#pitch_id").val();
    let date = $("#booking_date").val();
    if(!pitch_id || !date) {
      $("#slots_area").html(''); // clear if nothing selected
      return;
    }

    $.post("<?= site_url('booking/get_slots') ?>", {
      pitch_id: pitch_id,
      date: date
    }, function(res){
      let data;
      try {
        data = typeof res === 'object' ? res : JSON.parse(res);
      } catch(e) {
        console.error('Invalid JSON from get_slots:', res);
        $("#slots_area").html('<div class="text-danger">Failed to load slots</div>');
        return;
      }

      let html = "";
      if(!data || data.length === 0){
        html = '<div class="text-muted">No slots available</div>';
      } else {
        data.forEach(function(s){
          // use bootstrap badge classes — adjust if your CSS differs
          let cls = s.is_booked ? "badge badge-danger m-1" : "badge badge-success m-1 slot";
          // show display (already contains start-end if your controller does)
          html += `<span class="${cls}" data-start="${s.start}" data-end="${s.end}" style="cursor:pointer;">${s.display}</span>`;
        });
      }
      $("#slots_area").html(html);
    });
  };

  // Initialize datepicker (jQuery UI)
  $("#booking_date").datepicker({
    dateFormat: "yy-mm-dd",
    minDate: 0,
    maxDate: "+365D",
    showAnim: "slideDown",
    onSelect: function(dateText, inst) {
      // call global loadSlots
      window.loadSlots();
    }
  }).datepicker('setDate', new Date()); // set default to today

  // If booking_date is manually changed (typed), refresh slots too
  $("#booking_date").on('change', function(){ window.loadSlots(); });

  // load pitches for selected sport
  $("#sport_id").on('change', function(){
    let sport_id = $(this).val();
    if(!sport_id){
      $("#pitch_id").html('<option value="">Select Pitch</option>');
      return;
    }
    $.get("<?= site_url('booking/get_pitches/') ?>" + sport_id, function(res){
      let data;
      try { data = typeof res === 'object' ? res : JSON.parse(res); } catch(e){ console.error(res); return; }
      let html = '<option value="">Select Pitch</option>';
      data.forEach(function(p){
        html += `<option value="${p.id}">${p.name}</option>`;
      });
      $("#pitch_id").html(html);

      // optionally auto-select the first pitch and load slots
      // let first = data.length ? data[0].id : null;
      // if(first) { $("#pitch_id").val(first); window.loadSlots(); }
    });
  });

  // When pitch changes, refresh slots
  $("#pitch_id").on('change', function(){ window.loadSlots(); });

  // slot click handler (delegated)
  $(document).on("click", ".slot", function(){
    // unselect other slots
    $(".slot").removeClass("badge-primary").addClass("badge-success");
    $(this).removeClass("badge-success").addClass("badge-primary");
    // set hidden inputs
    $("#start_time").val($(this).data("start"));
    $("#end_time").val($(this).data("end"));

    // fetch price for this selected slot
    $.post("<?= site_url('booking/get_price') ?>", {
      pitch_id: $("#pitch_id").val(),
      date: $("#booking_date").val(),
      start_time: $("#start_time").val(),
      end_time: $("#end_time").val()
    }, function(res){
      let data;
      try { data = typeof res === 'object' ? res : JSON.parse(res); } catch(e){ console.error(res); return; }
      $("#total_price").val(data.price || 0);
    });
  });

  // submit walkin booking
  $("#walkinFrm").on('submit', function(e){
    e.preventDefault();
    // simple validation: ensure slot selected
    if(!$("#start_time").val() || !$("#end_time").val()){
      alert('Please select a slot.');
      return;
    }

    $.ajax({
      type: 'POST',
      url: '<?= base_url("booking/save_walkin") ?>',
      data: $(this).serialize(),
      beforeSend: function(){
        $('.addbtn').hide();
        $('.addload').show();
      },
      success: function(msg){
        // backend should echo 'Success' on success
        if($.trim(msg) === 'Success'){
          $(".Add").show().delay(3000).fadeOut();
          $('#walkinFrm')[0].reset();
          // clear slots & price
          $("#slots_area").html('');
          $("#total_price").val('');
          // reset date to today (optional)
          $("#booking_date").datepicker('setDate', new Date());
        } else {
          console.error('Save Walkin response:', msg);
          $(".Adderror").show().delay(3000).fadeOut();
        }
        $('.addbtn').show();
        $('.addload').hide();
      },
      error: function(xhr, status, err){
        console.error('AJAX error', status, err);
        $(".Adderror").show().delay(3000).fadeOut();
        $('.addbtn').show();
        $('.addload').hide();
      }
    });
  });

  // Optional: if page initially has a selected sport/pitch, load slots now
  // e.g. if server prefilled #sport_id/#pitch_id
  setTimeout(function(){
    if($("#pitch_id").val() && $("#booking_date").val()){
      window.loadSlots();
    }
  }, 200);

});
</script>

