<?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="quotation_list.php">Quotation List</a></li>
    <li class="breadcrumb-item active"><?php echo isset($_GET['id']) ? 'Update Quotation' : 'Quotation Add'; ?></li>
    </ol>
</nav>
	<link rel="stylesheet" href="assets/vendor/libs/quill/editor.css" />
<button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#basicModal">
        <span class="ti-xs ti ti-plus me-1"></span> Add New Customer
    </button>
<div class="modal fade" id="basicModal" tabindex="-1" aria-labelledby="basicModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <form id="CustomerForm">
                        <div class="modal-header">
                            <h5 class="modal-title" id="basicModalLabel">Customer Form</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            
                            <div class="row">
                                <div class="col mb-3">
                                    <label for="name" class="form-label">Customer Name</label>
                                    <input type="text" id="name" name="name" class="form-control" placeholder="Enter Name" required />
                                </div>
                            </div>

                            <!-- Phone -->
                            <div class="row">
                                <div class="col mb-3">
                                    <label for="mobile" class="form-label">Mobile</label>
                                    <input type="tel" id="phone" name="phone" class="form-control" placeholder="Enter Mobile Number" pattern="\d{10}" maxlength="10" required />
                                </div>
                            </div>

                            <!-- Email -->
                            <div class="row">
                                <div class="col mb-3">
                                    <label for="email" class="form-label">Email</label>
                                    <input type="email" id="email" name="email" class="form-control" required />
                                </div>
                            </div>
							
							
                            <!-- Username -->
                            <div class="row">
                                <div class="col mb-3">
                                    <label for="username" class="form-label">Address</label>
                                    <input type="text" id="address" name="address" class="form-control" />
                                </div>
                            </div>

                        </div>
                        <div class="modal-footer">
                            <input type="hidden" name="id" id="id" />
                            <input type="hidden" name="action" id="action" value="Create" />
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary">Save Changes</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
<script>
$(document).ready(function () {

    // Show modal for Create
    $('#modal_button').click(function () {
        $('#CustomerForm')[0].reset();
        $('.modal-title').text("Create New Customer");
        $('#action').val('Create');
        $('#id').val('');
        $('#basicModal').modal('show');
    });

    // Submit form for Create or Update
    $('#CustomerForm').on('submit', function (e) {
        e.preventDefault();

        const formData = {
            name: $('#name').val().trim(),
            phone: $('#phone').val().trim(),
            email: $('#email').val().trim(),
            address: $('#address').val().trim(),
            action: $('#action').val(),
            id: $('#id').val()
        };

        if (formData.name && formData.phone && formData.email) {
            $.ajax({
                url: "controller/CustomerController.php",
                method: "POST",
                data: formData,
                dataType: "json",
                success: function (response) {
                    $('#basicModal').modal('hide');
                    if (response.status === 'success') {
                        toastr.success(response.message);
                        // Dynamically add the new customer to the dropdown
                        const newCustomer = response.customer;
                        const newOption = `<option value="${newCustomer.id}">${newCustomer.name} ${newCustomer.phone}</option>`;
                        $('#customer_id').append(newOption); // Add the new customer option to the dropdown

                        // Optionally, set the dropdown to select the newly added customer
                        $('#customer_id').val(newCustomer.id);

                        setTimeout(function() {
                            $('#basicModal').modal('hide'); // Hide modal
                        }, 3000);  // Wait 3 seconds before closing modal and refreshing dropdown

                    } else {
                        toastr.error(response.message);
                    }
                },
                error: function () {
                    toastr.error('Request failed. Please try again.');
                }
            });
        } else {
            toastr.error("Please fill all required fields.");
        }
    });
    
    // Function to reload the customer dropdown
    function loadCustomerDropdown() {
        $.ajax({
            url: "controller/CustomerController.php",
            method: "GET",
            data: { action: 'getCustomers' },
            success: function (response) {
                if (response.status === 'success') {
                    const customerSelect = $('#customer_id');
                    customerSelect.empty();  // Clear the current options
                    customerSelect.append('<option value="">Select Customer</option>');  // Add default option
                    response.customers.forEach(function (customer) {
                        customerSelect.append('<option value="' + customer.id + '">' + customer.name + ' ' + customer.phone + '</option>');
                    });

                    // If no customers exist, show a "No results found" message (using Select2 or custom message)
                    if (response.customers.length === 0) {
                        customerSelect.append('<option value="" disabled>No customers found</option>');
                    }
                } else {
                    toastr.error('Failed to load customers.');
                }
            },
            error: function () {
                toastr.error('Error loading customers.');
            }
        });
    }

});
</script>
<div class="card shadow p-4">
<form method="post" id="reference_quotation" enctype="multipart/form-data">
  <!-- Customer Details -->
  <div class="row g-3">
    <div class="col-md-6">
      <label for="customer_id" class="form-label">Customer Name</label>
      <select name="customer_id" id="customer_id" required class="select2 form-select form-select-lg">
  <option value="">Select Customer</option>
  <?php 
    $result = $conn->query("SELECT id, name, phone FROM customers WHERE status = 'active' ORDER BY name ASC");
    while ($row = $result->fetch_assoc()) {
      echo '<option value="' . $row['id'] . '">' . htmlspecialchars(ucwords(strtolower($row['name']))) . ' ' . htmlspecialchars($row['phone']) . '</option>';
    }
  ?>
