@extends('layouts.main')

@section('title', 'Nerve Tech Client Management System')

@section('content')  

  <div class="modal fade" id="addClientModal" 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="addClientModalLabel">Add Client</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="addClientForm">
            {{-- <div class="form-group">
              <label for="accountBalance">Account Balance (GHS)</label>
              <input type="number" class="form-control" id="accountBalance" name="accountBalance">
            </div> --}}
            {{-- <div class="form-group">
              <label for="firstName">First Name</label>
              <input type="text" class="form-control" id="firstName" name="firstName">
            </div>
            <div class="form-group">
              <label for="lastName">Last Name</label>
              <input type="text" class="form-control" id="lastName" name="lastName">
            </div> --}}
            <div class="form-group">
              <label for="accountUsername">Name</label>
              <input type="text" class="form-control" id="accountUsername" name="accountUsername">
            </div>

            <div class="form-group">
              <label for="username">Username</label>
              <input type="text" class="form-control" id="username" name="username">
            </div>

            <div class="form-group">
              <label for="clientId">Client Id</label>
              <input type="text" class="form-control" id="clientId" name="clientId">
            </div>
            
            <div class="form-group">
              <label for="phoneNumber">Phone Number</label>
              <input type="text" class="form-control" id="phoneNumber" name="phoneNumber">
            </div>
            <!-- Add more form fields here -->
            <div class="form-group">
              <label for="email">Email Address</label>
              <input type="text" class="form-control" id="email" name="email">
            </div>
            <div class="form-group">
              <label for="gps">GPS (Ghana Post Number)</label>
              <input type="text" class="form-control" id="gps" name="gps">
            </div>
            {{-- <div class="form-group">
              <label for="plan">Plan (Internet Package)</label>
              <select class="form-control" id="plan" name="plan">
                <option>Plan 1</option>
                <option>Plan 2</option>
                <!-- Add more options here -->
              </select>
            </div> --}}
            <div class="form-group">
                <label for="plan">Plan (Internet Package)</label>
                <select class="form-control" id="plan" name="plan">
                    <option selected disabled> -- Select -- </option>
                    @foreach($packages as $plan)
                        <option value="{{ $plan->id }}">{{ $plan->data_package }}(GHC{{ $plan->price}})</option>
                    @endforeach
                </select>
            </div>

            <div class="form-group">
              <label for="node">Node</label>
              <select class="form-control" id="node" name="node">
                @foreach($nodes as $node)
                  <option value="{{ $node->node_uuid }}">{{ $node->node_name }}</option>
                @endforeach
              </select>
            </div>

            <div class="form-group">
              <label for="expiryDate">Expiry Date</label>
              <input type="date" class="form-control" id="expiryDate" name="expiryDate">
            </div>

            <div class="form-group">
              <label for="referalBonus">Referal Bonus</label>
              <input type="text" class="form-control" id="referalBonus" name="referalBonus">
            </div>

            <div class="form-group">
              <label for="installationType">Installation Type</label>
              <input type="text" class="form-control" id="installationType" name="installationType">
            </div>

            <div class="form-group">
              <label for="status">Status</label>
              <select class="form-control" id="status" name="status">
                  <option selected disabled>--Select--</option>
                  <option value="Active">Active</option>
                  <option value="Expired">Expired</option>
              </select>
            </div>

            <div class="form-group">
              <label for="cpeOutdoor">CPE-OUTDOOR</label>
              <input type="text" class="form-control" id="cpeOutdoor" name="cpeOutdoor">
            </div>

            <div class="form-group">
              <label for="cpeIndoor">CPE-INDOOR</label>
              <input type="text" class="form-control" id="cpeIndoor" name="cpeIndoor">
            </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="addClientSubmit">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 Client</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-accountBalance">Account Balance (GHS)</label>
                        <input type="number" class="form-control" id="edit-accountBalance" name="accountBalance">
                    </div> --}}
                    {{-- <div class="form-group">
                        <label for="edit-firstName">First Name</label>
                        <input type="text" class="form-control" id="edit-firstName" name="firstName">
                    </div>
                    <div class="form-group">
                        <label for="edit-lastName">Last Name</label>
                        <input type="text" class="form-control" id="edit-lastName" name="lastName">
                    </div> --}}

                    <div class="form-group">
                        <label for="edit-accountUsername">Name</label>
                        <input type="text" class="form-control" id="edit-accountUsername" name="accountUsername">
                    </div>

                    <div class="form-group">
                        <label for="edit-username">Username</label>
                        <input type="text" class="form-control" id="edit-username" name="username">
                    </div>

                    <div class="form-group">
                        <label for="edit-clientId">Client Id</label>
                        <input type="text" class="form-control" id="edit-clientId" name="clientId">
                    </div>

                    <!-- Wallet -->
                    <div class="form-group">
                        <label for="edit-wallet">Wallet</label>
                        <input type="number" class="form-control" id="edit-wallet" name="wallet">
                    </div>  
                    
                    <div class="form-group">
                        <label for="edit-phoneNumber">Phone Number</label>
                        <input type="text" class="form-control" id="edit-phoneNumber" name="phoneNumber">
                    </div>
                    <div class="form-group">
                        <label for="edit-email">Email Address</label>
                        <input type="text" class="form-control" id="edit-email" name="email">
                    </div>
                    <div class="form-group">
                        <label for="edit-gps">GPS (Ghana Post Number)</label>
                        <input type="text" class="form-control" id="edit-gps" name="gps">
                    </div>
                    <div class="form-group">
                        <label for="edit-plan">Plan (Internet Package)</label>
                        <select class="form-control" id="edit-plan" name="plan">
                            <option selected disabled> -- Select -- </option>
                            @foreach($packages as $plan)
                                <option value="{{ $plan->id }}">{{ $plan->data_package }}(GHC{{ $plan->price}})</option>
                            @endforeach
                        </select>
                    </div>
                   <div class="form-group">
                    <label for="edit-node">Node</label>
                    <select class="form-select" id="edit-node" name="edit-node">
                      @foreach($nodes as $node)
                        <option value="{{ $node->node_uuid }}" >{{ $node->node_name }}</option>
                      @endforeach
                    </select>
                  </div>
                    <div class="form-group">
                        <label for="edit-expiryDate">Expiry Date</label>
                        <input type="date" class="form-control" id="edit-expiryDate" name="expiryDate">
                    </div>
                    <div class="form-group">
                        <label for="edit-referalBonus">Referal Bonus</label>
                        <input type="text" class="form-control" id="edit-referalBonus" name="referalBonus">
                    </div>

                    <div class="form-group">
                        <label for="edit-installationType">Installation Type</label>
                        <input type="text" class="form-control" id="edit-installationType" name="installationType">
                    </div>

                    {{-- <div class="form-group">
                        <label for="edit-status">Status</label>
                        <input type="text" class="form-control" id="edit-status" name="status">
                    </div> --}}

                    <div class="form-group">
                      <label for="edit-status">Status</label>
                      <select class="form-control" id="edit-status" name="status">
                          <option selected disabled>--Select--</option>
                          <option value="Active">Active</option>
                          <option value="Expired">Expired</option>
                      </select>
                    </div>

                    <div class="form-group">
                        <label for="edit-cpeOutdoor">CPE OUTDOOR</label>
                        <input type="text" class="form-control" id="edit-cpeOutdoor" name="cpeOutdoor">
                    </div>

                     <div class="form-group">
                        <label for="edit-cpeIndoor">CPE INDOOR</label>
                        <input type="text" class="form-control" id="edit-cpeIndoor" name="cpeIndoor">
                    </div>                    
                    
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">Submit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
  </div>

  <div class="modal fade" id="renewModal" tabindex="-1" role="dialog" aria-labelledby="renewModalLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="renewModalLabel">Renew Client</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="renewForm">
              {{-- <div class="form-group">
                <label for="renew-client">Client</label>
                <input type="number" class="form-control" id="renew-client" name="client">
              </div> --}}
              {{-- <div class="form-group">
                <label for="renew-package">Package</label>
                <input type="text" class="form-control" id="renew-package" name="package">
              </div> --}}

                <div class="form-group">
                      <label for="renew-package">Plan (Internet Package)</label>
                      <select class="form-control" id="renew-package" name="package" required>
                          <option selected disabled> -- Select -- </option>
                          @foreach($packages as $plan)
                              <option value="{{ $plan->id }}">{{ $plan->data_package }}(GHC{{ $plan->price}})</option>
                          @endforeach
                      </select>
                  </div>

                  <div class="form-group">
                    <label for="renew-type">Renew Type</label>
                    <select class="form-control" id="renew-type" name="renew_type" required>
                      <option selected disabled> -- Select -- </option>
                      <option value="renew_with_payment">Renew with Payment</option>
                      <option value="renew_without_payment">Renew without Payment</option>
                    </select>
                  </div>

              {{-- <div class="form-group">
                <label for="renew-date">Renew Date</label>
                <input type="date" class="form-control" id="renew-date" name="renewDate">
              </div> --}}

              {{-- <div class="form-group">
                <label for="renew-expiry">Expiry Date</label>
                <input type="date" class="form-control" id="renew-expiry" name="expiryDate">
              </div> --}}

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

  <div class="modal fade" id="receiptsModal" tabindex="-1" role="dialog" aria-labelledby="receiptsModalLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
          <div class="modal-content">
              <div class="modal-header">
                  <h5 class="modal-title" id="receiptsModalLabel">Receipts</h5>
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                      <span aria-hidden="true">&times;</span>
                  </button>
              </div>
                  <div class="modal-body">
                      {{-- <h5>Client Receipts</h5> --}}
                      <table class="table">
                          <thead>
                              <tr>
                                  <th>Receipt Date</th>
                                  <th>Plan (Internet Package)</th>
                                  <th>Expiry Date</th>
                                  <th>Action</th>
                              </tr>
                          </thead>
                          <tbody id="receiptsTableBody">
                              
                          </tbody>
                      </table>

                      {{-- <form method="POST" action="" id="receiptsForm">
                          <div class="form-group">
                              <label for="receipts-package">Plan (Internet Package)</label>
                              <select class="form-control" id="receipts-package" name="package">
                                  <option selected disabled> -- Select -- </option>
                                  @foreach($packages as $plan)
                                      <option value="{{ $plan->id }}">{{ $plan->data_package }} (GHC{{ $plan->price }})</option>
                                  @endforeach
                              </select>
                          </div>
                          <div class="form-group">
                              <label for="receipts-date">Receipt Date</label>
                              <input type="date" class="form-control" id="receipts-date" name="receiptDate">
                          </div>
                          <div class="form-group">
                              <label for="receipts-expiry">Expiry Date</label>
                              <input type="date" class="form-control" id="receipts-expiry" name="expiryDate">
                          </div>
                          <div class="modal-footer">
                              <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                              <button type="submit" class="btn btn-primary">Submit</button>
                          </div>
                      </form> --}}
                  </div>

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

  <div class="modal fade" id="viewClientModal" tabindex="-1" role="dialog" aria-labelledby="viewClientModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="viewClientModalLabel">Client Details</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <!-- Display client details here -->

                 {{-- <form id="addClientForm"> --}}
                {{-- <div class="form-group">
                  <label for="accountBalance">Account Balance (GHS)</label>
                  <input type="number" class="form-control" id="view-accountBalance" name="accountBalance" disabled>
                </div> --}}
                {{-- <div class="form-group">
                  <label for="firstName">First Name</label>
                  <input type="text" class="form-control" id="view-firstName" name="firstName" disabled>
                </div> --}}
                {{-- <div class="form-group">
                  <label for="lastName">Last Name</label>
                  <input type="text" class="form-control" id="view-lastName" name="lastName" disabled>
                </div> --}}
                <div class="form-group">
                  <label for="accountUsername">Name</label>
                  <input type="text" class="form-control" id="view-accountUsername" name="accountUsername" disabled>
                </div>

                <div class="form-group">
                  <label for="username">Username</label>
                  <input type="text" class="form-control" id="view-username" name="username" disabled>
                </div>

                <div class="form-group">
                  <label for="clientId">Client ID</label>
                  <input type="text" class="form-control" id="view-clientId" name="clientId" disabled>
                </div>

                <div class="form-group">
                  <label for="wallet">Wallet</label>
                  <input type="text" class="form-control" id="view-wallet" name="wallet" disabled>
                </div>
                
                <div class="form-group">
                  <label for="phoneNumber">Phone Number</label>
                  <input type="text" class="form-control" id="view-phoneNumber" name="phoneNumber" disabled>
                </div>
                <!-- Add more form fields here -->
                <div class="form-group">
                  <label for="email">Email Address</label>
                  <input type="email" class="form-control" id="view-email" name="email" disabled>
                </div>
                <div class="form-group">
                  <label for="gps">GPS (Ghana Post Number)</label>
                  <input type="text" class="form-control" id="view-gps" name="gps" disabled>
                </div>
                
                <div class="form-group">
                    <label for="plan">Plan (Internet Package)</label>
                    <select class="form-control" id="view-plan" name="plan" disabled>
                        <option selected disabled> -- Select -- </option>
                        @foreach($packages as $plan)
                            <option value="{{ $plan->id }}">{{ $plan->data_package }}(GHC{{ $plan->price}})</option>
                        @endforeach
                    </select>
                </div>

                <div class="form-group">
                  <label for="node">Node</label>
                  <input type="text" class="form-control" id="view-node" name="node" disabled>
                </div>

                <div class="form-group">
                  <label for="expiryDate">Expiry Date</label>
                  <input type="text" class="form-control" id="view-expiryDate" name="expiryDate" disabled>
                </div>

                <div class="form-group">
                  <label for="referalBonus">Referal Bonus</label>
                  <input type="text" class="form-control" id="view-referalBonus" name="referalBonus" disabled>
                </div>

                <div class="form-group">
                  <label for="installationType">Installation Type</label>
                  <input type="text" class="form-control" id="view-installationType" name="installationType" disabled>
                </div>

                 <div class="form-group">
                  <label for="status">Status</label>
                  <input type="text" class="form-control" id="view-status" name="status" disabled>
                </div>

                 <div class="form-group">
                  <label for="cpeOutdoor">CPE OUTDOOR</label>
                  <input type="text" class="form-control" id="view-cpeOutdoor" name="cpeOutdoor" disabled>
                </div>

                 <div class="form-group">
                  <label for="cpeIndoor">CPE INDOOR</label>
                  <input type="text" class="form-control" id="view-cpeIndoor" name="cpeIndoor" disabled>
                </div>
               
              {{-- </form> --}}
            </div>
            
        </div>
    </div>
  </div>

  <!-- Make Payment Modal -->
  <div class="modal fade" id="makePaymentModal" tabindex="-1" role="dialog" aria-labelledby="makePaymentLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
          <div class="modal-content">
              <div class="modal-header">
                  <h5 class="modal-title" id="makePaymentLabel">Make Payment</h5>
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                      <span aria-hidden="true">&times;</span>
                  </button>
              </div>
              <form action="" method="POST">
                  <div class="modal-body">
                      <input type="hidden" name="client_id" id="client_id">
                       <div class="form-group">
                          <label for="amount">Wallet Balance</label>
                          <input type="text" class="form-control" id="wallet_balance" name="amount" step="0.01" disabled>
                       </div>
                       <div class="form-group" >
                          <label for="amount">Payment Type</label>
                          <select class="form-select" id="payment_type" name="payment_type">
                              <option selected disabled>--Select--</option>
                              <option value="early_payment">Early Payment</option>
                              <option value="late_payment">Late Payment</option>
                          </select>
                        </div>
                        <!-- Plan (Internet Package) -->
                        <div class="form-group" id="internet_package">
                            <label for="renew-package">Plan (Internet Package)</label>
                            <select class="form-select"  id="renew_package" name="package">
                                <option selected disabled> -- Select -- </option>
                                @foreach($packages as $plan)
                                    <option value="{{ $plan->id .'-'.$plan->price }}">{{ $plan->data_package }}(GHC{{ $plan->price}})</option>
                                @endforeach
                            </select>
                        </div>

                        <div class="form-group" id="payment_amount">
                            <label for="amount">Amount</label>
                            <input type="number" class="form-control" id="amount" name="amount" step="0.01" required>
                        </div>
                  </div>
                  <div class="modal-footer">
                      <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                      <button type="submit" class="btn btn-primary">Make Payment</button>
                  </div>
              </form>
          </div>
      </div>
  </div>

  <!-- Send SMS Modal -->
  <div class="modal fade" id="sendSmsModal" tabindex="-1" role="dialog" aria-labelledby="sendSmsLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
          <div class="modal-content">
              <div class="modal-header">
                  <h5 class="modal-title" id="sendSmsLabel">Send SMS</h5>
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                      <span aria-hidden="true">&times;</span>
                  </button>
              </div>
              <form action="" method="POST">
                  <div class="modal-body">
                                  <!-- Default sms -->
                      <div class="form-group">
                        <label for="default-sms">Default Message</label>
                        <select class="form-select" id="default-sms" name="default_sms">
                          <option selected disabled>--Select--</option>
                          @foreach($sms as $key=> $smsMessage)
                            <option data-sms_content="{{ $smsMessage->sms_content }}" value="{{ $smsMessage->id }}">{{ $smsMessage->sms_type }}</option>
                          @endforeach
                        </select>
                      </div>    
                      {{-- <input type="hidden" name="client_id" id="sms_client_id"> --}}
                      <div class="form-group">
                          <label for="sms_message">Message</label>
                          <textarea class="form-control" id="sms_message" name="sms_message" rows="3" required></textarea>
                      </div>
                  </div>
                  <div class="modal-footer">
                      <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                      <button type="submit" class="btn btn-primary">Send SMS</button>
                  </div>
              </form>
          </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">
    
      <!--  Main wrapper -->
      <div class="" style="padding-top: calc(70px + 15px)">
        
       
        <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">Manage Client</h5>
                    </div>
                    <div>

                      <!-- Button trigger modal -->
                      <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addClientModal">
                        Add Client
                      </button>

                      <input type="file" id="excelFile" accept=".csv" style="display: none;" />
                      <a class="btn btn-primary" onclick="uploadFile();">Import Client</a>

                      <a class="btn btn-primary" href="{{ url('/export-clients') }}">Export Client</a>

                      {{-- <a class="btn btn-primary" href="{{ url('/default-renewal') }}">Default Renewal</a> --}}

                      <button id="deleteSelected" class="btn btn-primary" type="button">Delete Selected</button>

                      </div>
                  </div>
                  <!-- <div id="chart"></div> -->
                </div>
              </div>
            </div>

            <div class="col-lg-12">
              <div class="row">
                <div class="col-lg-12">
                  
                </div>
                <div class="col-lg-12">
                  
                </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">
                  <div class="row">
                    <div class="col-md-6">
                      <h5 class="card-title fw-semibold mb-4">Clients</h5>
                    </div>
                    <div class="col-md-6 d-flex justify-content-end">
                      <form id="searchForm" class="mb-3">
                        <div class="input-group">
                          <input type="text" name="search" class="form-control" placeholder="Search clients" value="{{ request()->get('search') }}">
                          <button  class="btn btn-primary">Search</button>
                        </div>
                      </form>
                    </div>
                  </div>

                  <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">Name</h6>
                          </th>
                          {{-- <th class="border-bottom-0">
                            <h6 class="fw-semibold mb-0">GPS</h6>
                          </th>
                          <th class="border-bottom-0">
                            <h6 class="fw-semibold mb-0">Email</h6>
                          </th> --}}
                          <th class="border-bottom-0">
                            <h6 class="fw-semibold mb-0">Expiry Date</h6>
                          </th>

                          <th class="border-bottom-0">
                            <h6 class="fw-semibold mb-0">Status</h6>
                          </th>

                          <th class="border-bottom-0">
                            <h6 class="fw-semibold mb-0">Action</h6>
                          </th>

                        </tr>
                      </thead>
                      <tbody>
                        @foreach ($clients as $key => $client)
                          <tr>
                            <td class="border-bottom-0">
                                    <input type="checkbox" class="selectClient" value="{{ $client->id }}">
                            </td>
                            <td class="border-bottom-0"><h6 class="fw-semibold mb-0">{{ $loop->iteration }}</h6></td>
                            <td class="border-bottom-0">
                              <h6 class="fw-semibold mb-1">{{ $client->account_username }}</h6>
                              <span class="fw-normal">{{ $client->data_package }}</span>                          
                            </td>

                            <td class="border-bottom-0">
                              <h6 class="fw-semibold mb-0 fs-4">{{ $client->expiry_date }}</h6>
                            </td>

                            <td class="border-bottom-0">
                                <div class="d-flex align-items-center gap-2">
                                    @if ($client->is_renewed)
                                        <span class="badge bg-secondary rounded-3 fw-semibold">Active</span>
                                    @else
                                        <span class="badge bg-primary rounded-3 fw-semibold">Expired</span>
                                    @endif
                                </div>
                            </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="{{ $client->id }}" data-first_name="{{ $client->first_name }}" data-email="{{ $client->email }}" data-plan="{{ $client->plan }}" data-gps="{{ $client->gps }}" data-expiry_date="{{ $client->expiry_date }}" data-url="{{ url('/clients') }}">
                                      Edit
                                     </button>

                                     <button type="button" class="dropdown-item remove-button" data-toggle="modal" data-target="#removeModal" data-id="{{ $client->id }}" data-first_name="{{ $client->first_name }}" data-email="{{ $client->email }}" data-plan="{{ $client->plan }}" data-gps="{{ $client->gps }}" data-expiry_date="{{ $client->expiry_date }}" data-url="{{ url('/clients') }}">
                                      Remove
                                    </button>
                                    {{-- <a class="dropdown-item" href="#">Remove</a> --}}
                                    <button type="button" class="dropdown-item renew-button" data-toggle="modal" data-target="#renewModal" data-id="{{ $client->id }}" >
                                          Renew
                                    </button>
                                    {{-- <a class="dropdown-item" href="#">Renew</a> --}}
                                    <button type="button" class="dropdown-item receipts-button" data-toggle="modal" data-target="#receiptsModal" data-id="{{ $client->id }}">
                                        Receipts
                                    </button>
                                    {{-- <a class="dropdown-item" href="#">View Client</a> --}}
                                    <button type="button" class="dropdown-item btn btn-primary view-client" id="viewClientButton" data-toggle="modal" data-target="#viewClientModal" data-id="{{ $client->id }}">
                                        View Client
                                    </button>

                                     <button type="button" class="dropdown-item btn btn-primary makePayment"  data-toggle="modal" data-target="#makePaymentModal" data-id="{{ $client->id }}">
                                        Payment
                                    </button>

                                    <!-- Send SMS -->
                                    <button type="button" class="dropdown-item send-sms" data-toggle="modal" data-target="#sendSmsModal" data-id="{{ $client->id }}">
                                        Send SMS
                                    </button>

                                  </div>
                                </div>
                              </h6>
                            </td>
                          </tr>
                        @endforeach
                      </tbody>
                    </table>
                  </div>
                  <br>
                  <br>
                  <div class="d-flex align-items-center justify-content-end">
                    <nav aria-label="Page navigation example">
                      <ul class="pagination">
                        <li class="page-item" style="margin-right: 20px;">
                          <input type="number" id="page-number-input" class="form-control" min="1" max="{{ $total_pages }}" value="{{ $page_number }}">
                        </li>
                        <li class="page-item" style="margin-right: 20px;">
                          <button class="btn btn-primary" onclick="goToPage()">Go</button>
                        </li>
                        <li class="page-item">
                          <span class="page-link">{{ $page_number }} of {{ $total_pages }}</span>
                        </li>
                      </ul>
                    </nav>
                  </div>
                </div>
              </div>
            </div>
          </div>    
        </div>    
      </div>
    </div>
