<?php $__env->startSection('title', 'Nerve Tech Client Management System'); ?>

<?php $__env->startSection('content'); ?>  

  <div class="modal fade" id="addPackage" tabindex="-1" role="dialog" aria-labelledby="addClientModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="addPackageModalLabel">Add Plan</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
        <form id="addPackageForm">
            <div class="form-group">
              <label for="accountBalance">Plan</label>
              <input type="text" class="form-control" id="accountBalance" name="accountBalance">
            </div>
            <div class="form-group">
              <label for="firstName">Price</label>
              <input type="number" class="form-control" id="firstName" name="firstName">
            </div>
            <!-- Add more form fields here -->
            
            <div class="form-group">
              <label for="plan">Plan Type</label>
              <select class="form-control" id="plan" name="plan">
                <option disabled selected>--Select--</option>
                <option>Data Package</option>
                <option>Unlimited Package</option>
                <!-- Add more options here -->
              </select>
            </div>
            
            <!-- <button type="submit" class="btn btn-primary">Submit</button> -->

            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
              <button type="submit" class="btn btn-primary" id="addPlanSubmit">Submit</button>
            </div>
          </form>
        </div>
        
      </div>
    </div>
  </div>

    <!-- Add this outside your table -->
  <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
          <div class="modal-content">
              <div class="modal-header">
                  <h5 class="modal-title" id="editModalLabel">Edit Plan</h5>
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                      <span aria-hidden="true">&times;</span>
                  </button>
              </div>
              <div class="modal-body">
                <form method="POST" action="" id="editForm">
                  <div class="form-group">
                    <label for="edit-dataPackage">Plan</label>
                    <input type="text" class="form-control" id="edit-dataPackage" name="dataPackage">
                  </div>
                  <div class="form-group">
                    <label for="edit-price">Price</label>
                    <input type="number" class="form-control" id="edit-price" name="price">
                  </div>
                  <!-- Add more form fields here -->
                  
                  <div class="form-group">
                    <label for="edit-plan">Plan Type</label>
                    <select class="form-control" id="edit-plan" name="plan">
                        <option disabled selected>--Select--</option>
                        <option>Data Package</option>
                        <option>Unlimited Package</option>
                      <!-- Add more options here -->
                    </select>
                  </div>
                  
                  <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="updateClient" class="btn btn-primary">Submit</button>
                  </div>
                </form>
            </div>
      </div>
          </div>
      </div>
  </div>

   <!--  Body Wrapper -->
  <div class="page-wrapper" id="main-wrapper" data-layout="vertical" data-navbarbg="skin6" data-sidebartype="full"
      data-sidebar-position="fixed" data-header-position="fixed">
      <!-- Sidebar Start -->
     
      <!--  Sidebar End -->
      <!--  Main wrapper -->
      <div class="body-wrapper">
        <!--  Header Start -->
        
        <!--  Header End -->
        <div class="container-fluid">
          <!--  Row 1 -->
          <div class="row">
            <div class="col-lg-12 d-flex align-items-strech">
              <div class="card w-100">
                <div class="card-body">
                  <div class="d-sm-flex d-block align-items-center justify-content-between mb-9">
                    <div class="mb-3 mb-sm-0">
                      <h5 class="card-title fw-semibold">Plans</h5>
                    </div>
                    <div>
                      <!-- Button trigger modal -->
                      <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addPackage">
                        Add Plan
                      </button>
                      <button class="btn btn-primary" id="deleteSelected" type="button">Delete Selected</button>
                    </div>
                  <!-- <div id="chart"></div> -->
                </div>
              </div>
            </div>

            
          </div>

          <div class="row">
            <div class="col-lg-12 d-flex align-items-stretch">
              <div class="card w-100">
                <div class="card-body p-4">
                  <h5 class="card-title fw-semibold mb-4">Plans</h5>
                  <div class="table-responsive">
                    <table class="table text-nowrap mb-0 align-middle">
                      <thead class="text-dark fs-4">
                        <tr>
                          <th class="border-bottom-0">
                              <input type="checkbox" id="selectAll">
                          </th>
                          <th class="border-bottom-0">
                            <h6 class="fw-semibold mb-0">Id</h6>
                          </th>
                          <th class="border-bottom-0">
                            <h6 class="fw-semibold mb-0">Plan</h6>
                          </th>
                          <th class="border-bottom-0">
                            <h6 class="fw-semibold mb-0">Plan Type</h6>
                          </th>
                    
                          <th class="border-bottom-0">
                            <h6 class="fw-semibold mb-0">Action</h6>
                          </th>

                        </tr>
                      </thead>
                      <tbody>
                        <?php $__currentLoopData = $packages; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $package): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                          <tr>
                             <td class="border-bottom-0">
                                <input type="checkbox" class="selectPackage" value="<?php echo e($package->id); ?>">
                            </td>
                            <td class="border-bottom-0"><h6 class="fw-semibold mb-0"><?php echo e($loop->iteration); ?></h6></td>
                            <td class="border-bottom-0">
                              <h6 class="fw-semibold mb-1"><?php echo e($package->data_package); ?></h6>
                              <span class="fw-normal">GHC<?php echo e($package->price); ?></span>                          
                            </td>

                            <td class="border-bottom-0">
                              <p class="mb-0 fw-normal"><?php echo e($package->package_type); ?></p>
                            </td>
                           
                            <td class="border-bottom-0">
                              <h6 class="fw-semibold mb-0 fs-4">
                                <div class="dropdown">
                                  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    Select Action
                                  </button>
                                  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                                     <button type="button" class="dropdown-item edit-button" data-toggle="modal" data-target="#editModal" data-id="<?php echo e($package->id); ?>"  data-url="<?php echo e(url('/packages')); ?>">
                                      Edit
                                    </button>

                                     <button type="button" class="dropdown-item remove-button" data-toggle="modal" data-target="#removeModal" data-id="<?php echo e($package->id); ?>"  data-url="<?php echo e(url('/packages')); ?>">
                                      Remove
                                    </button>

                                  </div>
                                </div>
                              </h6>
                            </td>
                          </tr>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                      </tbody>
                    </table>
                  </div>

                  <div class="d-flex align-items-center justify-content-end">
                    <nav aria-label="Page navigation example">
                      <ul class="pagination">
                        <li class="page-item" style="cursor: pointer;"><a class="page-link" onclick="previousPage()">Previous</a></li>
                        <li class="page-item"><a class="page-link" href="#" disabled="true"><?php echo e($page_number); ?> of <?php echo e($total_pages); ?> </a></li>
                        <li class="page-item" style="cursor: pointer;"><a class="page-link" onclick="nextPage()">Next</a></li>
                      </ul>
                    </nav> 
                  </div>

                </div>
              </div>
            </div>
          </div> 

          
        </div>
      </div>
    </div>

