<?php include( 'inc/template.php' );?>
<div class="container-fluid flex-grow-1 container-p-y">
	<nav aria-label="breadcrumb">
	<ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="index.php">Home</a></li>
	<li class="breadcrumb-item"><a href="booking_list_with_gst.php">Booking List</a></li>
    <li class="breadcrumb-item active"><?php echo isset($_GET['id']) ? 'Update Booking' : 'Booking Add'; ?></li>
    </ol>
</nav>
	<link rel="stylesheet" href="assets/vendor/libs/quill/editor.css" />
<div class="card shadow p-4">
<form method="post" enctype="multipart/form-data">
  <!-- Customer Details -->
  <div class="row g-3">
	  
	  <div class="col-md-6">
      <label for="package_id" class="form-label">Booking Date</label>
     <input type="date" id="booking_date" name="booking_date" class="form-control" required value="<?php echo date('Y-m-d'); ?>" />

    </div>
    <div class="col-md-6">
      <label for="quotation_id" class="form-label">Quotation Details</label>
      
<select name="quotation_id" id="quotation_id" required class="select2 form-select form-select-lg">
  <option value="">Select Quotation</option>
  <?php 
    $result = $conn->query("SELECT quotations.id AS quotations_id,quotations.quotation_no,customers.name, customers.phone FROM quotations JOIN customers ON quotations.customer_id = customers.id WHERE quotations.status = 'accepted' ORDER BY customers.name ASC");

    while ($row = $result->fetch_assoc()) {
      $quotationNo = htmlspecialchars($row['quotation_no']);
      $customerName = htmlspecialchars(ucwords(strtolower($row['name'])));
      echo '<option value="' . $row['quotations_id'] . '">' . $quotationNo . ' [' . $customerName . ']</option>';
    }
  ?>
</select>

    </div>
	<input type="hidden" id="customer_id" name="customer_id"/>
    <!-- Package -->
    <div class="col-md-6">
      <label for="package_id" class="form-label">Package Name</label>
      <input type="text" id="package_name" name="package_name" class="form-control" readonly required/>
    </div>
	  <div class="col-md-6">
      <label for="package_id" class="form-label">Destination</label>
      <input type="text" id="destination" name="destination" class="form-control" readonly required/>
    </div>

    <div class="col-md-2">
      <label for="travel_date" class="form-label">Travel Date</label>
      <input type="date" id="travel_date" name="travel_date" class="form-control" readonly required />
    </div>
    <div class="col-md-2">
      <label for="nights" class="form-label">No. of Nights</label>
      <input type="number" id="nights" name="nights" min="1" max="100" class="form-control" readonly required />
    </div>
    <div class="col-md-2">
      <label for="rooms" class="form-label">No. of Rooms</label>
      <input type="number" id="rooms" name="rooms" min="1" max="100" class="form-control" readonly required />
    </div>
   
  </div>

  <!-- Pricing -->
  <div class="row g-3 mt-2">
    <h5>Package Pricing (Per Person)</h5>
	 <div class="col-md-4">
      <label for="adults" class="form-label">Adults</label>
      <input type="number" id="adults" name="adults" min="1" max="100" class="form-control" readonly required />
    </div>
    <div class="col-md-4">
      <label for="child" class="form-label">Child</label>
      <input type="number" id="child" name="child" min="0" max="100" class="form-control" readonly />
    </div>

    <div class="col-md-4">
      <label for="extrabed" class="form-label">Extra Bed</label>
      <input type="number" id="extrabed" name="extrabed" min="0" max="100" value="0" class="form-control" readonly required />
    </div>
    <div class="col-md-4">
      <label>Adult Price (INR)</label>
      <input type="number" name="adult_price" id="adult_price" class="form-control" readonly required>
    </div>
    <div class="col-md-4">
      <label>Child Price (INR)</label>
      <input type="number" name="child_price" id="child_price" class="form-control" readonly>
    </div>
    <div class="col-md-4">
      <label>Extra Bed Price (INR)</label>
      <input type="number" name="extra_bed_price" id="extra_bed_price" class="form-control" readonly>
    </div>
  </div>

  <!-- Other Charges -->
  <div class="row g-3 mt-2">
    <h5>Other Charges</h5>
    <div class="col-md-3">
      <label>Transport Type</label>
      <select name="transport_type" id="transport_type" class="form-select">
        <option value="">Select..</option>
        <option value="Private Cab">Private Cab</option>
        <option value="Shared Cab">Shared Cab</option>
        <option value="Bus">Bus</option>
        <option value="Train">Train</option>
        <option value="Flight">Flight</option>
        <option value="Self Drive">Self Drive</option>
      </select>
    </div>
    <div class="col-md-3">
      <label>Transport Charges (INR)</label>
      <input type="number" name="transport_charges" id="transport_charges" class="form-control" value="0">
    </div>