@endsection

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

clientId = '';

makePaymentClientId = '';

$(document).ready(function(){

   $('#default-sms').change(function(){
        var smsContent = $('option:selected', this).data('sms_content');
        $('#sms_message').val(smsContent);
  });

  //send sms to client
  $(document).on('click','.send-sms', function(e) {
      e.preventDefault();
      clientId = $(this).data('id');
  });

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

      let message = $('#sms_message').val();

      Swal.fire({
          title: "Are you sure?",
          text: "You are about to send an SMS to the client",
          icon: "warning",
          showCancelButton: true,
          confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          confirmButtonText: 'Yes, send SMS!'
      }).then((result) => {
          if (result.isConfirmed) {
              $.ajax({
                  url: `{{ url('/send-sms-to-client') }}`,
                  type: 'POST',
                  data: {
                      client_id: clientId,
                      message: message,
                      _token: $('meta[name="csrf-token"]').attr('content')
                  },
                  success: function(response) {
                      Swal.fire(
                          'Success!',
                          'SMS sent successfully!',
                          'success'
                      ).then(() => {
                          location.reload();
                      });
                  },
                  error: function(response) {
                      Swal.fire(
                          'Failed!',
                          'SMS failed!',
                          'error'
                      );
                  }
              });
          }
      });
  });

  $('#payment_type').change(function() {
    if ($(this).val() === 'early_payment') {
      $('#internet_package').hide();
      $('#payment_amount').show();

    } else {
      $('#payment_amount').hide();
      //hide amount
      $('#amount').removeAttr('required');
      $('#amount').val(0);
      $('#internet_package').show();
    }
  });

  $(document).on('click','.makePayment', function(e) {
      e.preventDefault();

      makePaymentClientId = $(this).data('id');

      //get wallet data
      $.ajax({
        url: `{{ url('/client-wallet')}}`, // Update this URL to the correct one
        type: 'POST',
        data: {
            client_id: makePaymentClientId,
            _token: '{{ csrf_token() }}'
        },
        success: function(response) {
            // display the wallet balance
            console.log(response);
            $('#wallet_balance').val('GHC'+response.balance);
        },
        error: function(response) {
            $('#wallet_balance').val('GHC0.00');
        }
      });
  });

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

    let amount = $('#amount').val();
    var paymentType = $('#payment_type').val();
    let renewPackage = $('#renew_package').val();
    
    if(paymentType == "late_payment"){
      let val = renewPackage.split('-');
      //split renew package to get the amount
      renewPackage = val[0]
      amount = val[1];
    }

    Swal.fire({
      title: "Are you sure?",
      text: "You are about to make a payment of GHC" + amount,
      icon: "warning",
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Yes, make payment!'
    }).then((result) => {
      if (result.isConfirmed) {
        $.ajax({
          url: `{{ url('/make-payment') }}`,
          type: 'POST',
          data: {
            client_id: makePaymentClientId,
            payment_type: paymentType,
            package_id: renewPackage,
            amount: amount,
            _token: $('meta[name="csrf-token"]').attr('content')
          },
          success: function(response) {
            Swal.fire(
              'Success!',
              'Payment made successfully!',
              'success'
            ).then(() => {
              location.reload();
            });
            // TODO: Update the page with the new payment
          },
          error: function(response) {
            Swal.fire(
              'Failed!',
              'Payment failed!',
              'error'
            );
            // TODO: Handle the error
          }
        });
      }
    });
  });

  $('#searchForm').submit(function(event) {
      event.preventDefault();
      let searchQuery = $('input[name="search"]').val();

      $.ajax({
          url: `{{ url('/search-client') }}`,
          type: 'POST',
          data: {
              search: searchQuery,
              _token: '{{ csrf_token() }}'
          },
          success: function(response) {
              // Handle success here
              console.log(response);

              // display the search client in the table
              let tableBody = '';

              response.clients.forEach((client, index) => {
                  tableBody += `
                      <tr>
                          <td class="border-bottom-0">
                              <input type="checkbox" class="selectClient" value="${client.id}">
                          </td>
                          <td class="border-bottom-0"><h6 class="fw-semibold mb-0">${index + 1}</h6></td>
                          <td class="border-bottom-0">
                              <h6 class="fw-semibold mb-1">${client.account_username}</h6>
                              <span class="fw-normal">${client.data_package}</span>                          
                          </td>

                          <td class="border-bottom-0">
                              <h6 class="fw-semibold mb-0 fs-4">${client.expiry_date}</h6>
                          </td>

                          <td class="border-bottom-0">
                              <div class="d-flex align-items-center gap-2">
                                  ${client.is_renewed ? '<span class="badge bg-secondary rounded-3 fw-semibold">Active</span>' : '<span class="badge bg-primary rounded-3 fw-semibold">Expired</span>'}
                              </div>
                          </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 dropdown-menu-right" style="z-index:100" aria-labelledby="dropdownMenuButton">
                                          <button type="button" class="dropdown-item edit-button" data-toggle="modal" data-target="#editModal" data-id="${client.id}"  data-plan="${client.plan}" data-gps="${client.gps}" data-expiry_date="${client.expiry_date}" data-url="{{ url('/clients') }}">
                                              Edit
                                          </button>

                                          <button type="button" class="dropdown-item remove-button" data-toggle="modal" data-target="#removeModal" data-id="${client.id}" data-first_name="${client.first_name}" data-email="${client.email}" data-plan="${client.plan}" data-gps="${client.gps}" data-expiry_date="${client.expiry_date}" data-url="{{ url('/clients') }}">
                                              Remove
                                          </button>
                                          <button type="button" class="dropdown-item renew-button" data-toggle="modal" data-target="#renewModal" data-id="${client.id}" >
                                              Renew
                                          </button>
                                          <button type="button" class="dropdown-item receipts-button" data-toggle="modal" data-target="#receiptsModal" data-id="${client.id}">
                                              Receipts
                                          </button>
                                          <button type="button" class="dropdown-item btn btn-primary view-client" id="viewClientButton" data-toggle="modal" data-target="#viewClientModal" data-id="${client.id}">
                                              View Client
                                          </button>
                                          <button type="button" class="dropdown-item btn btn-primary makePayment"  data-toggle="modal" data-target="#makePaymentModal" data-id="${client.id}">
                                              Payment
                                          </button>
                                          <!-- Send SMS -->
                                          <button type="button" class="dropdown-item send-sms" data-toggle="modal" data-target="#sendSmsModal" data-id="${client.id}">
                                              Send SMS
                                          </button>
                                      </div>
                                  </div>
                              </h6>
                          </td>
                      </tr>
                  `;
              });

            tableBody +=`
              <tr style="opacity: 0;">
                <!-- Dummy row -->
                <td class="border-0"></td>
                <td class="border-0"></td>
                <td class="border-0"></td>
                <td class="border-0"></td>
                <td class="border-0"></td>
                <td class="border-0"></td>
                </tr><tr style="opacity: 0;">
                    <!-- Dummy row -->
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                </tr>
                <tr style="opacity: 0;">
                    <!-- Dummy row -->
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                </tr>
                                <tr style="opacity: 0;">
                    <!-- Dummy row -->
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                </tr>
                                <tr style="opacity: 0;">
                    <!-- Dummy row -->
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                </tr>
                                <tr style="opacity: 0;">
                    <!-- Dummy row -->
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                    <td class="border-0"></td>
                </tr>
              `;

              $('tbody').html(tableBody);
          },
          error: function(err) {
              // Handle error here
          }
      });

  });

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

    $(document).on('click','.renew-button',function(e){
        const id = $(this).data('id');

        clientId = id;

        //get the client data
        $.ajax({
            url: `{{ url('/clients') }}/` + id + '/edit',
            type: 'GET',
            success: function(response) {
                // Assuming 'client' contains the JSON data

                const client = response.client;

                //select the plan
                $('#renew-package').val(client.plan);

                // Show the modal
                //$('#renewModal').modal('show');
            },
            error: function(jqXHR, textStatus, errorThrown) {
            }
        });
    });

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

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

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

      var formData = $(this).serialize();

      // Add CSRF token to form data
      formData += '&_token=' + csrfToken;

      $.ajax({
          url: `{{ url('/add-client')}}`, // replace with your endpoint
          type: 'POST',
          data: formData,
          success: function(response) {
              // Handle success here
              $('#addClientModal').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
              $('#addClientSubmit').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
              $('#addClientSubmit').prop('disabled', false);
          }
      });
    });

    $(document).on('click','.view-client', function() {
      var id = $(this).data('id');

              $('#view-accountUsername').val('');
              $('#view-username').val('');
              $('#view-clientId').val('');
              $('#view-phoneNumber').val('');
              $('#view-email').val('');
              $('#view-gps').val('');
              $('#view-plan').val('');
              $('#view-node').val('');
              $('#view-expiryDate').val('');
              $('#view-referalBonus').val('');
              $('#view-installationType').val('');
              $('#view-status').val('');
              $('#view-cpeOutdoor').val('');
              $('#view-cpeIndoor').val('');
              $('#view-wallet').val('');
              
      $.ajax({
          url: `{{ url('/clients') }}/` + id + '/edit',
          type: 'GET',
          success: function(response) {
              // Assuming 'client' contains the JSON data

              const client = response.client;
              const node = response.node; 

              //display the wallet balance
              $('#view-wallet').val('GHC'+client.wallet_balance);
              $('#view-accountUsername').val(client.account_username);
              $('#view-username').val(client.username);
              $('#view-clientId').val(client.client_id);
              $('#view-phoneNumber').val(client.phone_number);
              $('#view-email').val(client.email);
              $('#view-gps').val(client.gps);
              $('#view-plan').val(client.plan);
              $('#view-expiryDate').val(client.expiry_date);
              $('#view-referalBonus').val(client.referal_bonus);
              $('#view-installationType').val(client.installation_type);
              $('#view-status').val(client.status);
              $('#view-cpeOutdoor').val(client.cpe_outdoor);
              $('#view-cpeIndoor').val(client.cpe_indoor);
              if (node.length > 0 && node[0] !== undefined) {
                $('#view-node').val(node[0].node_name);
              } else {
                $('#view-node').val(''); // or some default value
              }              // Show the modal
              //$('#viewClientModal').modal('show');
          },
          error: function(jqXHR, textStatus, errorThrown) {
          }
      });
    });

    $(document).on('click','.edit-button', function() {
      clientId = $(this).data('id');
      const id = clientId;
      var url = $(this).data('url');
       
       $('#edit-accountUsername').val('');
            $('#edit-username').val('');
            $('#edit-clientId').val('');
            $('#edit-phoneNumber').val('');
            $('#edit-email').val('');
            $('#edit-gps').val('');
            $('#edit-plan').val('');
            $('#edit-node').val('');
            $('#edit-expiryDate').val('');
            $('#edit-referalBonus').val('');
            $('#edit-installationType').val('');
            $('#edit-status').val('');
            $('#edit-cpeOutdoor').val('');
            $('#edit-cpeIndoor').val('');
            $('#edit-wallet').val(0.00);

        $.ajax({
          url: `{{ url('/clients') }}/` + id + '/edit',
          type: 'GET',
          success: function(response) {
            
              //$('#edit-expiryDate').val(client.expiry_date);
              client = response.client;
              node = response.node;

              $('#edit-accountUsername').val(client.account_username);
              $('#edit-username').val(client.username);
              $('#edit-clientId').val(client.client_id);
              $('#edit-phoneNumber').val(client.phone_number);
              $('#edit-email').val(client.email);
              $('#edit-gps').val(client.gps);
              $('#edit-plan').val(client.plan);
              if (node.length > 0 && node[0] !== undefined) {
                $('#edit-node').val(node[0].node_uuid);
              } else {
                $('#edit-node').val(''); // or some default value
              }  
              let expiryDate = new Date(client.expiry_date);
              let formattedDate = expiryDate.toISOString().split('T')[0];
              $('#edit-expiryDate').val(formattedDate); 
              $('#edit-referalBonus').val(client.referal_bonus);
              $('#edit-installationType').val(client.installation_type);
              $('#edit-status').val(client.status);
              $('#edit-cpeOutdoor').val(client.cpe_outdoor);
              $('#edit-cpeIndoor').val(client.cpe_indoor);   
              $('#edit-wallet').val(client.wallet_balance);  
              //add wallet_id as data attribute to edit-wallet
              $('#edit-wallet').data('wallet_id', client.wallet_id);      
          },
          error: function(jqXHR, textStatus, errorThrown) {
            console.log(textStatus, errorThrown);
          }
        });
    });


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

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

      const id = $(this).data('id');
      const url = $(this).attr('action');
      let data = $(this).serialize();

      console.log(data);

      data += '&_token=' + csrfToken;

      //add id as part of serialize
      data += '&id=' + clientId;

      //get the wallet_id from the edit-wallet and add to the data
      const walletId = $('#edit-wallet').data('wallet_id');

      data += '&wallet_id=' + walletId;

      Swal.fire({
          title: 'Are you sure?',
          text: "You are about to update the client data.",
          icon: 'warning',
          showCancelButton: true,
          confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          confirmButtonText: 'Yes, update it!'
      }).then((result) => {
          if (result.isConfirmed) {
              $.ajax({
                  url: `{{ url('clients') }}`,
                  type: 'post',
                  data: data,
                  success: function(response) {
                      Swal.fire(
                          'Success!',
                          'Your form has been submitted.',
                          'success'
                      ).then((result) => {
                          if (result.isConfirmed || result.isDismissed) {
                              location.reload();
                          }
                      });
                  },
                  error: function(err) {
                      // console.log(textStatus, errorThrown);
                      let errorMessage = err.responseJSON.error || 'Something went wrong!';

                      Swal.fire({
                          icon: 'error',
                          title: 'Oops...',
                          text: errorMessage,
                      });
                  }
              });
          }
      });

    });

    $(document).on('click','.remove-button',function() {
        var clientId = $(this).data('id');
        var url = $(this).data('url');

        //add sweet alert here
        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, remove it!'
        }).then((result) => {
          if (result.isConfirmed) {
            $.ajax({
              url: url + '/' + clientId,
              type: 'DELETE',
              data: {
                  "_token": "{{ csrf_token() }}",
              },
              success: function(result) {
                 //add sweet alert
                  Swal.fire(
                    'Deleted!',
                    'Your file has been deleted.',
                    'success'
                  )
                  location.reload();
              },
              error: function(err) {
                  // add sweet alert

                  Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                    text: 'Something went wrong!',
                    footer: '<a href>Why do I have this issue?</a>'
                  })
              }
            });
          }
        })
    });

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

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

      //var url = '/clients/renew'; // the endpoint to submit to
      // var clientId = $('#renew-client').val();
      const packageId = $('#renew-package').val();
      const renewDate = $('#renew-date').val();
      const expiryDate = $('#renew-expiry').val();
      const renewType = $('#renew-type').val();

      //check if packageId and renewType is not empty if it is empty alert user

      if (packageId == null || renewType == null) {
        Swal.fire({
          icon: 'error',
          title: 'Oops...',
          text: 'Please select a package and renew type!',
          footer: '<a href>Why do I have this issue?</a>'
        });
        $('#renewClientSubmit').prop('disabled', false);
        return;
      }

      $.ajax({
          url: `{{ url('/renew-client') }}`,
          type: 'POST',
          data: {
              client_id: clientId,
              package_id: packageId,
              renew_date: renewDate,
              expiry_date: expiryDate,
              renew_type: renewType,
              _token: '{{ csrf_token() }}'
          },
          success: function(response) {
              // Handle success
              // console.log(response);
              // $('#renewModal').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();
                }
              });
             $('#renewClientSubmit').prop('disabled', false);

          },
          error: function(err) {
              // Handle error
              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>'
              });
              $('#renewClientSubmit').prop('disabled', false);
          }
      });
    });

    $(document).on('click','.receipts-button',function () {
            var clientId = $(this).data('id');

            // Make an AJAX request to fetch client receipts
            $.ajax({
                url: `{{ url('/clients')}}/` + clientId + '/receiptsById', // Replace with your actual API endpoint
                method: 'GET',
                dataType: 'json',
                success: function (data) {
                    // Handle the retrieved receipts data
                    console.log(data);
                    displayReceipts(data.receipts);
                },
                error: function (err) {
                    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>'
                    });
                }
            });
    });

    $('#selectAll').on('click', function() {
      // Check or uncheck all client checkboxes
      $('.selectClient').prop('checked', this.checked);
    });   

    // When the "delete selected" button is clicked
    $('#deleteSelected').on('click', function() {
        // Get all selected client IDs
        var selectedClients = $('.selectClient:checked').map(function() {
            return $(this).val();
        }).get();

        // Show a confirmation dialog
        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) {
                // User confirmed, send a DELETE request to the server
                $.ajax({
                    url: `{{ url('/delete-clients') }}`, // replace with your endpoint
                    type: 'DELETE',
                    data: {
                        clients: selectedClients,
                        _token: $('meta[name="csrf-token"]').attr('content')
                    },
                    success: function(response) {
                        // Show a success alert and reload the page
                        Swal.fire(
                            'Deleted!',
                            'Your file has been deleted.',
                            'success'
                        ).then((result) => {
                            location.reload();
                        });
                    },
                    error: function(err) {
                        // Show an error alert
                        Swal.fire({
                            icon: 'error',
                            title: 'Oops...',
                            text: err.responseJSON.error,
                            footer: '<a href>Why do I have this issue?</a>'
                        });
                    }
                });
            }
        });
    });
});

