<script type="text/javascript">

$(document).ready(function(){
    $("#checkall").click(function(){
        if(this.checked){
            $(".check_class").attr("checked",true);					
            $(".check_class").parent().addClass("checked");					
        }else{
            $(".check_class").attr("checked",false);					
            $(".check_class").parent().removeClass("checked");					
        }
    });
    $("#status_msg").hide();
    $("#alert_msg").hide();
});

function delete_entry(user_id){
  swal({
        title: 'Are you sure?',
        text: "You won't be able to revert this!",
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#0CC27E',
        cancelButtonColor: '#FF586B',
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: 'No, cancel!',
        confirmButtonClass: 'btn btn-success mr-5',
        cancelButtonClass: 'btn btn-danger',
        buttonsStyling: false
    }).then(function () {
        location.href = 'userlist.php?act=delete&user_id='+user_id;
    }, function (dismiss) {
      return false; 
    });
}


function change_status(plan_id,status){
  //$(".loading_image").show();
  swal({
        title: 'Are you sure ?',
        text: "change status!",
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#0CC27E',
        cancelButtonColor: '#FF586B',
        confirmButtonText: 'Yes, change status!',
        cancelButtonText: 'No, cancel!',
        confirmButtonClass: 'btn btn-success mr-5',
        cancelButtonClass: 'btn btn-danger',
        buttonsStyling: false
    }).then(function () {
        $.ajax({
          url: "planlist.php",
          data: 'act=change_status&plan_id='+plan_id+'&status='+status,
          /*dataType: 'json',
          cache: false,*/
          success: function(msg){
                      $("#status_msg").show();
                      $("#status_msg").html("<div class='alert alert-success'><button data-dismiss='alert' class='close' type='button'>×</button>Status updated successfully...</div>");
                      $("#status_msg_td").html(msg);
                      hideMessage();
                      
                      if(status==0){
                        
                          $("#td_status_"+plan_id).html("<a href=\"javascript:void(0)\" onclick=\"change_status('"+plan_id+"','1')\" ><span class=\"badge badge-success\">InactiveActive</span></a>");

                      }else{
                        
                          /*$("#td_status_"+plan_id).html("<a href=\"javascript:void(0)\" onclick=\"change_status('"+plan_id+"','0')\" ><span class=\"badge badge-danger\">Inactive</span></a>");*/
                          $("#td_status_"+plan_id).html("<a href=\"javascript:void(0)\" onclick=\"change_status('"+plan_id+"','0')\" ><span class=\"badge badge-danger\">Active</span></a>");
                      }
                      window.location.reload();
          }
        });
    }, function (dismiss) {    
        return false; 
    });    
}

function validate_all(act){
    var act = $("#act").val();
    if(act==''){
        $("#alert_msg").show();
        $("#alert_msg").html("<div class='alert alert-danger'><button data-dismiss='alert' class='close' type='button'>×</button>Please select action to apply on selected records.</div>");
        return false;
    }else if($(".check_class:checked").length == 0){
  	$("#alert_msg").show();
  	$("#alert_msg").html("<div class='alert alert-danger'><button data-dismiss='alert' class='close' type='button'>×</button>Please select atleast one checkbox.</div>");
        return false;
    }else{
        $("#alert_msg").hide();
    }
        
  if(act == 'delete_all'){
      var msg = 'delete';
  }else if(act == 'activate_all'){
      var msg = 'activate';
  }else{
      var msg = 'inactivate';
  }
  
    swal({
        title: 'Are you sure to '+act.replace("_"," ")+' ?',
        text: "You won't be able to revert this!",
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#0CC27E',
        cancelButtonColor: '#FF586B',
        confirmButtonText: 'Yes, '+msg+' it!',
        cancelButtonText: 'No, cancel!',
        confirmButtonClass: 'btn btn-success mr-5',
        cancelButtonClass: 'btn btn-danger',
        buttonsStyling: false
    }).then(function () {
        $("#action").val(act);
        $("#listFrm").submit();
    }, function (dismiss) {
      return false; 
    });
}
	
</script>

<?php
$filename=basename($_SERVER['SCRIPT_FILENAME']);
$adminlogObj = new admin_log();

if($filename == 'productlist.php')
{
    $module_id = $adminlogObj->getModuleId($filename);
}
?>

<div class="breadcrumb">
    <h1>Clinic Subscriptions </h1>
    <ul>
        <li><a href="<?php echo SITE_URL.ADMIN_DIR ?>">Dashboard</a></li>
        <li>Clinic Subscriptipn list</li>
        <li><a href="<?php echo SITE_URL."x-admin/adminloglist.php?module_id=$module_id" ?>" target="_blank">Log</a></li>
    </ul>
</div>
<div class="separator-breadcrumb border-top"></div>


