<?php
require_once('config.php');

// Update Informations
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  if (isset($_POST['update_user'])) {
    extract($_POST);
    $tt_this_uid = $_POST['update_user'];

    // Check Email Dublicate
    $tt_email_dublicate_chacker = showAllttdata("admin_user", "WHERE admin_email = '$admin_email' AND NOT (admin_email = '$admin_email' AND admin_id = '$tt_this_uid') ");
    if (empty($tt_email_dublicate_chacker)) {

      $old_user_password = getSingleValue('admin_user', 'admin_id', $tt_this_uid, 'admin_password');
      $old_user_key = getSingleValue('admin_user', 'admin_id', $tt_this_uid, 'admin_security_key');

      if ($admin_password !='') {
        $old_user_password = password_hash($admin_password, PASSWORD_BCRYPT);
        $old_user_key = '';
      }else {
        $old_user_password = getSingleValue('admin_user', 'admin_id', $tt_this_uid, 'admin_password');
        $old_user_key = getSingleValue('admin_user', 'admin_id', $tt_this_uid, 'admin_security_key');
      }

      // User cannton Change Their Status And Role
      if ($c_user == $tt_this_uid) {
        // Update Data
        $data_for_update = array(
          "admin_name"=>htmlentities($admin_name, ENT_QUOTES, 'utf-8'),
          "admin_email"=>htmlentities($admin_email, ENT_QUOTES, 'utf-8'),
          "admin_password"=> $old_user_password,
          "admin_security_key"=> $old_user_key,
        );
      }else {
        // Update Data
        $data_for_update = array(
          "admin_name"=>htmlentities($admin_name, ENT_QUOTES, 'utf-8'),
          "admin_email"=>htmlentities($admin_email, ENT_QUOTES, 'utf-8'),
          "admin_access"=>htmlentities($admin_access, ENT_QUOTES, 'utf-8'),
          "admin_status"=>htmlentities($admin_status, ENT_QUOTES, 'utf-8'),
          "admin_ud_post"=>$admin_ud_post,
          "admin_password"=> $old_user_password,
          "admin_security_key"=> $old_user_key,
        );
      }
      if (UpdateData('admin_user', 'admin_id', $tt_this_uid, $data_for_update)) {
        $tt_alert = ttAlert('success', 'User Update Successfully ! ');
      }else {
        $tt_alert = ttAlert('danger', 'Something went wrong to Update User !');
      }

    }else {
      $tt_alert = ttAlert('danger', 'This email is already associated with another account !');
    }
  }
}

// Add Informations
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  if (isset($_POST['add_user'])) {
    extract($_POST);

    $tt_this_uid = $_POST['add_user'];

    // Check Email Dublicate
    $tt_email_dublicate_chacker = showAllttdata("admin_user", "WHERE admin_email = '$admin_email'");
    if (empty($tt_email_dublicate_chacker)) {

      // Add Data
      $data_for_update = array(
        "admin_name"=>htmlentities($admin_name, ENT_QUOTES, 'utf-8'),
        "admin_email"=>htmlentities($admin_email, ENT_QUOTES, 'utf-8'),
        "admin_access"=>htmlentities($admin_access, ENT_QUOTES, 'utf-8'),
        "admin_status"=>htmlentities($admin_status, ENT_QUOTES, 'utf-8'),
        "admin_password"=>password_hash($admin_password, PASSWORD_BCRYPT),
        "admin_ud_post" => "active",
      );

      if (InsertData('admin_user', $data_for_update)) {
        header("Location:web-administration.php");
        exit();
      }else {
        $tt_alert = ttAlert('danger', 'Something went wrong to add User !');
      }
    }else {
      $tt_alert = ttAlert('danger', 'This email is already associated with another account !');
    }
  }
}