function previousPage() {
  if (page_number > 1) {
    page_number--;
    window.location = `{{ url('/clients/${page_number}') }}`;
  }
}

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


function goToPage() {
  var pageNumber = document.getElementById('page-number-input').value;
  var totalPages = {{ $total_pages }};
  
  if (pageNumber > totalPages) {
    pageNumber = totalPages;
  }
  
  window.location.href = `{{ url('/clients') }}/${pageNumber}`;
}


function displayReceipts(receipts) {
    // Assuming you have a table body with ID 'receiptsTableBody'
    var tableBody = $('#receiptsTableBody');

    // Clear previous content
    tableBody.empty();

    // Append each receipt to the table body
    $.each(receipts, function (index, receipt) {
        tableBody.append('<tr>' +
            '<td>' + receipt.renew_date + '</td>' +
            '<td>' + receipt.data_package + '</td>' +
            '<td>' + receipt.expiry_date + '</td>' +
            '<td><button class="btn btn-primary">View</button></td>' +
            '</tr>');
    });
}

function uploadFile() {
    $('#excelFile').click();
    $('#excelFile').on('change', function() {
        var file = this.files[0];
        var formData = new FormData();
        formData.append('file', file);

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

        Swal.fire({
            title: 'Are you sure?',
            text: "You are about to import clients from the selected file.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, import it!'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: "{{ url('/import-clients') }}",
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        Swal.fire(
                            'Imported!',
                            'Your file has been imported.',
                            'success'
                        ).then((result) => {
                            location.reload();
                        });
                    },
                    error: function(err) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Oops...',
                            text: err.responseJSON.error,
                            footer: '<a href>Why do I have this issue?</a>'
                        });
                    }
                });
            }
        });
    });
}

</script>
    