<div class="widget-body">
    <div class="portlet-body">
                        
    <?php echo (isset($successMsg) && $successMsg!='') ? "<div class='alert alert-success'><button data-dismiss='alert' class='close' type='button'>×</button>".base64_decode($successMsg)."</div>" : '' ; ?>
    <?php echo (isset($failedMsg) && $failedMsg!='') ? "<div class='alert alert-danger'><button data-dismiss='alert' class='close' type='button'>×</button>".base64_decode($failedMsg)."</div>" : '' ?>
   
    <div id="status_msg" style="display: none;"><div class="alert alert-success"><button data-dismiss='alert' class='close' type='button'>×</button>&nbsp;</div></div>
    <div id="alert_msg" style="display: none;"><div class="alert alert-danger"><button data-dismiss='alert' class='close' type='button'>×</button>&nbsp;</div></div>

    </div>
</div>

<form action="" method="post" id="searchFrm" name="searchFrm">
    <div class="row">
        <div class="col-lg-12 col-md-12">
            <div class="card mb-5">
                <div class="card-body">
                    <div class="row row-xs">
                        
                        <div class="col-md-2 mt-3 mt-md-0"  id="div_product_name">
                            <label for="product_name ">Product Name</label>
                            <input type="text" class="form-control" name="product_name" id="product_name"  />
                        </div>

                        <div class="col-md-2 mt-3 mt-md-0"  id="div_plan_name">
                            <label for="plan_name">Plan Name</label>
                            <input type="text" class="form-control" name="plan_name" id="plan_name"  />
                        </div>

                        <div class="col-md-2 mt-3 mt-md-0"  id="div_plan_type">
                            <label for="plan_type ">Plan Type</label>
                            <!-- <input type="text" class="form-control" name="plan_type" id="plan_type"  /> -->
                            <select class="form-control" name="plan_type" id="plan_type">
                                <option value="">Select Type</option>
                                <?php
                                    $subscription_plansObj = new subscription_plans();
                                    $fields = array('plan_id','plan_type');
                                    $where = array('plan_status='=>'active');
                                    $groupBy = array('plan_type');
                                    $plantypeArg = array('fields'=>$fields,'where'=>$where,'groupBy'=>$groupBy);
                                    $allplantype = $subscription_plansObj->getAllRecords($plantypeArg);
                                    foreach($allplantype as $pkey => $plantype_value)
                                    { ?>
                                        <option value="<?php echo $plantype_value->plan_type; ?>"><?php echo $plantype_value->plan_type; ?></option>
                                   <?php }
                                ?>
                            </select>
                        </div>

                        <div class="col-md-2 mt-3 mt-md-0"  id="div_plan_interval">
                            <label for="plan_interval ">Plan Interval</label>
                            <!-- <input type="text" class="form-control" name="plan_interval" id="plan_interval"  /> -->
                            <select class="form-control" id="plan_interval" name="plan_interval">
                                <option value="">Select Interval</option>
                                <?php
                                    $subscription_plansObj = new subscription_plans();
                                    $fields = array('plan_id','plan_interval');
                                    $where = array('plan_status='=>'active');
                                    $groupBy = array("plan_interval");
                                    $subscription_plansArg = array('fields'=>$fields,'where'=>$where,'groupBy'=>$groupBy);
                                    $allinterval = $subscription_plansObj->getAllRecords($subscription_plansArg);
                                    foreach($allinterval as $ikey => $intervalval)
                                    { ?>

                                        <option value="<?php echo $intervalval->plan_interval;?>"><?php echo $intervalval->plan_interval; ?></option>
                                    <?php } ?>
                            </select>
                        </div>

                        <div class="col-md-2 mt-3 mt-md-0"  id="div_plan_price">
                            <label for="plan_price ">Plan Price</label>
                            <input type="text" class="form-control" name="plan_price" id="plan_price"  />
                        </div>
                        
                        <div class="col-md-2  mt-3 mt-md-0">
                            
                            <label for="plan_status">Status</label>
                            <select class="form-control" id="plan_status" name="plan_status">
                                <option value="">Select Status</option>
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>
                      
                        <div class="col-md-2 mt-3 mt-md-0">
                            <br/>
                            <label for="">&nbsp;</label>
                            <button type="submit" name="submit" class="btn btn-primary btn-block">Search</button>
                        </div>
                        <div class="col-md-2 mt-3 mt-md-0">
                            <br/>
                            <label for="">&nbsp;</label>
                            <button type="reset" name="reset" class="btn btn-primary btn-block" onClick="window.location.reload()">Reset</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