// Include Heaser File
require_once('inc/header.php');
?>
<main id="main" class="main ">
  <div class="row">
    <div class="col-6 align-items-center">
      <div class="pagetitle mb-0">
        <h1><?php echo $page_title ?></h1>
      </div>
    </div>
    <div class="col-6 text-end">
        <a  data-bs-toggle="modal" data-bs-target="#addUser" href="#" class="btn btn-primary btn-sm"><i class="bi bi-node-plus"></i> New User </a>
    </div>
  </div>
  <form class="" action="" method="post">
    <div class="modal fade" id="addUser" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="staticBackdropLabel">Edit User</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" ></button>
          </div>
          <div class="modal-body">
            <div class="mb-3">
              <label>User Name</label>
              <input  type="text" name="admin_name" class="form-control" required>
            </div>
            <div class="mb-3">
              <label>User Email</label>
              <input  type="email" name="admin_email" class="form-control" required>
            </div>

            <div class="mb-3">
              <label>Login Password</label>
              <div class="input-group mb-3">
                <input class="form-control"  id="valuPass1" type="text"  minlength="8" name="admin_password" class="form-control" required>
                <span class="cursor-pointer input-group-text" data-passmaker="generateFor" >Generate </span>
              </div>
            </div>
            <script>
            document.addEventListener('DOMContentLoaded', function() {
              document.querySelectorAll('[data-passmaker="generateFor"]').forEach(function(button) {
                button.addEventListener('click', function() {
                  const input = this.parentElement.querySelector('input[type="text"]');
                  if (input) {
                    input.value = generatePassword(10); // 10 characters
                  }
                });
              });
              function generatePassword(length) {
                const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()";
                let password = "";
                for (let i = 0; i < length; i++) {
                  password += charset.charAt(Math.floor(Math.random() * charset.length));
                }
                return password;
              }
            });
            </script>
            <div class="mb-3">
              <label>User Role</label>
              <select class="form-control" name="admin_access" required>
                <option value="" selected disabled>Select Role</option>
                <?php
                foreach ($pageAccess as $role => $pages) {
                  ?>
                  <option value="<?php echo $role ?>"><?php echo $role ?></option>
                  <?php
                }
                ?>
              </select>
            </div>
            <div class="mb-3">
              <label>User Status</label>
              <select class="form-control" name="admin_status">
                <option value="active">Active</option>
                <option value="deactive">Deactive</option>
              </select>
            </div>
          </div>
          <div class="modal-footer d-block">
            <div class="row">
              <div class="col-6">
                <button type="button" class="text-start btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
              </div>
              <div class="col-6 text-end">
                <button name="add_user" value="<?php echo $the_admin['admin_id'] ?>" type="submit" class="btn btn-primary ">Add New</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </form>
  <?php echo $tt_alert ?? ''; ?>
  <section class="section mt-4">
    <div class="bg-white rounded-2  ">
      <table  class="tt_datatable" style="width:100%">
        <thead>
            <tr>
                <th>#</th>
                <th>Name</th>
                <th class="text-center">Email</th>
                <th class="text-center">Role</th>
                <th class="text-center">Edit/Delete Post</th>
                <th class="text-center">Status</th>
                <th class="text-end">Action</th>
            </tr>
        </thead>
        <tbody>
        <?php
        $tt_user_access = showAllttdata("admin_user", " ORDER BY  admin_id  DESC ");
        if (!empty($tt_user_access)) {
          $count = 1;
          foreach ($tt_user_access as $the_admin) {
            ?>
            <tr>
                <td><?php echo $count ?></td>
                <td>
                  <?php echo $the_admin['admin_name'] ?>
                </td>
                <td class="text-center">
                  <?php echo $the_admin['admin_email'] ?>
                </td>
                <td class="text-center">
                  <?php echo $the_admin['admin_access'] ?>
                </td>
                <td class="text-center">
                  <?php
                  if ($the_admin['admin_ud_post'] == 'active')  {
                    echo "Yes";
                  } else {
                    echo "No";
                  }
                   ?>
                </td>
                <td class="text-center">
                  <?php
                  if ($the_admin['admin_status'] == 'active') {
                    ?>
                    <small class="badge bg-success fw-normal ms-3">Active</span>
                    <?php
                  }else {
                    ?>
                    <span class="badge bg-danger fw-normal ms-3">Deactive</span>
                    <?php
                  }
                  ?>
                </td>
                <td class="text-end action-btn">
                  <a class="bg-primary" data-bs-toggle="modal" data-bs-target="#editUser<?php echo $the_admin['admin_id'] ?>" href="#"><i class="bi bi-pencil"></i> Edit </a>
                </td>
            </tr>
            <?php
            $count ++;
          }
        }
        ?>
        </tbody>
      </table>
    </div>
  </section>
