<?php
ob_start();
session_start();
define('DIR_APPLICATION', str_replace('\'', '/', realpath(dirname(__FILE__))) . '/');

if (!file_exists("config.php")) {
  header("Location: install/index.php");
  die();
}

include_once("functions.php");
unset($_SESSION['step'], $_SESSION['domain']);

include_once(DIR_APPLICATION."config.php");
include_once(DIR_APPLICATION."library/maxPower.php");
include_once(DIR_APPLICATION."library/encryption.php");
include_once(DIR_APPLICATION."library/helper.php");

$converter = new Encryption;
$helper    = new ams_helper;
$helper->removeInstallFolder(ROOT_PATH.'install');

/* If already logged in, go to dashboard */
if (check_login()) {
  if ($_SESSION['login_type'] == 'admin' || $_SESSION['login_type'] == 'super') {
    header("Location: dashboard.php");
    die();
  }
}

/* ----------------- State ----------------- */
$msg = false;
$cookie_name = "ams_lang_code";

/* ----------------- Handle POST (login) ----------------- */
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $data = post_input_serilization();
  if (!empty($data['username']) && !empty($data['password'])) {
    $user_name     = trim(make_safe($link, $data['username']));
    $user          = [];
    $authenticated = false;

    // Admin
    if (isset($data['ddlLoginType']) && $data['ddlLoginType'] === 'admin') {
      $stmt = $link->prepare("SELECT * FROM admins WHERE email = ?");
      $stmt->bind_param("s", $user_name);
      $stmt->execute();
      $res = $stmt->get_result();
      if ($res->num_rows === 1) {
        $user = $res->fetch_assoc();
        if (verify_password($data["password"], $user["password"])) {
          $authenticated = "admin";
        }
      }
    }

    // Super admin
    if (isset($data['ddlLoginType']) && $data['ddlLoginType'] === 'super') {
      $stmt = $link->prepare("SELECT * FROM tblsuper_admin WHERE email = ?");
      $stmt->bind_param("s", $user_name);
      $stmt->execute();
      $res = $stmt->get_result();
      if ($res->num_rows === 1) {
        $user = $res->fetch_assoc();
        if (verify_password($data["password"], $user["password"])) {
          $authenticated = "super";
        }
      }
    }

    if ($authenticated === "admin" || $authenticated === "super") {
      $_SESSION = array(
        'user_id'    => $user['user_id'],
        'name'       => $user['name'],
        'email'      => $user['email'],
        'contact'    => $user['contact'],
        'login_type' => $authenticated
      );
      $_SESSION["objLogin"] = $_SESSION;
      $link->close();
      header("Location: " . WEB_URL . 'dashboard.php');
      exit;
    } else {
      $msg = true;
    }
  }
}

/* ----------------- Helpers ----------------- */
function make_safe($con, $variable){
  return mysqli_real_escape_string($con, strip_tags(trim($variable)));
}

/* ----------------- Settings & Language ----------------- */
$query_ams_settings = mysqli_query($link,"SELECT * FROM settings");
if ($row = mysqli_fetch_array($query_ams_settings)) {
  $lang_code_global   = $row['lang_code'];
  $global_currency    = $row['currency'];
  $currency_position  = $row['currency_position'];
  $currency_sep       = $row['currency_seperator'];
}

$lang_code = "English";
if (isset($_COOKIE[$cookie_name]) && !empty($_COOKIE[$cookie_name])) {
  $lang_code        = $_COOKIE[$cookie_name];
  $lang_code_global = $_COOKIE[$cookie_name];
}

