<style>
.dataTables_filter{
margin-top: -35px;

}
.buttons-csv{
background-color: white;
color: #002B60;
border-color: #000;
}
.test {
box-shadow: 0 2px 6px 0 rgba(0,86,193,.5);
cursor: pointer;
color: #fff;
font-size: 15px;
padding: 10px;
width: 55px;
height: 25px;
line-height: 8px;
background: #00B4D5;
border-radius: 5px;
font-weight: 500;
display: block;
}
/* th{
text-align: center;
} */
</style>
<!-- start page title -->
<input id="empName" type="hidden" value="<?php echo $fname." ".$lname; ?> "><input id="empId" type="hidden" value=" <?php echo $id; ?>">
<div class="row">
<div class="col-12">
<div class="page-title-box page-title-box-alt">
<a href="<?php echo base_url().'members_list'; ?>" title="Back" ><i class="mdi mdi-keyboard-backspace" style="font-size: 35px;"></i></a>
<h4 class="page-title">Member Name : <?php echo $fname." ".$lname; ?> (Total Credits : <?php echo $avaiable_credit; ?>)</h4>

<div class="page-title-right">
<ol class="breadcrumb m-0">
<li class="breadcrumb-item manage-credits" >
<button type="button" class="btn btn-primary waves-effect waves-light">Manage Credits</button>
</li>
<!-- <li class="breadcrumb-item"><a href="javascript: void(0);">Tables</a></li>
<li class="breadcrumb-item active">Datatables</li> -->
</ol>
</div>
</div>
</div>
</div>     
<!-- end page title --> 




<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<input hidden id="costHidden" value="">
<!-- <h4 class="header-title">Buttons example</h4>
<p class="text-muted font-13 mb-4">

</p> -->

<table id="datatable-buttons" class="table table-striped dt-responsive nowrap w-100">
<thead>
<tr>
<th hidden>id</th>
<th style="text-align: center;">Order Id</th>
<th style="text-align: center;">Order Date</th>
<th style="text-align: center;">Expiry Date</th>
<th style="text-align: center;">Credit Transactions</th>
<th style="text-align: center;">Credit Balance</th>
<th style="text-align: center;">Remarks</th>
</tr>
</thead>


<tbody>
<?php foreach ($credit_data as $row)
{ ?>
<tr>
<td hidden><?php echo $row['id'];?></td>
    <td style="text-align: center;"><?php echo $row['order_id'];?></td>
    <td style="text-align: center;"><?php  $date = new DateTime($row['created_at']); echo $date->format('M d , Y'); ?></td>
    <td style="text-align: center;"><?php  
                                      if($row['running_balance'] + $row['used_points'] ==  0)
                                      {
                                       echo '-';
                                      }
                                      else
                                      {
                                        $expirydate = new DateTime($row['expiring_date']); echo $expirydate->format('M d , Y');
                                      }
                                      ?></td>
    <td style="text-align: center;">
                                      <?php  
                                      if($row['running_balance'] + $row['used_points'] ==  0) 
                                      {
                                        $balance = "- ".$row['credit_points'];
                                      }else{
                                        $balance = "+ ".$row['credit_points'];
                                      }  
                                      echo  $balance;
                                      ?>
	</td>
    <td style="text-align: center;">    <?php echo $row['avaiable_credit'];?> </td>
    <td style="text-align: center;">    <?php if($row['remark'] != null && $row['remark'] != ''){ echo $row['remark'];  }else{echo "-";};?> </td>
 
   
    
</tr>    
<?php } ?>

</tbody>
</table>

</div> <!-- end card body-->
</div> <!-- end card -->
</div><!-- end col-->
</div>
<!-- end row-->

<!--  Modal content for the Large example -->
<!-- <div  class="modal fade" id="bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" id="modalname">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myLargeModalLabel"></h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div id="plus" class="plus-ico" style="font-size:25px;text-align: end;padding-right: 40px;"></div>
<div class="modal-body" id="model-table" ></div>                   
</div>
</div>
</div>
</div> -->





<!--  Modal content for the Large example -->
<div  class="modal fade" id="bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" id="modalname">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myLargeModalLabel"></h4>
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
          </div>
        
        <div class="modal-body" id="model-table" ></div>                   
      </div>
    </div>
 </div>