<!--
    <div class="col-md-3">
      <label>Extra Charges (INR)</label>
      <input type="number" name="extra_charges" id="extra_charges" class="form-control" value="0">
    </div>
-->
	<div class="col-md-3">
          <label for="gst_included" class="form-label">With GST?</label>
          <select id="gst_included" name="gst_included" class="form-select" required>
            <option value="no">No</option>
			  <option value="yes">Yes</option>
             </select>
        </div>
    
      <input type="hidden" name="gst" id="gst" class="form-control" value="5">
    
    <div class="col-md-3">
      <label>Discount %</label>
      <input type="number" name="discount" id="discount" class="form-control" value="0">
    </div>
	  <div class="col-md-6">
      <label>Grand Total (INR)</label>
      <input type="text" name="grand_total" id="grand_total" class="form-control" readonly>
    </div>
  </div>
	
  <!-- Total -->
  <div class="row g-3 mt-2">
   
    <div class="mt-4">
    <h5>Hotel Stay Details</h5>
     <div id="hotelRepeater">
      <div class="row g-2 hotelBlock border p-3 rounded mb-2 bg-white">
        <div class="col-md-3">
          <label>Hotel Name</label>
          <input type="text" name="hotel_name[]" data-name="hotel_name" class="form-control" required>
        </div>
        <div class="col-md-3">
          <label>Location</label>
          <input type="text" name="hotel_location[]" data-name="hotel_location" class="form-control" required>
        </div>
        <div class="col-md-1">
          <label>No. of Rooms</label>
          <input type="number" name="hotel_rooms[]" data-name="hotel_rooms" min="1" max="100" value="0" class="form-control" required>
        </div>

        <div class="col-md-2">
          <label>Hotel Type</label>
          <select name="hotel_type[]" data-name="hotel_type" class="form-select" required>
            <option value="">Select</option>
            <option value="3-star">3-star</option>
            <option value="4-star">4-star</option>
            <option value="5-star">5-star</option>
          </select>
        </div>
        <div class="col-md-3">
          <label>Meal Plan</label>
          <select name="meal_plan[]" data-name="meal_plan" class="form-select" required>
            <option value="">Select</option>
            <option value="CP">CP (Room + Breakfast)</option>
            <option value="MAP">MAP (Room + Breakfast + Dinner)</option>
            <option value="AP">AP (Room + All Meals)</option>
          </select>
        </div>
		  
      </div>
    </div>
    
  </div>
	  
  </div>
	<!-- Payment Mode and Advance Payment -->
<div class="row g-3 mt-2">
  <div class="col-md-4">
    <label for="payment_mode" class="form-label">Payment Mode</label>
    <select name="payment_mode" id="payment_mode" class="form-select" required>
      <option value="cash">Cash</option>
      <option value="upi">UPI</option>
      <option value="cheque">Cheque</option>
    </select>
  </div>

  <div class="col-md-4">
    <label for="advance_payment" class="form-label">Advance Payment (INR)</label>
    <input type="number" name="advance_payment" id="advance_payment" class="form-control" min="0" value="0" required>
  </div>
