   <?php

   session_start();

    include_once('../config/conn/db-connection.php');
    include_once('../config/class/sap_model.php');


   if(!isset($_SESSION['logged_in']))
    {
       header("location:../index.php");
    }else{

    $user_session = trim($_SESSION['user_no']);
    $SAP = new SAP_infosytem();
    $SAPform = $SAP->fetch_sapform2();  

    /////////////////////////////////////////////////

   if(isset($_POST['save'])){
        error_reporting(0);
        $checkbox = $_POST['check'];
          for($i=0;$i<count($checkbox);$i++){
          $del_id = $checkbox[$i]; 

          $sql = "DELETE FROM `tbl_sapform` WHERE sapform_id = ?";
          $db->prepare($sql)->execute([$del_id]);



         // ==========audit trail==================
           $user = $user_session;
             if(!empty($_SERVER["HTTP_CLIENT_IP"])){
                     $ip = $_SERVER["HTTP_CLIENT_IP"];
                  }elseif(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){ 
                     $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
                  }else{
                     $ip = $_SERVER["REMOTE_ADDR"];
                }
               $host = gethostbyaddr($_SERVER['REMOTE_ADDR']);
               date_default_timezone_set("asia/manila");
               $logdate =  date('M-d-Y h:i A', strtotime("+0 HOURS"));
               $action = "'Zone Leader' Deleted SAPForm ID: '".$del_id."'";    
            // ==========end audit trail==============

            $stmt = $db->prepare("INSERT INTO  tbl_audittrail(`user_name`, `user_ip`, `user_host`, `logdate`, `action`) VALUES(?,?,?,?,?)");
            $true = $stmt->execute([$user, $ip, $host,  $logdate, $action]);


          $message = "<div class='alert alert-success'>Data deleted successfully !</div>";
          header('Refresh: 1;url='.$_SERVER['REQUEST_URI']);
        }
      }

     $stmt = $db->query("SELECT * FROM tbl_sapform");

?>



   <?php include 'header/main-header.php';?>

   <div class="content-wrapper">
       <section class="content-header">
           <div class="container-fluid">
               <div class="row mb-2">
                   <div class="col-sm-6">
                       <h1>Social Amelioration Program Form</h1>
                   </div>

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

       <section class="content">
           <div class="container-fluid">
               <div class="row">
                   <div class="col-12">


                       <div class="card">
                       <form method="post" action="">
                           <div class="card-header">
                             <button type="submit" class="btn btn-danger" name="save">Delete</button>
                           </div>
                          <div><?php if(isset($message)) { echo $message; } ?></div>
                           <div class="card-body">
                   

                               <table id="sapform-table" class="table table-bordered table-striped">
                                   <thead>
                                       <tr>
                                           <th><input type="checkbox" id="checkAl">&nbsp;Select All</th>
                                           <th>Beneficiaries Name</th>
                                           <th>Pupose</th>
                                           <th>Action</th>

                                       </tr>
                                   </thead>
                                  <tbody>
                                 <?php
                                      foreach($SAPform as $sap){ ?>
                                       <tr>
                                        <td><input type="checkbox" id="checkItem" name="check[]" value="<?= htmlentities($sap['sapform_id']); ?>"></td>
        
                                           <td><?= ucfirst(htmlentities($sap['beneficiary_name'])); ?></td>
                                           <td><?= ucfirst(htmlentities($sap['purpose'])); ?></td>
                                           <td>
                                            <div class="d-flex">
                                            <div class="flex-1">
                                            <button type="button" class="btn btn-success edit_sapformapprove" data-toggle="modal" data-target="#approve-Modal<?= htmlentities($user_session); ?>" data-id="<?= htmlentities($sap['sapform_id']); ?>"><i class="fas fa-thumbs-up"></i>&nbsp;Approve 
                                            </button>
                                          </div>&nbsp;
                                          <div class="flex-1">
                                            <button type="button"  class="btn btn-warning edit_sapformdisapprove" data-toggle="modal" data-target="#disapprove-Modal<?= htmlentities($user_session); ?>" data-disapprove="<?= htmlentities($sap['sapform_id']); ?>"><i class="fas fa-thumbs-down"></i>&nbsp; Disapprove
                                            </button>
                                          </div>
                                          </div>
                                        </td>
                                       </tr>
                                       <?php $found_rows = true; }  if (!isset($found_rows)) echo "<tr><td colspan ='4'><div class='alert alert-dark' style='font-weight:bold;'>No records found.</div></td></tr>"; 
                                       ?>
  
                                   </tbody>
                               </table>
                             </form>
                           </div>
                       </div>
                   </div>
               </div>
           </div>
       </section>
   </div>
   <?php } ?>