<div class="row mb-4">
  <div class="col-md-6">
        <!-- <select id="act" name="act" class="form-control maction">
          <option value="">Multiple action</option>              
          <option value="activate_all">Activate selected</option>
          <option value="inactivate_all">De-activate selected</option>
          <option value="delete_all">Delete selected</option>
        </select>
        <button type="button" class="btn btn-primary m-1" onclick="return validate_all();">Apply</button> -->
  </div>
  <!-- <div class="col-md-6 pull-right">
      <div class="button-group">
         <a href="planadd.php" class="btn btn-dark m-1"><i class="i-Add-User"></i> Add New</a>
      </div>    
  </div>  --> 
</div>

<div class="row mb-4">
    <div class="col-md-12 mb-4">
        <div class="card text-left">

            <div class="card-body">
                <div class="table-responsive">
                  <form id="listFrm" name="listFrm" action="" method="post">       
                    <input type="hidden" id="action" name="action" value="">
                    <table id="list" class="display table table-striped table-bordered" style="width:100%">
                        <thead>
                            <tr>
                                <!-- <th class="center"><input type="checkbox" name="checkall" id="checkall"></th> -->
                                <th>ID</th>
                                <th>Clinic Name</th>
                                <th>Subscription Plan</th>
                                <!-- <th>Monthly/yearly</th> -->
                                <th>Trial Period</th>
                                <th>Subscription Start Date</th>
                                <th>Subscription Renewal Date</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                    </table>
                  </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="application/javascript">
   $(document).ready(function() {
    var currentDate = new Date().toJSON().slice(0, 10);
    
     $('#list').DataTable( { 
          "ajax": "subscription.php?act=load",
          "processing": true,
          "serverSide": true,
          "fnRowCallback" : function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                var renewal = aData[5];
                
                    const [year, month, day] = aData[5].split('-');
                    const renewalDate = [month, day, year].join('/');

                    const [year1, month1, day1] = currentDate.split('-');
                    const todayDate = [month1, day1, year1].join('/');
                    
                    var date1 = new Date(renewalDate);

                    var date2 = new Date(todayDate);  

                    var time_difference = date1.getTime() - date2.getTime(); 
                    var days_difference = Math.round(Math.abs(time_difference / (1000 * 60 * 60 * 24)));  
                          
                
                
                /*var millisBetween = renewal.getTime() - currentDate.getTime(); 
                var days = millisBetween/(1000*3600*24);
                var daysleft = Math.round(Math.abs(days));
                console.log(daysleft);*/
              if (days_difference <= 7) {
                $('td', nRow).css('background-color', 'Red');
              } /*else if (aData[5] == "4") {
                $('td', nRow).css('background-color', 'Orange');
              }*/
            },
          "pageLength": 25,
                "aaSorting": [],
                "aoColumnDefs": [
                    { 'bSortable': false, 'aTargets': [0] },
                    { 'bSortable': true, 'aTargets': [1] },
                    { 'bSortable': false, 'aTargets': [2] },
                    { 'bSortable': true, 'aTargets': [3] },
                    { 'bSortable': true, 'aTargets': [4] },
                    { 'bSortable': true, 'aTargets': [5] },
                    { 'bSortable': true, 'aTargets': [6] },
                    { 'bSortable': false, 'aTargets': [7] },
                ],

          language: {
              "processing" : "<div class='loader-bubble loader-bubble-primary m-5'></div>",
              "sEmptyTable" :  "No records found."
          }
          
      } );

      $( "#searchFrm" ).on( "submit", function(e) {
        e.preventDefault();

        var product_name = $("#product_name").val();
        var plan_name = $("#plan_name").val();
        var plan_type = $("#plan_type").val();
        var plan_interval = $("#plan_interval").val();
        var plan_price = $("#plan_price").val();
        var plan_status = $("#plan_status").val();
        
        $('#list').DataTable().destroy();
          $('#list').DataTable( { 
            "ajax": "planlist.php?act=load&plan_name="+plan_name+"&plan_type="+plan_type+"&plan_interval="+plan_interval+"&plan_status="+plan_status+"&plan_price="+plan_price+"&product_name="+product_name,
            "processing": true,
            "serverSide": true,
            "pageLength": 25,
                  "aaSorting": [],
                  "aoColumnDefs": [
                      { 'bSortable': false, 'aTargets': [0] },
                      { 'bSortable': true, 'aTargets': [1] },
                      { 'bSortable': true, 'aTargets': [2] },
                      { 'bSortable': false, 'aTargets': [3] },
                      { 'bSortable': true, 'aTargets': [4] },
                      { 'bSortable': true, 'aTargets': [5] },
                      { 'bSortable': true, 'aTargets': [6] },
                      { 'bSortable': false, 'aTargets': [7] },
                  ],
            language: {
                "processing" : "<div class='loader-bubble loader-bubble-primary m-5'></div>",
                "sEmptyTable" :  "No records found."
            }
            
        } );

      });

    });
</script>