</select>


    </div>

    <!-- 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" 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" 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" />
	  <input type="hidden" id="inquiry_id" name="inquiry_id" />
    </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" />
    </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" />
    </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" />
    </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" value="0" class="form-control" />
    </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" />
    </div>
    <div class="col-md-4">
      <label>Adult Price (INR)</label>
      <input type="number" name="adult_price" id="adult_price" value="0" class="form-control" required>
    </div>
    <div class="col-md-4">
      <label>Child Price (INR)</label>
      <input type="number" name="child_price" id="child_price" value="0" class="form-control" required>
    </div>
    <div class="col-md-4">
      <label>Extra Bed Price (INR)</label>
      <input type="number" name="extra_bed_price" id="extra_bed_price" value="0" class="form-control" required>
    </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="hotels[0][hotel_name]" class="form-control" required>
    </div>
    <div class="col-md-3">
      <label>Location</label>
      <input type="text" name="hotels[0][hotel_location]" class="form-control" required>
    </div>
    <div class="col-md-1">
      <label>No. of Rooms</label>
      <input type="number" name="hotels[0][hotel_rooms]" min="1" max="100" value="1" class="form-control" required>
    </div>
    <div class="col-md-2">
      <label>Hotel Type</label>
      <select name="hotels[0][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="hotels[0][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 class="col-md-2 d-flex align-items-end">
      <button type="button" class="btn btn-danger btn-sm removeHotelBtn">Remove</button>
    </div>
  </div>
</div>

    <button type="button" class="btn btn-primary btn-sm mt-2" id="addHotelBtn">+ Add Another Hotel</button>
  </div>
	  <div class="col-md-12">
  <label class="form-label">Description</label>
  <div id="editor_description" class="quill-editor"></div>
  <input type="hidden" name="description" id="desc_input">
</div>
<?php
$result = mysqli_query($conn, "SELECT inclusions FROM packages_inclusions WHERE status = 'active' LIMIT 1");
$row = mysqli_fetch_array($result);
?>

<!-- Inclusions -->
<div class="col-md-12">
  <label class="form-label">Inclusions</label>
  <div id="editor_inclusions" class="quill-editor"></div>
  <input type="hidden" name="inclusions" value="<?php echo $row['inclusions'] ?>" id="incl_input">
</div>

	  <div class="col-md-12">
  <label class="form-label">Exclusions</label>
  <div id="editor_exclusions" class="quill-editor"></div>
  <input type="hidden" name="exclusions" id="excl_input">
</div>
  </div>
	<!-- Hidden Fields -->
      <input type="hidden" name="useridnew" id="useridnew" value="<?php echo $adminId; ?>" />
      <input type="hidden" name="id" id="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">Save</button>
		<button type="button" id="download-pdf" class="btn btn-primary me-2">Download PDF</button>
    
    <button type="reset" class="btn btn-secondary">Reset</button>
  </div>
</form>
<script src="assets/vendor/libs/quill/quill.js"></script>
<script>
	$(document).ready(function() {
	
    let baseAdultPrice = 0;
    let baseChildPrice = 0;
    let baseExtraBedPrice = 0;
    let downloadPdfAfterSubmit = false;
    let editing = false;

    // Price input events
    $('#adult_price, #child_price, #extra_bed_price').on('input', function () {
        baseAdultPrice = parseFloat($('#adult_price').val()) || 0;
        baseChildPrice = parseFloat($('#child_price').val()) || 0;
        baseExtraBedPrice = parseFloat($('#extra_bed_price').val()) || 0;
        updateTotalPrices();
    });

    // Quantity input events
    $('#adults, #child, #extrabed').on('input', function () {
        updateTotalPrices();
    });

    function updateTotalPrices() {
        let adults = parseInt($('#adults').val()) || 0;
        let child = parseInt($('#child').val()) || 0;
        let extrabed = parseInt($('#extrabed').val()) || 0;

        let totalAdult = baseAdultPrice * adults;
        let totalChild = baseChildPrice * child;
        let totalExtraBed = baseExtraBedPrice * extrabed;

        $('#total_adult_price').val(totalAdult.toFixed(2));
        $('#total_child_price').val(totalChild.toFixed(2));
        $('#total_extrabed_price').val(totalExtraBed.toFixed(2));

        calculateTotalAmount(totalAdult, totalChild, totalExtraBed);
    }

    function calculateTotalAmount(totalAdult = 0, totalChild = 0, totalExtraBed = 0) {
    totalAdult = isNaN(totalAdult) ? 0 : totalAdult;
    totalChild = isNaN(totalChild) ? 0 : totalChild;
    totalExtraBed = isNaN(totalExtraBed) ? 0 : totalExtraBed;

    let transportCharges = parseFloat($('#transport_charges').val()) || 0;
    let discountPercent = parseFloat($('#discount').val()) || 0;
    let gstPercent = parseFloat($('#gst').val()) || 0;
    let gstIncluded = $('#gst_included').val();

    let baseSubtotal = totalAdult + totalChild + totalExtraBed;

    if (discountPercent > 0) {
        baseSubtotal -= (baseSubtotal * (discountPercent / 100));
    }

    if (gstIncluded === 'yes') {
        baseSubtotal += (baseSubtotal * (gstPercent / 100));
    }

    let grandTotal = baseSubtotal + transportCharges;

    $('#grand_total').val(grandTotal.toFixed(2));
}


    $('#transport_charges, #discount, #gst, #gst_included').on('input change', function () {
        updateTotalPrices();
    });

    // Quill Editor for exclusions
    const fullToolbar = [
        [{ font: [] }, { size: [] }],
        ['bold', 'italic', 'underline', 'strike'],
        [{ color: [] }, { background: [] }],
        [{ script: 'super' }, { script: 'sub' }],
        [{ header: '1' }, { header: '2' }, 'blockquote', 'code-block'],
        [{ list: 'ordered' }, { list: 'bullet' }, { indent: '-1' }, { indent: '+1' }],
        [{ direction: 'rtl' }],
        ['link', 'image', 'video', 'formula'],
        ['clean']
    ];
		
	 // Initialize each editor separately
  const editorDescription = new Quill('#editor_description', {
    bounds: '#editor_description',
    placeholder: 'Type Description...',
    modules: { toolbar: fullToolbar },
    theme: 'snow'
  });

  // Initialize Inclusions Editor
const editorInclusions = new Quill('#editor_inclusions', {
  bounds: '#editor_inclusions',
  placeholder: 'Type Inclusions...',
  modules: { toolbar: fullToolbar },
  theme: 'snow'
});

// Set initial content from hidden input
const inclInput = document.getElementById('incl_input');
if (inclInput && inclInput.value) {
  editorInclusions.root.innerHTML = inclInput.value;
}


    const editorExclusions = new Quill('#editor_exclusions', {
        bounds: '#editor_exclusions',
        placeholder: 'Type Exclusions...',
        modules: { toolbar: fullToolbar },
        theme: 'snow'
    });
		$('#download-pdf').click(function () {
    downloadPdfAfterSubmit = true;
    $('form').submit();
});

    $('form').on('submit', function () {
        // Collect exclusions data
        $('#desc_input').val(editorDescription.root.innerHTML);
		$('#incl_input').val(editorInclusions.root.innerHTML);
		$('#excl_input').val(editorExclusions.root.innerHTML);
    });
		
	// Add new hotel block
$('#addHotelBtn').click(function () {
  var block = $('#hotelRepeater .hotelBlock').first().clone();
  block.find('input, select').each(function () {
    $(this).val('');
  });
  $('#hotelRepeater').append(block);
  updateHotelBlockIndexes();
});

// Remove hotel block
$(document).on('click', '.removeHotelBtn', function () {
  if ($('.hotelBlock').length > 1) {
    $(this).closest('.hotelBlock').remove();
    updateHotelBlockIndexes();
  } else {
    alert('At least one hotel entry is required.');
  }
});

// Update index names
function updateHotelBlockIndexes() {
  $('#hotelRepeater .hotelBlock').each(function (index) {
    $(this).find('input, select').each(function () {
      let baseName = $(this).attr('name').split('[').pop().split(']')[0]; // Get field name
      $(this).attr('name', `hotels[${index}][${baseName}]`);
    });
  });
}


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

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

        $.ajax({
            url: 'controller/QuotationController.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/DownloadPDFQuotationController.php?id=' + response.id, '_blank');
                        downloadPdfAfterSubmit = false;
                        setTimeout(() => window.location.href = 'quotation_list.php', 1500);
                    } else {
                        setTimeout(() => window.location.href = 'quotation_list.php', 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');?>