<?php include 'modal/sapformzoneleaderdisapprove_modal.php';?>
<?php include 'modal/sapformzoneleaderapprove_modal.php';?>

    <script>
           $(document).ready(function() {   
               load_data();    
               var count = 1; 
               function load_data() {
                   $(document).on('click', '.edit_sapformapprove', function() {
                        var sapform_id = $(this).data("id");
                          getID(sapform_id); //argument    
                 
                   });
                }

                 function getID(sapform_id) {
                      $.ajax({
                          type: 'POST',
                          url: 'fetch_row/sapformapprove_row.php',
                          data: {
                              sapform_id: sapform_id
                          },
                          dataType: 'json',
                          success: function(response) {
                          $('#edit_sapformid').val(response.sapform_id);
                          $('#edit_sapformno').val(response.sapform_no);
                          $('#edit_purpose').val(response.purpose);
                          $('#edit_totalmembersofthefamily').val(response.total_membersofthefamily);
                          const uppercaseWords1 = str => str.replace(/^(.)|\s+(.)/g, c => c.toUpperCase());//Pinapalaki lang nito ang unang letra.
                          $('#edit_fullname').val(uppercaseWords1(response.lastname)+', '+uppercaseWords1(response.firstname)+' '+uppercaseWords1(response.middlename));
                       }
                    });
                 }
           
           });
            
     </script>
    <script>
           $(document).ready(function() {   
               load_data();    
               var count = 1; 
               function load_data() {
                   $(document).on('click', '.edit_sapformdisapprove', function() {
                        var sapform_id = $(this).data("disapprove");
                          getID(sapform_id); //argument    
                 
                   });
                }

                 function getID(sapform_id) {
                      $.ajax({
                          type: 'POST',
                          url: 'fetch_row/sapformapprove_row.php',
                          data: {
                              sapform_id: sapform_id
                          },
                          dataType: 'json',
                          success: function(response2) {
                          $('#edit2_sapformid').val(response2.sapform_id);
                          $('#edit2_sapformno').val(response2.sapform_no);
                          $('#edit2_purpose').val(response2.purpose);
                          $('#edit2_totalmembersofthefamily').val(response2.total_membersofthefamily);
                          const uppercaseWords = str => str.replace(/^(.)|\s+(.)/g, c => c.toUpperCase());//Pinapalaki lang nito ang unang letra.
                          $('#edit2_fullname').val(uppercaseWords(response2.lastname)+', '+uppercaseWords(response2.firstname)+' '+uppercaseWords(response2.middlename));
                       }
                    });
                 }
           
           });
            
     </script>

   <footer class="main-footer">
       <div class="float-right d-none d-sm-block">
           <b>Version</b> 1.0.0
       </div>
       <strong>Copyright &copy; 2021 <b>SAP Information System </b>.</strong>
   </footer>

   <aside class="control-sidebar control-sidebar-dark">
   </aside>
   </div>


<script>
$("#checkAl").click(function () {
  $('input:checkbox').not(this).prop('checked', this.checked);
});
</script>

   <script src="../plugins/jquery/jquery.min.js"></script>
   <script src="../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
   <script src="../plugins/datatables/jquery.dataTables.min.js"></script>
   <script src="../plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
   <script src="../plugins/datatables-responsive/js/dataTables.responsive.min.js"></script>
   <script src="../plugins/datatables-responsive/js/responsive.bootstrap4.min.js"></script>
   <script src="../dist/js/adminlte.min.js"></script>
   <script src="../dist/js/demo.js"></script>
   <script>
       $(function() {
           $("#sapform-table").DataTable({
               // "responsive": true,
               // "autoWidth": false,
           });
       });
   </script>
   </body>

   </html>