<?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="inquiry_list.php">Quotation List</a></li>
    <li class="breadcrumb-item active">Update Quotation</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="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 inquiries.id, inquiries.customer_id, customers.name, customers.phone 
                                  FROM inquiries 
                                  JOIN customers ON inquiries.customer_id = customers.id 
                                  WHERE inquiries.followup_status = 'done' 
                                  ORDER BY customers.name ASC");
          while ($row = $result->fetch_assoc()) {
            echo '<option value="' . $row['customer_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" value="0" 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" 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" class="form-control" required>
    </div>
    <div class="col-md-4">
      <label>Child Price (INR)</label>
      <input type="number" name="child_price" id="child_price" 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" 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="hotelTemplate" class="d-none">
  <div class="row g-2 hotelBlock border p-3 rounded mb-2 bg-white">
    <div class="col-md-4">
      <input type="text" name="hotel_name[]" data-name="hotel_name" class="form-control" placeholder="Hotel Name">
    </div>
    <div class="col-md-3">
      <input type="text" name="hotel_location[]" data-name="hotel_location" class="form-control" placeholder="Location">
    </div>
    <div class="col-md-1">
      <input type="number" name="hotel_rooms[]" data-name="hotel_rooms" class="form-control" placeholder="Rooms">
    </div>
    <div class="col-md-2">
      <select name="hotel_type[]" data-name="hotel_type" class="form-select">
        <option value="">Type</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-2">
      <select name="meal_plan[]" data-name="meal_plan" class="form-select">
        <option value="">Meal Plan</option>
        <option value="CP">CP</option>
        <option value="MAP">MAP</option>
        <option value="AP">AP</option>
      </select>
    </div>
  </div>
</div>

	
    <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 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>

<!-- 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" 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" id="action" value="<?php echo isset($_GET['id']) ? 'Update' : ''; ?>" />

<div class="mt-4">
    <!-- Update Button -->
    <button type="submit" class="btn btn-primary me-2">Update</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>

    
   
  </div>
</form>


<script src="assets/vendor/libs/quill/quill.js"></script>
<script>
	$(document).ready(function() {
    let baseAdultPrice = 0;
    let baseChildPrice = 0;
    let baseExtraBedPrice = 0;
    
    // 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;
        console.log('Prices updated:', baseAdultPrice, baseChildPrice, baseExtraBedPrice);
        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;

        console.log('Total prices calculated:', totalAdult, totalChild, totalExtraBed);

        $('#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();
    });
});

	</script>
	<script>
$(document).ready(function () {
	
    let editing = false;

    // Quill Editor setup
    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']
    ];
	
	 const editorDescription = new Quill('#editor_description', {
    bounds: '#editor_description',
    placeholder: 'Type Description...',
    modules: { toolbar: fullToolbar },
    theme: 'snow'
  });

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

    const editorExclusions = new Quill('#editor_exclusions', {
        bounds: '#editor_exclusions',
        placeholder: 'Type Exclusions...',
        modules: { toolbar: fullToolbar },
        theme: 'snow'
    });

    // Save exclusions to hidden input on submit
    $('form').on('submit', function () {
		
		$('#desc_input').val(editorDescription.root.innerHTML);
		$('#incl_input').val(editorInclusions.root.innerHTML);
        $('#excl_input').val(editorExclusions.root.innerHTML);
    });

    // Add hotel block
    $('#addHotelBtn').click(function () {
        const block = $('#hotelTemplate .hotelBlock').first().clone().removeClass('d-none');
        block.find('input, select').val('').prop('required', true);
        $('#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.');
        }
    });

    // Reindex hotel blocks
    function updateHotelBlockIndexes() {
        $('#hotelRepeater .hotelBlock').each(function (index) {
            $(this).find('.block-title').text('Hotel ' + (index + 1));
            $(this).find('input, select').each(function () {
                const name = $(this).attr('data-name');
                if (name) {
                    $(this).attr('name', `hotels[${index}][${name}]`);
                }
            });
        });
    }

    // Load inquiry details on customer change
    $('#customer_id').change(function () {
        if (editing) return;

        const customerId = $(this).val();
        if (customerId) {
            $.ajax({
                url: 'controller/InquiryFetchController.php',
                method: 'POST',
                data: { customer_id: customerId, action: 'fetch_inquiry_details' },
                dataType: 'json',
                success: function (response) {
                    if (response.status === 'success') {
                        Object.entries(response.data).forEach(([key, val]) => {
                            $('#' + key).val(val);
                        });
                        calculateTotalAmount();
                    }
                }
            });
        }
    });
	    let downloadPdfAfterSubmit = false;
    $('#download-pdf').click(function (e) {
        e.preventDefault();
        downloadPdfAfterSubmit = true;
        $('form').submit();
    });

    // Submit form via AJAX
    $('form').submit(function (e) {
        e.preventDefault();

        const formData = new FormData(this);
        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 {
                    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);
            }
        });
    });

    // Edit mode: populate data
    const upd = $('#id').val();
    if (upd) {
        editing = true;

        $.ajax({
            url: 'controller/QuotationController.php',
            method: 'POST',
            data: { id: upd, action: 'Select' },
            dataType: 'json',
            success: function (data) {
                if (data) {
                    $('#customer_id').val(data.customer_id).trigger('change');
                    $('#inquiry_id').val(data.inquiry_id);
                    $('#package_name').val(data.package_name);
                    $('#destination').val(data.destination);
                    $('#travel_date').val(data.travel_date);
					$('#rooms').val(data.rooms);
                    $('#nights').val(data.nights);
                    $('#adults').val(data.adults);
                    $('#child').val(data.child);
                    $('#extrabed').val(data.extrabed);
                    $('#adult_price').val(data.adult_price);
                    $('#child_price').val(data.child_price);
                    $('#extra_bed_price').val(data.extra_bed_price);
                    $('#transport_type').val(data.transport_type);
                    $('#transport_charges').val(data.transport_charges);
                    $('#gst_included').val(data.gst_included);
                    $('#gst').val(data.gst_rate);
                    $('#discount').val(data.discount);
                    $('#grand_total').val(data.grand_total);

                    if (data.remarks) {
                        editorDescription.root.innerHTML = data.remarks;
                    }
					if (data.inclusions) {
                        editorInclusions.root.innerHTML = data.inclusions;
                    }
					if (data.exclusions) {
                        editorExclusions.root.innerHTML = data.exclusions;
                    }

                    $('#hotelRepeater').empty();
                    if (Array.isArray(data.hotels)) {
                        data.hotels.forEach((hotel, index) => {
                            const block = $('#hotelTemplate .hotelBlock').first().clone().removeClass('d-none');
                            block.find('[data-name="hotel_name"]').val(hotel.hotel_name);
                            block.find('[data-name="hotel_location"]').val(hotel.hotel_location);
                            block.find('[data-name="hotel_rooms"]').val(hotel.hotel_rooms);
                            block.find('[data-name="hotel_type"]').val(hotel.hotel_type);
                            block.find('[data-name="meal_plan"]').val(hotel.meal_plan);
                            $('#hotelRepeater').append(block);
                        });
                        updateHotelBlockIndexes();
                    }

                    calculateTotalAmount();
                }
                editing = false;
            },
            error: function (xhr, status, error) {
                console.error("Fetch error:", status, error, xhr.responseText);
                toastr.error('Error loading quotation data.');
            }
        });
    }
});
</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');?>