<?php
require 'db.php';
require 'functions.php';

if (isLoggedIn() && currentRole() === 'panchayatuser') {
    header('Location: ' . loginRedirectAfter('panchayat_dashboard.php'));
    exit;
}
$redirect = safeOut($_GET['redirect'] ?? '');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Panchayat Login - Divar Ferry Pass App</title>
<link rel="icon" href="logo.png" type="image/png">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="dfpToastWrap"><div class="dfp-toast" id="dfpToastBox"></div></div>

<div class="dfp-loginwrap">
  <img src="logo.png" class="logo" alt="logo">
  <h3>Panchayat Login</h3>
  <form id="frmLogin" autocomplete="off">
    <input type="hidden" name="redirect" value="<?php echo $redirect; ?>">
    <div class="dfp-formgroup" style="text-align:left;">
      <label>Username</label>
      <input type="text" name="username" id="username" required>
    </div>
    <div class="dfp-formgroup" style="text-align:left;">
      <label>Password</label>
      <input type="password" name="password" id="password" required>
    </div>
    <div class="dfp-formgroup" style="text-align:left;">
      <label><input type="checkbox" id="rememberme" style="width:auto;height:auto;"> Remember me</label>
    </div>
    <button type="submit" class="btn" style="width:100%;">Login</button>
  </form>
  <p style="margin-top:10px;"><a href="panchayat_forgotpassword.php">Forgot password?</a></p>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(function () {
  var saved = localStorage.getItem('dfpPanchayatRemember');
  if (saved) {
    var obj = JSON.parse(saved);
    $('#username').val(obj.username);
    $('#rememberme').prop('checked', true);
  }

  $('#frmLogin').on('submit', function (e) {
    e.preventDefault();
    var btn = $(this).find('button[type=submit]');
    if (btn.prop('disabled')) { return; }
    btn.prop('disabled', true);

    $.post('ajax_panchayat_login.php', $(this).serialize(), function (resp) {
      btn.prop('disabled', false);
      if (resp.success) {
        if ($('#rememberme').is(':checked')) {
          localStorage.setItem('dfpPanchayatRemember', JSON.stringify({ username: $('#username').val() }));
        } else {
          localStorage.removeItem('dfpPanchayatRemember');
        }
        window.location.href = resp.data.redirect;
      } else {
        toast(resp.message, 'error');
      }
    }, 'json').fail(function () {
      btn.prop('disabled', false);
      toast('Login failed. Please try again.', 'error');
    });
  });
});

function toast(msg, type) {
  var box = document.getElementById('dfpToastBox');
  var wrap = document.getElementById('dfpToastWrap');
  box.className = 'dfp-toast ' + type;
  box.innerText = msg;
  wrap.style.display = 'block';
  setTimeout(function () { wrap.style.display = 'none'; }, 2500);
}
</script>
</body>
</html>
