<?php
session_start();
include 'includes/database.php';
include 'includes/functions.php';
$conn= new Functions();

if(isset($_POST['privilege'])){
   $privilege_input = $_POST['privilege'];
    $sql = "SELECT * FROM admin_privileges";
    $conn->query($sql);
    $result = $conn->fetchMultiple();
    $admin_privileges = [];
    foreach ($result as $details){
        $admin_privileges[] = $details->module_name;

    }

    $success_message = '';

    //insert newly added data
    foreach ($privilege_input as $new_data){
        if(!in_array($new_data, $admin_privileges)){
           $sql = "INSERT INTO admin_privileges (module_name) VALUES (:module_name)";
           $conn->query($sql);
           $conn->bind(":module_name", $new_data);
           //execute
          try{
              $conn->execute();
                  $success_message = "<script>
                         toastr['success']('Admin privileges updated successfully.');
                         </script><meta http-equiv='refresh' content='3; admin-privileges'>";
          }catch (PDOException $err){
              $error= $err->getMessage();
              $success_message = "<script>
                 toastr['error']('$error');
              </script>";
          }

        }
    }

    //delete unselected data already in database
    foreach ($admin_privileges as $added_data){
        if(!in_array($added_data, $privilege_input)){
            $sql = "DELETE FROM admin_privileges WHERE module_name = :module_name";
            $conn->query($sql);
            $conn->bind(":module_name", $added_data);
            //execute

            try{
                $conn->execute();
                $success_message = "<script>
                         toastr['success']('Admin privileges updated successfully.');
                         </script><meta http-equiv='refresh' content='3; admin-privileges'>";
            }catch (PDOException $err){
                $error= $err->getMessage();
                $success_message = "<script>
                 toastr['error']('$error');
              </script>";
            }
        }
    }

    echo $success_message;

}else{
    echo "<script>
         toastr['error']('You haven\'t selected any values');
      </script>";
}