</div>

<!-- Conditional Fields -->
<div class="row g-3 mt-2" id="upi_details_group" style="display: none;">
  <div class="col-md-8">
    <label for="upi_details" class="form-label">UPI Details</label>
    <textarea name="upi_details" id="upi_details" class="form-control" rows="2"></textarea>
  </div>
</div>

<div class="row g-3 mt-2" id="bank_cheque_group" style="display: none;">
  <div class="col-md-4">
    <label for="cheque_no" class="form-label">Cheque No. / Ref No.</label>
    <input type="text" name="cheque_no" id="cheque_no" class="form-control">
  </div>
  <div class="col-md-4">
    <label for="bank_name" class="form-label">Bank Name</label>
    <input type="text" name="bank_name" id="bank_name" class="form-control">
  </div>
</div>


	<!-- Hidden Fields -->
      <input type="hidden" name="useridnew" value="<?php echo $adminId; ?>" />
      <input type="hidden" name="id" value="<?php echo isset($_GET['id']) ? $_GET['id'] : ''; ?>" />
      <input type="hidden" name="action" value="<?php echo isset($_GET['id']) ? 'Update' : 'Create'; ?>" />
  <div class="mt-4">
	  <button type="submit" class="btn btn-primary me-2"><?php echo isset($_GET['id']) ? 'Update' : 'Save'; ?></button>
		<button type="submit" id="download-pdf" class="btn btn-primary me-2"><?php echo isset($_GET['id']) ? 'Download PDF' : 'Download PDF'; ?></button>
    
    <button type="reset" class="btn btn-secondary">Reset</button>
  </div>
</form>
<script>
$(document).ready(function() {
  $('#payment_mode').on('change', function() {
    let mode = $(this).val();

    // Hide all groups first
    $('#upi_details_group, #bank_cheque_group').hide();

    // Remove required attributes from all optional inputs
    $('#upi_details').prop('required', false);
    $('#cheque_no').prop('required', false);
    $('#bank_name').prop('required', false);

    if (mode === 'upi') {
      $('#upi_details_group').show();
      $('#upi_details').prop('required', true);
    } else if (mode === 'cheque' || mode === 'bank_transfer') {
      $('#bank_cheque_group').show();
      $('#cheque_no').prop('required', true);
      $('#bank_name').prop('required', true);
    }
  });
});
</script>