</div>

                                            
<script>
$(document).on('click','.manage-credits',function(){
    var rule_key = '14';
  $.ajax({
    url:"<?= base_url(); ?>get_pack_list",
    method: 'GET',
    success: function(response) {
      pack=[];
      res = JSON.parse(response);
      res.data.forEach((val,index) => {
        pack[index] = `<option value="${val.id}">${val.package_name}</option>`;
      });
      addForm = `<div class="myform">
                  <form id="myform" method="POST" action="<?= base_url(); ?>add_creditsModel">
                  <input id="member_id" type="hidden" name="member_id" value="${ $('#empId').val() }">
                 
                                     
                      <div class="row" style="width:80%;margin:auto;">

                      <div class="mb-1 mt-2 col-md-4 ">
                      <label  >Add Credit points</label>
                      <input  type="radio" class="add_or_sub" id="add" name="add_or_sub" value="add"  checked> 
                      </div>
                      <div class="mb-1 mt-2 col-md-4 ">
                      <label  >Deduct Credit Points</label>
                      <input  type="radio" class="add_or_sub" id="sub" name="add_or_sub" value="sub"> 
                      </div>
                      

                        <div class="mb-1 mt-2 col-md-12 changeClass">
                            <label class="form-label">Pack</label>
                            <select name="package_name" id="packs" class="form-control">
                              <option value="CreditPoints">Custom credit points</option>
                              ${pack}
                            </select>
                        </div>
                        <div id="count_hide_show" class="mb-1 mt-2"></div>
                        <div class="mb-1 mt-2 col-md-4">
                            <label class="form-label">Credit Points<span style="color: red;margin-left: 4px;">*</label>
                            <input type="number" class="form-control" min="1"  name="credit_points" id="credit" required value="1" onkeypress = "return matchnum(event)">
                        </div>
                        <div class="mb-1 mt-2 col-md-4">
                            <label class="form-label">Cost($)<span style="color: red;margin-left: 4px;">*</label>
                            <input type="number" class="form-control" name="cost" id="cost" onkeypress = "return matchnum(event)" required value="${res.OnePackValue[0]['value']}">
                        </div>
                        <div class="mb-1 mt-2 col-md-4">
                            <label class="form-label">Transaction Method<span style="color: red;margin-left: 4px;">*</label>
                            <select name="method" id="method" class="form-control" required>
                              <option value="Others">Others</option>
                              <option value="card">Card</option>
                              <option value="cash">Cash</option>
                            </select>
                        </div>
                        <div class="mb-1 mt-2 col-md-12">
                            <label for="remarks" class="form-label">Remarks<span style="color: red;margin-left: 4px;">*</span></label>
                            <input type="text" class="form-control" id="remarks" name="remarks" required maxlength="30">
                            <span style="color: red;margin-left: 4px;"><i>Remarks must be 30 characters</i></span>
                        </div>
                    </div>
                    <div style="text-align:center;margin-top:30px;"><button type="submit" class="btn btn-primary waves-effect waves-light" id="button">Add</button></div>
                  </form>
              </div>`
    $('#myLargeModalLabel').html("Manage Credits For  "+$('#empName').val()+" ")
    $('#model-table').html(addForm);
    $('#bs-example-modal-lg').modal('show');
    $('#costHidden').val(res.OnePackValue[0]['value'])
    
     $('#credit').on('keyup', function(){  
        var CrieditCount = $(this).val();
        var cost = res.OnePackValue[0]['value'];
        var costcount = cost * CrieditCount;
        $('#cost').val(costcount);
        if (CrieditCount == 0)
        {
             $('#button').prop('disabled', true);
        }
        else
        {
            $('#button').prop('disabled', false);
        }
        
      });

      $('#method').on('click', function(){ 
        if($(this).val() == 'Others')
        {
        $('#remarks').prop('required', true);
        $('label[for="remarks"]').html('Remarks<span style="color: red;margin-left: 4px;">*</span>');
        }
        else
        {
          $('#remarks').prop('required', false);
          $('label[for="remarks"]').text('Remarks');
        }
      });
      
      $('#credit').on('click', function(){
        if($('#packs').val() == 'CreditPoints')
        {
        var CrieditCount = $(this).val();
        var cost = res.OnePackValue[0]['value'];
        var costcount = cost * CrieditCount;

        $('#cost').val(costcount);
        if (CrieditCount == 0 || CrieditCount == "")
        {
             $('#button').prop('disabled', true);
        }
        else
        {
            $('#button').prop('disabled', false);
        }
        }

      });

      if ($('#credit').val() == 0)
      {
         $('#button').hide();
      }
      else
      {
        $('#button').show();
      }

    },
    error: function(xhr, status, error) {
      // Handle the error here
      console.error(error);
    }
  });

  
});
</script>