include_once(ROOT_PATH.'language/'.$lang_code_global.'/lang_index.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Zen Property Management System 2.0</title>

<!-- Keep your app CSS (this preserves your background image from custom.css) -->
<link href="assets/css/bootstrap.css" rel="stylesheet" />
<link href="assets/css/font-awesome.css" rel="stylesheet" />
<link href="assets/css/custom.css" rel="stylesheet" />
<link href="<?= WEB_URL; ?>assets/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

<!-- jQuery -->
<script src="<?= WEB_URL; ?>assets/js/jquery-3.5.1.js"></script>

<!-- Modern font -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;800&display=swap" rel="stylesheet">

<style>
  :root{
    --ink:#0b0b0b;
    --ink2:#111827;
    --muted:#6b7280;
    --line:#e5e7eb;
    --white:#ffffff;
    --off:#f7f7f7;
  }

  /* Maintain your background image (defined in assets/css/custom.css). Add subtle overlay for legibility. */
  body{
    min-height:100vh;
    margin:0;
    display:grid;
    place-items:center; /* center island layout */
    font-family:'Inter', system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif;
    color:#fff;
    overflow-x:hidden;
    text-align:center;
  }
  .bg-overlay{
    position:fixed; inset:0;
    background: radial-gradient(80% 60% at 50% 10%, rgba(0,0,0,.20), transparent 60%),
                linear-gradient(180deg, rgba(0,0,0,.55), rgba(0,0,0,.35) 45%, rgba(0,0,0,.25));
    pointer-events:none;
    z-index:0;
  }

  .auth-wrap{
    position:relative; z-index:1; width:100%;
    max-width:560px; padding:24px;
  }

  /* Brand */
  .brand{
    margin-bottom:16px;
    text-shadow:0 6px 28px rgba(0,0,0,.5);
  }
  .brand .logo{
    display:block;
    font-size:52px;
    font-weight:800;
    letter-spacing:.5px;
    line-height:1;
    /* Stylish grayscale gradient text */
    background: linear-gradient(90deg, #fff, #e5e7eb, #fff);
    -webkit-background-clip:text;
    background-clip:text;
    color:transparent;
  }
  .brand .sub{
    margin-top:6px;
    font-size:14px;
    letter-spacing:.35px;
    color:#e5e7eb;
  }

  /* Black & White Login Box */
  #loginBox.panel{
    margin:0 auto;
    border:none;
    border-radius:16px;
    overflow:hidden;
    /* box-shadow:0 24px 70px rgba(0,0,0,.55); */
    background:#fff;         /* white body */
    color:#111827;
  }
  /* Black header for strong contrast */
 #loginBox .panel-heading {
  background: #000 !important; /* black */
  color: #fff;                 /* white text */
  border: none;
  padding: 16px 18px;
  font-weight: 800;
  letter-spacing: 0.3px;
}
  
  #loginBox .panel-body{
    background: linear-gradient(180deg, #ffffff, #f7f7f7);
    padding:22px 22px 24px;
  }

  /* Inputs */
  .input-group{
    max-width:440px;
    margin:0 auto 10px;
    text-align:left;
  }
  .input-group-addon{
    background:#fff;
    border:1px solid var(--line);
    border-right:0;
    color:#6b7280;
    border-radius:12px 0 0 12px !important;
  }
  .form-control{
    height:46px;
    border:1px solid var(--line);
    border-left:0;
    border-radius:0 12px 12px 0 !important;
    box-shadow:none !important;
    color:#0f172a;
  }
  .form-control::placeholder{ color:#9aa3af; }

  /* Password toggle addon */
  .toggle-pass{
    background:#fff;
    border:1px solid var(--line);
    border-left:0;
    color:#111827;
    cursor:pointer;
    user-select:none;
    border-radius:0 12px 12px 0 !important;
  }

  /* User type (round radio “chips”) */
  .role-wrap{
    margin:10px auto 6px;
    display:flex; align-items:center; justify-content:center;
    gap:18px; flex-wrap:wrap;
  }
  .role-option{
    display:flex; align-items:center; gap:10px;
    cursor:pointer; user-select:none;
    padding:10px 14px;
    border:1px solid var(--line);
    border-radius:9999px;
    background:#fff;
    color:#111827;
    font-weight:700;
    min-width:140px;
    justify-content:center;
    transition: box-shadow .15s ease, transform .05s ease;
  }
  .role-option:hover{ box-shadow:0 10px 24px rgba(0,0,0,.08); }
  .role-option:active{ transform:translateY(1px); }
  .role-option input[type="radio"]{
    appearance:none; -webkit-appearance:none; -moz-appearance:none;
    position:relative; width:22px; height:22px;
    border:2px solid #111827; border-radius:50%;
    outline:none; display:inline-block;
  }
  .role-option input[type="radio"]::after{
    content:""; position:absolute; inset:3px; border-radius:50%;
    background:#111827; transform:scale(0); transition: transform .12s ease;
  }
  .role-option input[type="radio"]:checked::after{ transform:scale(1); }

  /* Monochrome primary button (BLACK instead of green) */
  .btn-login{
    display:inline-flex; align-items:center; justify-content:center; gap:8px;
    width:100%; max-width:440px; height:48px; margin:8px auto 0;
    border-radius:12px; font-weight:800; letter-spacing:.2px;
    color:#fff !important;
    background: linear-gradient(180deg,#1a1a1a,#0e0e0e);
    border:1px solid #0b0b0b;
    box-shadow:0 10px 28px rgba(0,0,0,.35);
    transition:filter .15s ease, transform .05s ease;
  }
  .btn-login:hover{ filter:brightness(1.05); }
  .btn-login:active{ transform:translateY(1px); }

  /* Forgot link */
  .link-light{ color:#111; }
  .link-light:hover{ text-decoration:underline; }

  /* Error toast */
  #login_error{
    background: rgba(220,38,38,.96);
    color:#fff;
    border-radius:12px;
    padding:10px 12px;
    margin:0 auto 12px;
    text-align:center;
    max-width:560px;
    box-shadow:0 12px 28px rgba(220,38,38,.35);
  }

  /* Footer notes under the login box */
  .rights{
    margin-top:10px;
    font-size:12px;
    color:#e5e7eb;
    letter-spacing:.25px;
  }
</style>
</head>
<body>
<div class="bg-overlay"></div>

<div class="auth-wrap">
  <!-- Brand (stylish) -->
  <div class="brand" aria-label="Zen Property Management System 2.0">
    <span class="logo">Zen Property Management System 2.0</span>
    <span class="sub">Secure access to your dashboard</span>
  </div>

  <!-- Error message -->
  <?php if ($msg) { ?>
    <div id="login_error" role="alert" aria-live="assertive">
      <?= $_data['wrong_login_msg']; ?>
    </div>
  <?php } ?>

  <!-- Login Card (black & white) -->
  <div class="panel" id="loginBox">
    <div class="panel-heading">
      <?= $_data['enter_login_details']; ?>
    </div>
    <div class="panel-body">
      <form onsubmit="return validationForm();" role="form" id="form" method="post" novalidate>
        <!-- Email -->
        <div class="form-group input-group">
          <span class="input-group-addon"><i class="fa fa-envelope-o" aria-hidden="true"></i></span>
          <label class="sr-only" for="username"><?= $_data['your_email']; ?></label>
          <input required type="email" name="username" autocomplete="email" id="username"
                 class="form-control" placeholder="<?= $_data['your_email']; ?>" />
        </div>

        <!-- Password with eye toggle (BLACK theme) -->
        <div class="form-group input-group">
          <span class="input-group-addon"><i class="fa fa-key" aria-hidden="true"></i></span>
          <label class="sr-only" for="password"><?= $_data['your_password']; ?></label>
          <input required type="password" name="password" autocomplete="current-password" id="password"
                 class="form-control" placeholder="<?= $_data['your_password']; ?>" />
          <span class="input-group-addon toggle-pass" id="togglePass" title="Show password" aria-label="Show password">
            <i class="fa fa-eye" aria-hidden="true"></i>
          </span>
        </div>

        <!-- User type (round radios) -->
        <div class="role-wrap" aria-label="<?= $_data['select_type']; ?>">
          <label class="role-option" for="role_admin">
            <input type="radio" id="role_admin" name="ddlLoginType" value="admin" />
            <span><?= $_data['user_1']; ?></span>
          </label>

        <label class="role-option" for="role_super">
            <input type="radio" id="role_super" name="ddlLoginType" value="super" />
            <span><?= $_data['user_5']; ?></span>
          </label>
        </div>

        <input type="hidden" name="ddlLanguage" value="English" />

        <div class="form-group" style="margin:8px 0 0;">
          <a class="link-light" href="<?= WEB_URL;?>forgetpassword.php"><?= $_data['forgot_password']; ?></a>
        </div>

        <hr style="max-width:440px; margin:16px auto;" />
        <button type="submit" id="login" class="btn btn-login">
          <i class="fa fa-sign-in"></i><span><?= $_data['_login']; ?></span>
        </button>
      </form>
    </div>
  </div>

  <!-- Rights line under the login box -->
  <div class="rights">© 2025 Zen PMS 2.0. All rights reserved.</div>
</div>

<script type="text/javascript">
function validationForm(){
  if($("#username").val().trim() === ''){
    alert("<?= $_data['v1'];?>");
    $("#username").focus();
    return false;
  }
  if($("#password").val().trim() === ''){
    alert("<?= $_data['v3'];?>");
    $("#password").focus();
    return false;
  }
  if(!$('input[name="ddlLoginType"]:checked').val()){
    alert("<?= $_data['v4'];?>");
    return false;
  }
  if(!validateEmail($("#username").val().trim())){
    alert("<?= $_data['v2'];?>");
    $("#username").focus();
    return false;
  }
  return true;
}
function validateEmail(email) {
  var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/i;
  return re.test(email);
}

// Password show/hide
(function(){
  var btn = document.getElementById('togglePass');
  var input = document.getElementById('password');
  if (!btn || !input) return;
  btn.addEventListener('click', function(){
    var isPwd = input.getAttribute('type') === 'password';
    input.setAttribute('type', isPwd ? 'text' : 'password');
    btn.setAttribute('aria-label', isPwd ? 'Hide password' : 'Show password');
    btn.title = isPwd ? 'Hide password' : 'Show password';
    btn.innerHTML = isPwd
      ? '<i class="fa fa-eye-slash" aria-hidden="true"></i>'
      : '<i class="fa fa-eye" aria-hidden="true"></i>';
  });
})();
</script>

<input type="hidden" id="web_url" value="<?= WEB_URL; ?>" />
</body>
</html>