<script>
$(document).ready(function() {
    $('#quotation_id').change(function() {
        var quotationId = $(this).val();

        if (quotationId != '') {
            $.ajax({
                url: 'controller/FetchQuotationDetails.php',
                method: 'POST',
                data: { quotation_id: quotationId },
                dataType: 'json',
                success: function(response) {
                    if (response.status == 'success') {
                        // Fill quotation details
                        var q = response.data.quotation;
						$('#customer_id').val(q.customer_id);
                        $('#package_name').val(q.package_name);
                        $('#destination').val(q.destination);
                        $('#travel_date').val(q.travel_date);
                        $('#nights').val(q.nights);
                        $('#rooms').val(q.rooms);
                        $('#adults').val(q.adults);
                        $('#child').val(q.child);
                        $('#extrabed').val(q.extrabed);
                        $('#adult_price').val(q.adult_price);
                        $('#child_price').val(q.child_price);
                        $('#extra_bed_price').val(q.extra_bed_price);
                        $('#transport_type').val(q.transport_type);
                        $('#transport_charges').val(q.transport_charges);
                        $('#gst_included').val(q.gst_included);
                        $('#discount').val(q.discount);
                        $('#grand_total').val(q.grand_total);

                        // Clear old hotel blocks
                        $('#hotelRepeater').html('');

                        // Fill hotel blocks
                        var hotels = response.data.hotels;
                        $.each(hotels, function(index, hotel) {
                            var hotelBlock = `
                            <div class="row g-2 hotelBlock border p-3 rounded mb-2 bg-white">
                                <div class="col-md-3">
                                  <label>Hotel Name</label>
                                  <input type="text" name="hotel_name[]" class="form-control" value="${hotel.hotel_name}" required>
                                </div>
                                <div class="col-md-3">
                                  <label>Location</label>
                                  <input type="text" name="hotel_location[]" class="form-control" value="${hotel.hotel_location}" required>
                                </div>
                                <div class="col-md-1">
                                  <label>No. of Rooms</label>
                                  <input type="number" name="hotel_rooms[]" class="form-control" value="${hotel.hotel_rooms}" required>
                                </div>
                                <div class="col-md-2">
                                  <label>Hotel Type</label>
                                  <select name="hotel_type[]" class="form-select" required>
                                    <option value="">Select</option>
                                    <option value="3-star" ${hotel.hotel_type == '3-star' ? 'selected' : ''}>3-star</option>
                                    <option value="4-star" ${hotel.hotel_type == '4-star' ? 'selected' : ''}>4-star</option>
                                    <option value="5-star" ${hotel.hotel_type == '5-star' ? 'selected' : ''}>5-star</option>
                                  </select>
                                </div>
                                <div class="col-md-3">
                                  <label>Meal Plan</label>
                                  <select name="meal_plan[]" class="form-select" required>
                                    <option value="">Select</option>
                                    <option value="CP" ${hotel.meal_plan == 'CP' ? 'selected' : ''}>CP</option>
                                    <option value="MAP" ${hotel.meal_plan == 'MAP' ? 'selected' : ''}>MAP</option>
                                    <option value="AP" ${hotel.meal_plan == 'AP' ? 'selected' : ''}>AP</option>
                                  </select>
                                </div>
                                
                            </div>
                            `;
                            $('#hotelRepeater').append(hotelBlock);
                        });
                    } else {
                        alert('Quotation details not found.');
                    }
                }
            });
        }
    });

    // Remove hotel block
    $(document).on('click', '.removeHotelBtn', function() {
        $(this).closest('.hotelBlock').remove();
    });
});

</script>


<script>
	$(document).ready(function() {
    

	    // Manage download PDF after submit
    let downloadPdfAfterSubmit = false;
    $('#download-pdf').click(function (e) {
        e.preventDefault();
        downloadPdfAfterSubmit = true;
        $('form').submit();
    });

		
    // Form submission handling for creating or updating
    $('form').submit(function (e) {
    e.preventDefault();
    let formData = new FormData(this);

    // Validate required fields
    if (!formData.get("quotation_id") || !formData.get("package_name")) {
        toastr.error("Customer Name and Package Name are required.");
        return;
    }

    $.ajax({
        url: 'controller/BookingController.php',
        method: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function (response) {
            if (response.status === 'success') {
                toastr.success(response.message);
                
                if (downloadPdfAfterSubmit && response.id) {
                    window.open('controller/DownloadPDFBookingController.php?id=' + response.id, '_blank');
                    downloadPdfAfterSubmit = false;
                }

                // Redirect based on GST inclusion
                let redirectUrl = response.gst_included === 'yes' ? 'booking_list_with_gst.php' : 'booking_list_without_gst.php';

                setTimeout(() => window.location.href = redirectUrl, 1500);
                
            } else {
                toastr.error(response.message || 'An error occurred.');
            }
        },
        error: function (xhr, status, error) {
            toastr.error('An error occurred while submitting.');
            console.error('AJAX Error:', status, error, xhr.responseText);
        }
    });
});

    
});
</script>
<script src="iadmin/assets/js/form-wizard-numbered.js"></script>
<script src="iadmin/assets/js/form-wizard-validation.js"></script>
<?php include('inc/footer.php');?>