<?php $__env->stopSection(); ?>

<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>

<script>
  
  page_number = 1;

  $(document).ready(function() {

    page_number = <?php echo $page_number; ?>;

    $('#addPackageForm').on('submit', function(e) {
      e.preventDefault();

      var dataPackage = $('#accountBalance').val();
      var price = $('#firstName').val();
      var packageType = $('#plan').val();

      // Disable the submit button
      $('#addPlanSubmit').prop('disabled', true);

      $.ajax({
          url: `<?php echo e(url('/add-package')); ?>`, // replace with your endpoint
          type: 'POST',
          data: {
              dataPackage: dataPackage,
              price: price,
              packageType: packageType,
              _token: $('meta[name="csrf-token"]').attr('content')
          },
          success: function(response) {
              // Handle success here
              $('#addPackage').modal('hide');
              Swal.fire(
                  'Success!',
                  'Your form has been submitted.',
                  'success'
              ).then((result) => {
                  // Reload the page when the dialog is dismissed
                  if (result.isConfirmed || result.isDismissed) {
                      location.reload();
                  }
              });

              // Enable the submit button
              $('#addPlanSubmit').prop('disabled', false);
          },
          error: function(err) {
              // Handle error here
              var errorMessage = err.responseJSON.error || 'Something went wrong!';
              Swal.fire({
                  icon: 'error',
                  title: 'Oops...',
                  text: errorMessage,
                  footer: '<a href>Why do I have this issue?</a>'
              });

              // Enable the submit button
              $('#addPlanSubmit').prop('disabled', false);
          }
      });
    });

    
    $('.edit-button').on('click', function() {
        var id = $(this).data('id');
        // var url = $(this).data('url');
        $.ajax({
          url: `<?php echo e(url('/packages')); ?>/` + id + '/edit',
          type: 'GET',
          success: function(package) {
            //console.log(package);
            // $('#editForm').attr('action', `${url}/${package.id}`);
            $('#editForm').data('id', package.id);         
            $('#edit-dataPackage').val(package.data_package);
            $('#edit-price').val(package.price);
            if (package.package_type) {
                $('#edit-plan').val(package.package_type);
            }            // $('#edit-email').val(client.email);
            // $('#edit-plan').val(client.plan);
            // $('#edit-gps').val(client.gps);
            // $('#edit-expiryDate').val(client.expiry_date);
          },
          error: function(jqXHR, textStatus, errorThrown) {
            //console.log(textStatus, errorThrown);
          }
        });
    });

    $('#editForm').on('submit', function(e) {
      e.preventDefault();

      var csrfToken = $('meta[name="csrf-token"]').attr('content');

      var id = $(this).data('id');
      // var url = $(this).attr('action');
      var data = $(this).serialize();

      data += '&_token=' + csrfToken;

      // console.log(data);
      // return;

      // console.log(`<?php echo e(url('/clients')); ?>/` + id);

      $.ajax({
        url: `<?php echo e(url('/packages')); ?>/` + id,
        type: 'post',
        data: data,
        success: function(response) {
          // Handle success here, for example by updating the table or showing a success message
          // console.log(response);
          //add sweet alert here
          
          Swal.fire(
            'Success!',
            'Your form has been submitted.',
            'success'
          ).then((result) => {
            // Reload the page when the dialog is dismissed
            if (result.isConfirmed || result.isDismissed) {
              location.reload();
            }
          });
        },
        error: function(jqXHR, textStatus, errorThrown) {
          console.log(textStatus, errorThrown);
        }
      });
    });

    $('#selectAll').on('click', function() {
          $('.selectPackage').prop('checked', $(this).prop('checked'));
    });

    $('#deleteSelected').on('click', function() {
          var selectedPackages = $('.selectPackage:checked').map(function() {
              return $(this).val();
          }).get();

          Swal.fire({
              title: 'Are you sure?',
              text: "You won't be able to revert this!",
              icon: 'warning',
              showCancelButton: true,
              confirmButtonColor: '#3085d6',
              cancelButtonColor: '#d33',
              confirmButtonText: 'Yes, delete it!'
          }).then((result) => {
              if (result.isConfirmed) {
                  $.ajax({
                      url: `<?php echo e(url('/delete-packages')); ?>`,
                      type: 'DELETE',
                      data: {
                          packages: selectedPackages,
                          _token: $('meta[name="csrf-token"]').attr('content')
                      },
                      success: function(response) {
                          Swal.fire(
                              'Deleted!',
                              'Your file has been deleted.',
                              'success'
                          ).then((result) => {
                              location.reload();
                          });
                      },
                      error: function(err) {
                          Swal.fire({
                              icon: 'error',
                              title: 'Oops...',
                              text: 'Something went wrong!',
                              footer: '<a href>Why do I have this issue?</a>'
                          });
                      }
                  });
              }
          });
      });
  });

  function previousPage() {
    if (page_number > 1) {
      page_number--;
      window.location = `<?php echo e(url('/packages/${page_number}')); ?>`;
    }
  }

  function nextPage() {
    let total_pages = <?php echo json_encode($total_pages); ?>;
    if (total_pages > page_number) {
      page_number++;
      window.location = `<?php echo e(url('/packages/${page_number}')); ?>`;
    }
  }
</script>


<?php echo $__env->make('layouts.main', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>