<script>
$(document).on('change','#packs',function(){
    id = $(this).val();
    $.ajax({
    url:"<?= base_url(); ?>get_pack_list",
    method: 'POST',
    data: { 'id' : id },
    success: function(response) {
        res = JSON.parse(response);
        console.log(res)
      if( res.data.length > 0)
      {
        $('.changeClass').removeClass('col-md-12').addClass('col-md-8');
        count_hide_show = `<label class="form-label">Count</label><input type="number" class="form-control" name="count" min="1" value="1" onKeyDown="return false" id="count">`;
        $('#count_hide_show').show();
        $("#count_hide_show").addClass("col-md-4");
        $('#count_hide_show').html(count_hide_show);
        $('#credit').val(res.data[0]['credit']);
        $('#credit').attr('readonly', true);
        $('#cost').val(Number(res.data[0]['cost']).toFixed(2));
        $('#cost').attr('readonly', true);

        $('#count').on('input', function() {
            var countValue = $(this).val();
            var calculatedCredit = res.data[0]['credit'] * countValue;
            $('#credit').val(calculatedCredit);
            var calculatedCost = Number(res.data[0]['cost']).toFixed(2) * countValue
            $('#cost').val(calculatedCost);
          });

      }
      else
      {
        $('.changeClass').removeClass('col-md-8').addClass('col-md-12');
        $('#count_hide_show').removeClass('col-md-4');
        $('#count_hide_show').html('');
        $('#credit').removeAttr('readonly');
        $('#credit').val('1');
        $('#cost').val(res.OnePackValue[0]['value']);
        $('#cost').removeAttr('readonly');
      }

    },
    error: function(xhr, status, error) {
      // Handle the error here
      console.error(error);
    }
  });
});


</script>







<script>
    $(document).ready(function() {
      $('#datatable-buttons').DataTable({
        "order": [[0, 'desc']], // Set initial sorting to descending on the first column
        "dom": 'Bfrtip', // Show export buttons
        buttons: [
            {
                extend: 'pdfHtml5',
                title: 'Member Name : <?php echo $fname." ".$lname; ?> (Total Credits : <?php echo $avaiable_credit; ?>)', // Set your custom PDF title here
                text: 'PDF',
                customize: function(doc) {
                  doc.content[1].table.body.forEach(function(row) {
                    row.splice(0, 1); // Remove the first column (ID column)
                  });
                }
            },
            {
                extend: 'print',
                title: 'Member Name : <?php echo $fname." ".$lname; ?> (Total Credits : <?php echo $avaiable_credit; ?>)', // Set your custom print title here
                text: 'Print',
                customize: function(win) {
                  $(win.document.body).find('table').find('th:first-child, td:first-child').remove();
                }
            },
            {
                extend: 'copy',
                text: 'Copy', // Set the title for the Copy button
                titleAttr: 'Copy', // Set the tooltip for the Copy button
                exportOptions: {
                  columns: ':not(:first-child)' // Exclude the first column (ID column)
                }
            },
            {
                extend: 'csv',
                text: 'CSV', // Set the title for the CSV button
                title: 'Member Name : <?php echo $fname." ".$lname; ?> (Total Credits : <?php echo $avaiable_credit; ?>)', // Set your custom print title here
                exportOptions: {
                  columns: ':not(:first-child)' // Exclude the first column (ID column)
                }
            }
        ]
      });
    });

function matchnum(event)
{
    var charcode;
    charcode = event.which || event.keyCode;
    if(charcode>= 48 && charcode <= 57)return true; //only  numbers
    return false;
}
$(document).on('change','.add_or_sub',function(){
  var selectedValue = $('input[name="add_or_sub"]:checked').val();
  // alert(selectedValue)
  packSel = $('#packs').val();
  if (selectedValue === 'sub') {
     $("#packs").val(""); // Clear the Pack select
        $("#packs").val("CreditPoints");
        $('#count').val("")
        $('#method option[value="card"]').hide();
        $('#method option[value="cash"]').hide();
        $('#method').val("Others")
        $("#packs option[value='6']").hide();
        $("#packs option[value='7']").hide();
        $('#count_hide_show').hide();
        $('#remarks').prop('required', true);
        $("#credit").val("1"); // Reset Credit to 1 (you can set it to any default value)
        $("#cost").val($("#costHidden").val()); 
        $('#credit').prop('readonly', false);
        $('#cost').prop('readonly', false);
        $('.changeClass').removeClass('col-md-8').addClass('col-md-12');
        $('label[for="remarks"]').html('Remarks<span style="color: red;margin-left: 4px;">*</span>');
      } else {
        $("#packs").val("CreditPoints");
        $('#method option[value="card"]').show();
        $('#method option[value="cash"]').show();
        $("#packs option[value='6']").show();
        $("#packs option[value='7']").show();
        // $('#remarks').prop('required', false);
        $("#cost").val($("#costHidden").val()); 
        // $('label[for="remarks"]').text('Remarks');
        $('#remarks').prop('required', true);
        $('label[for="remarks"]').html('Remarks<span style="color: red;margin-left: 4px;">*</span>');
        if(packSel == 'CreditPoints'){
          $('#count_hide_show').hide();
        }
        else
        {
          $('#count_hide_show').show();
        }
      }


  if($(this).val() == 'sub')
  {
  $('#button').html('Deduct');
  }else{ 
    $('#button').html('Add');
    }
});


</script>




 