<?php
require 'db.php';
require 'functions.php';
requireRole(['admin']);

$pagetitle = 'My Profile';
$activemenu = '';

$stmt = $pdo->prepare("SELECT name, username, phone FROM adminuser WHERE id = ? AND isdeleted = 0");
$stmt->execute([currentUserId()]);
$me = $stmt->fetch();

require 'header.php';
?>

<div class="dfp-card" style="max-width:480px;">
  <h3>My Profile</h3>
  <form id="frmProfile" autocomplete="off">
    <div class="dfp-formgroup">
      <label>Name</label>
      <input type="text" name="name" value="<?php echo safeOut($me['name']); ?>" required>
    </div>
    <div class="dfp-formgroup">
      <label>Phone</label>
      <input type="text" name="phone" value="<?php echo safeOut($me['phone']); ?>" required>
    </div>
    <div class="dfp-formgroup">
      <label>Username</label>
      <input type="text" value="<?php echo safeOut($me['username']); ?>" disabled>
    </div>
    <button type="submit" class="btn">Save Profile</button>
  </form>
</div>

<div class="dfp-card" style="max-width:480px;">
  <h3>Change Password</h3>
  <form id="frmChangePassword" autocomplete="off">
    <div class="dfp-formgroup">
      <label>Current Password</label>
      <input type="password" name="currentpassword" required>
    </div>
    <div class="dfp-formgroup">
      <label>New Password</label>
      <input type="password" name="newpassword" required>
    </div>
    <button type="submit" class="btn">Change Password</button>
  </form>
</div>

<?php require 'footer.php'; ?>
<script>
$('#frmProfile').on('submit', function (e) {
  e.preventDefault();
  $.post('ajax_admin_profile.php', $(this).serialize() + '&action=updateprofile', function (resp) {
    dfpToast(resp.message, resp.success ? 'success' : 'error');
  }, 'json');
});

$('#frmChangePassword').on('submit', function (e) {
  e.preventDefault();
  var form = this;
  $.post('ajax_admin_profile.php', $(this).serialize() + '&action=changepassword', function (resp) {
    dfpToast(resp.message, resp.success ? 'success' : 'error');
    if (resp.success) { form.reset(); }
  }, 'json');
});
</script>
<?php require 'footer2.php'; ?>
