<?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 active">Packages Inclusions</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 Packages Inclusions
    </button>
-->
    <div class="row mb-4">
                <!--  Modal -->
        <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="inclusionsForm">
                        <div class="modal-header">
                            <h5 class="modal-title" id="basicModalLabel">Packages Inclusions</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            

                            <!-- Name -->
                            <div class="row">
                                <div class="col-md-12">
								  <label class="form-label">Packages Inclusions</label>
								  <div id="editor_inclusions" class="quill-editor"></div>
								  <input type="hidden" name="inclusions" id="incl_input">
								</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>

        <!-- Users Table -->
        <div class="col-xl-12 col-lg-6 col-md-6">
            <div class="card">
                <div class="card-datatable table-responsive pt-0">
                    <table class="datatables-ajax table table-bordered table-responsive">
                        <thead>
                            <tr>
                                <th>Packages Inclusions</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $result = mysqli_query($conn, "SELECT * FROM packages_inclusions ORDER BY id ASC");
                            while ($row = mysqli_fetch_array($result)) {
                            ?>
                            <tr class="showtr">
                                <td><?php echo $row['inclusions']; ?></td>
                                
                                <td>
                                    <label class="switch">
                                        <input type="checkbox" class="switch-input" value="<?php echo $row[0]; ?>"
                                               <?php if ($row['status'] == 'active') echo "checked"; ?>
                                               onClick="statusChange(this.value);" />
                                        <span class="switch-toggle-slider">
                                            <span class="switch-on"></span>
                                            <span class="switch-off"></span>
                                        </span>
                                    </label>
                                </td>
                                <td>
									
									<button type="button" id="<?php echo $row[0]; ?>" class="btn btn-xs btn-warning update"><i class="far fa-edit"></i></button>
                   				 <button type="button" id="<?php echo $row[0]; ?>" class="btn btn-xs btn-danger delete"><i class="far fa-trash-alt"></i></button>
                                   
                                </td>
                            </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="assets/vendor/libs/quill/quill.js"></script>
<script>
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 editorInclusions = new Quill('#editor_inclusions', {
  bounds: '#editor_inclusions',
  placeholder: 'Type Inclusions...',
  modules: { toolbar: fullToolbar },
  theme: 'snow'
});

$(document).ready(function () {
  // Open modal for Create
  $('#modal_button').click(function () {
    $('#inclusionsForm')[0].reset();
    editorInclusions.root.innerHTML = '';
    $('#action').val('Create');
    $('#id').val('');
    $('.modal-title').text("Add Inclusions");
    $('#basicModal').modal('show');
  });

  // Update
$(document).on('click', '.update', function () {
  const id = $(this).attr("id");
  console.log("Edit clicked, ID:", id); // ✅ Check if this logs

  $.ajax({
    url: "controller/PackagesInclusionsController.php",
    method: "POST",
    data: { id: id, action: 'Select' },
    dataType: "json",
    success: function (res) {
      console.log("AJAX response:", res); // ✅ Log response
      
      if (res.status === 'success') {
        editorInclusions.root.innerHTML = res.data.inclusions;
        $('#id').val(res.data.id);
        $('#action').val('Update');
        $('.modal-title').text("Update Inclusions");

        const modal = new bootstrap.Modal(document.getElementById('basicModal'));
        modal.show();
      } else {
        toastr.error(res.message || 'Unknown error');
      }
    },
    error: function (xhr, status, error) {
      console.error("AJAX Error:", error);
      toastr.error("AJAX failed: " + error);
    }
  });
});


  // Submit (Create or Update)
  $('#inclusionsForm').submit(function (e) {
    e.preventDefault();
    $('#incl_input').val(editorInclusions.root.innerHTML);

    $.ajax({
      url: "controller/PackagesInclusionsController.php",
      method: "POST",
      data: $(this).serialize(),
      dataType: "json",
      success: function (res) {
        if (res.status === 'success') {
          $('#basicModal').modal('hide');
          toastr.success(res.message);
                  setTimeout(function() {
          location.reload(); // This will reload the page
        }, 3000); // 3-second delay before refreshing the page

        } else {
          toastr.error(res.message);
        }
      },
      error: function () {
        toastr.error("Server error occurred.");
      }
    });
  });

  // Delete
$(document).on('click', '.delete', function () {
  const id = $(this).attr("id");
  const row = $(this).closest('tr'); // Get the table row

  if (confirm("Delete this inclusion?")) {
    $.ajax({
      url: "controller/PackagesInclusionsController.php",
      method: "POST",
      data: { id: id, action: 'Delete' },
      dataType: "json",
      success: function (res) {
        if (res.status === 'success') {
          toastr.success(res.message);
          row.css('background-color', '#f8d7da').fadeOut(800, function () {
            $(this).remove(); // Remove the row after fade out
          });
        } else {
          toastr.error(res.message);
        }
      },
      error: function () {
        toastr.error('Error while deleting the inclusion.');
      }
    });
  }
});

window.statusChange = function (id) {
        $.ajax({
            url: 'controller/PackagesInclusionsController.php',
            method: 'POST',
            data: { id: id, action: 'ToggleStatus' },
            dataType: "json",
            success: function (response) {
                if (response.status === 'success') {
                    const newStatus = response.new_status === "active" ? "Active" : "Inactive";
                    toastr.success(`Status changed to ${newStatus}`);
                } else {
                    toastr.error(response.message);
                }
            },
            error: function () {
                toastr.error('Failed to update status.');
            }
        });
    };
});

  
</script>
<?php include('inc/footer.php');?>