</main>
<?php
if (!empty($tt_user_access)) {
  foreach ($tt_user_access as $the_admin) {
    ?>
    <form class="" action="" method="post">
      <div class="modal fade" id="editUser<?php echo $the_admin['admin_id'] ?>" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="staticBackdropLabel">Add User</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
              <div class="mb-3">
                <label>User Name</label>
                <input  type="text" name="admin_name" value="<?php echo $the_admin['admin_name'] ?>" class="form-control">
              </div>
              <div class="mb-3">
                <label>User Email</label>
                <input  type="email" name="admin_email" value="<?php echo $the_admin['admin_email'] ?>" class="form-control">
              </div>
              <div class="mb-3">
                <label>Login Password <small>(If You Want to Change)</small></label>
                <div class="input-group mb-3">
                  <input  class="form-control"  id="mahamudfutureit_valuPass<?php echo $the_admin['admin_id']; ?>"  type="search"  minlength="8"  name="admin_password" >
                  <span  class="cursor-pointer input-group-text"  onclick="mahamudfutureit_GeneratePass('mahamudfutureit_valuPass<?php echo $the_admin['admin_id']; ?>')" >
                    Generate
                  </span>
                </div>
              </div>
              <?php
              // User cannton Change Their Status And Role
              if ($the_user['admin_id'] != $the_admin['admin_id']) {
                ?>
                <div class="mb-3">
                  <label>User Role</label>
                  <select class="form-control" name="admin_access">
                    <?php
                    foreach ($pageAccess as $role => $pages) {
                      ?>
                      <option value="<?php echo $role ?>" <?php if ($role == $the_admin['admin_access']) { echo "selected"; } ?>  ><?php echo $role ?></option>
                      <?php
                    }
                    ?>
                  </select>
                </div>
                <div class="mb-3">
                  <label>Edit/Delete Post <small class="text-muted"> (User Can Edit/Delete Article, Web Story, Pages) </small> </label>
                  <select class="form-control" name="admin_ud_post" required>
                    <option value="active" <?php if ($the_admin['admin_ud_post'] == 'active') { echo "selected"; } ?>>Yes</option>
                    <option value="deactive" <?php if ($the_admin['admin_ud_post'] == 'deactive') { echo "selected"; } ?>>No</option>
                  </select>
                </div>
                <div class="mb-3">
                  <label>User Status</label>
                  <select class="form-control" name="admin_status">
                    <option value="active" <?php if ($the_admin['admin_status'] == 'active') { echo "selected"; } ?>  >Active</option>
                    <option value="deactive" <?php if ($the_admin['admin_status'] == 'deactive') { echo "selected"; } ?>  >Deactive</option>
                  </select>
                </div>
                <?php
              }
              ?>
            </div>
            <div class="modal-footer d-block">
              <div class="row">
                <div class="col-6">
                  <button type="button" class="text-start btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
                <div class="col-6 text-end">
                  <button name="update_user" value="<?php echo $the_admin['admin_id'] ?>" type="submit" class="btn btn-primary ">Update</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </form>
    <?php
  }
}
 ?>
 <script>
   function mahamudfutureit_GeneratePass(mahamudfutureit_inputId) {
     const mahamudfutureit_input = document.getElementById(mahamudfutureit_inputId);
     if (mahamudfutureit_input) {
       mahamudfutureit_input.value = mahamudfutureit_generatePassword(10); // 10 characters
     }
   }

   function mahamudfutureit_generatePassword(mahamudfutureit_length) {
     const mahamudfutureit_charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()";
     let mahamudfutureit_password = "";
     for (let i = 0; i < mahamudfutureit_length; i++) {
       mahamudfutureit_password += mahamudfutureit_charset.charAt(Math.floor(Math.random() * mahamudfutureit_charset.length));
     }
     return mahamudfutureit_password;
   }
 </script>
<?php require_once('inc/footer.php'); ?>
