<?php
ob_start();
session_start();

include_once("config.php");
include_once("library/encryption.php");

$converter = new Encryption;

/* ------------- Small helpers ------------- */
function e($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function make_safe($con, $variable){
  return mysqli_real_escape_string($con, strip_tags(trim((string)$variable)));
}
function loadForgotEmailTemplate($temp_name, $variables = array()) {
  $template = file_get_contents(ROOT_PATH."partial/email_templates/".$temp_name);
  foreach($variables as $key => $value){
    $template = str_replace('{{ '.$key.' }}', $value, $template);
  }
  return $template;
}

/* ------------- CSRF token ------------- */
if (empty($_SESSION['csrf_token'])) {
  $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

/* ------------- Settings & language ------------- */
$lang_code_global  = "English";
$global_currency   = "$";
$currency_position = "left";
$currency_sep      = ".";

$_data = []; // language strings container

$query_ams_settings = mysqli_query($link,"SELECT * FROM settings");
if($row_query_ams_core = mysqli_fetch_array($query_ams_settings)){
  $lang_code_global  = $row_query_ams_core['lang_code'] ?: $lang_code_global;
  $global_currency   = $row_query_ams_core['currency'] ?: $global_currency;
  $currency_position = $row_query_ams_core['currency_position'] ?: $currency_position;
  $currency_sep      = $row_query_ams_core['currency_seperator'] ?: $currency_sep;
}

$lang_file = ROOT_PATH.'language/'.$lang_code_global.'/lang_index.php';
if (file_exists($lang_file)) {
  include_once($lang_file);
} else {
  $fallback = ROOT_PATH.'language/English/lang_index.php';
  if (file_exists($fallback)) include_once($fallback);
}

/* ------------- State for error toast ------------- */
$show_msg  = false;             // whether to render the toast
$msg_class = 'error';           // 'success' | 'error' (we'll only show error because success redirects)
$xMsg = isset($_data['no_info_found']) ? $_data['no_info_found'] : 'No information found in our database.';

/* ------------- Handle POST ------------- */
if($_SERVER['REQUEST_METHOD'] === 'POST'){
  $csrf_ok  = isset($_POST['csrf_token']) && hash_equals($_SESSION['csrf_token'], (string)$_POST['csrf_token']);
  $has_user = isset($_POST['username']) && !empty($_POST['username']);
  $has_role = isset($_POST['ddlLoginType']) && ($_POST['ddlLoginType'] === '1' || $_POST['ddlLoginType'] === '5');

  if ($csrf_ok && $has_user && $has_role){
    $user_name = make_safe($link, $_POST['username']); // Escaping Strings

    $password = '';
    $name     = '';

    if($_POST['ddlLoginType'] === '1'){
      // admin
      if ($stmt = $link->prepare("SELECT password, name FROM admins WHERE email = ?")) {
        $stmt->bind_param("s", $user_name);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($row = $res->fetch_assoc()) {
          $password = $converter->decode($row['password']);
          $name     = $row['name'];
        }
        $stmt->close();
      }
    }
    else if($_POST['ddlLoginType'] === '5'){
      // super admin
      if ($stmt = $link->prepare("SELECT password, name FROM tblsuper_admin WHERE email = ?")) {
        $stmt->bind_param("s", $user_name);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($row = $res->fetch_assoc()) {
          $password = $converter->decode($row['password']);
          $name     = $row['name'];
        }
        $stmt->close();
      }
    }

    if(!empty($password)){
      // SUCCESS PATH: email exists — send email, then redirect to login
      $replyEmail = null;
      $query_set = mysqli_query($link, "SELECT email FROM tblsuper_admin LIMIT 1");
      if($row = mysqli_fetch_assoc($query_set)){
        $replyEmail = $row['email'];
      }
      if (!$replyEmail) { $replyEmail = 'no-reply@'.parse_url(WEB_URL, PHP_URL_HOST); }

      $to       = trim($_POST['username']);
      $subject  = 'User Login Details';
      $headers  = "From: " . strip_tags($replyEmail) . "\r\n";
      $headers .= "Reply-To: ". strip_tags($replyEmail) . "\r\n";
      $headers .= "MIME-Version: 1.0\r\n";
      $headers .= "Content-Type: text/html; charset=UTF-8\r\n";

      // Preserve original behavior
      $variables = array(
        'subject'   => $subject,
        'message'   => true,
        'site_url'  => WEB_URL,
        'user_name' => $_POST['username'],
        'password'  => $password,
        'name'      => $name
      );

      $message = loadForgotEmailTemplate('tmp_forget.html', $variables);
      @mail($to, $subject, $message, $headers);

      // Optional: set a one-time flag to show a message on the login page (if you later want to use it)
      $_SESSION['reset_notice'] = 'Superadmin will reset your password.';

      // Redirect to login page
      header("Location: " . WEB_URL . "index.php");
      exit;
    } else {
      // ERROR PATH: not found
      $show_msg  = true;
      $msg_class = 'error';
      $xMsg = isset($_data['no_info_found']) ? $_data['no_info_found'] : 'No information found in our database.';
    }
  } else {
    // ERROR PATH: invalid submission
    $show_msg  = true;
    $msg_class = 'error';
    $xMsg = isset($_data['no_info_found']) ? $_data['no_info_found'] : 'No information found in our database.';
  }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title><?= e(isset($_data['application_title']) ? $_data['application_title'] : 'Zen Property Management System 2.0'); ?></title>

<!-- Keep your app CSS (preserves background 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>

<!-- Inter 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;
    --success:#10b981; --error:#dc2626;
  }
  /* Background image remains from assets/css/custom.css; overlay for legibility */
  body{
    min-height:100vh; margin:0; display:grid; place-items:center;
    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:48px; font-weight:800; letter-spacing:.5px; line-height:1;
    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; }

  /* Card */
  #loginBox.panel{
    margin:0 auto; border:none; border-radius:16px; overflow:hidden;
    background:#fff; color:#111827;
  }
  #loginBox .panel-heading {
    background:#000 !important; color:#fff; border:none; padding:16px 18px;
    font-weight:800; letter-spacing:.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; }

  /* Buttons */
  .btn-primary-modern{
    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-primary-modern:hover{ filter:brightness(1.05); }
  .btn-primary-modern:active{ transform:translateY(1px); }

  .btn-secondary-modern{
    display:inline-flex; align-items:center; justify-content:center; gap:8px;
    width:100%; max-width:440px; height:44px; margin:6px auto 0;
    border-radius:12px; font-weight:700; letter-spacing:.2px;
    color:#111827 !important; background:#fff; border:1px solid var(--line);
    box-shadow:0 6px 16px rgba(0,0,0,.08);
  }
  .btn-secondary-modern:hover{ box-shadow:0 10px 22px rgba(0,0,0,.12); }

  /* Toasts */
  .toast{
    border-radius:12px; padding:10px 12px; margin:0 auto 12px; text-align:center;
    max-width:560px; color:#fff; box-shadow:0 12px 28px rgba(0,0,0,.25);
  }
  .toast.success{ background: var(--success); box-shadow:0 12px 28px rgba(16,185,129,.35); }
  .toast.error{ background: var(--error); box-shadow:0 12px 28px rgba(220,38,38,.35); }

  .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 -->
  <div class="brand" aria-label="Zen Property Management System 2.0">
    <span class="logo">Zen Property Management System 2.0</span>
    <span class="sub"><?= e(isset($_data['forgot_your_password']) ? $_data['forgot_your_password'] : 'Forgot your password'); ?></span>
  </div>

  <!-- Toast Message (only shows for errors; success redirects) -->
  <?php if($show_msg) { ?>
    <div class="toast <?= $msg_class === 'success' ? 'success' : 'error' ?>" role="alert" aria-live="assertive">
      <?= e($xMsg); ?>
    </div>
  <?php } ?>

  <!-- Card -->
  <div class="panel" id="loginBox">
    <div class="panel-heading">
      <?= e(isset($_data['forgot_your_password']) ? $_data['forgot_your_password'] : 'Forgot your password'); ?>
    </div>
    <div class="panel-body">
      <form role="form" id="form" method="post" onsubmit="return validationForm();" novalidate>
        <input type="hidden" name="csrf_token" value="<?= e($_SESSION['csrf_token']); ?>"/>

        <!-- 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"><?= e(isset($_data['your_email']) ? $_data['your_email'] : 'Your email'); ?></label>
          <input type="email" name="username" id="username" class="form-control"
                 placeholder="<?= e(isset($_data['your_email']) ? $_data['your_email'] : 'Your email'); ?>" required />
        </div>

        <!-- Role -->
        <div class="form-group input-group">
          <span class="input-group-addon"><i class="fa fa-users" aria-hidden="true"></i></span>
          <label class="sr-only" for="ddlLoginType"><?= e(isset($_data['select_type']) ? $_data['select_type'] : 'Select type'); ?></label>
          <select name="ddlLoginType" id="ddlLoginType" class="form-control" required>
            <option value="">--<?= e(isset($_data['select_type']) ? $_data['select_type'] : 'Select type'); ?>--</option>
            <option value="1"><?= e(isset($_data['user_1']) ? $_data['user_1'] : 'Admin'); ?></option>
            <option value="5"><?= e(isset($_data['user_5']) ? $_data['user_5'] : 'Super Admin'); ?></option>
          </select>
        </div>

        <hr style="max-width:440px; margin:16px auto;" />

        <!-- Submit -->
        <div class="form-group">
          <button type="submit" id="login" class="btn btn-primary-modern">
            <i class="fa fa-paper-plane" aria-hidden="true"></i>
            <span><?= e(isset($_data['btn_submit']) ? $_data['btn_submit'] : 'Submit'); ?></span>
          </button>
        </div>

        <!-- Back -->
        <div class="form-group">
          <a class="btn btn-secondary-modern" href="<?= WEB_URL;?>index.php">
            <i class="fa fa-reply" aria-hidden="true"></i>
            <span><?= e(isset($_data['btn_back_login']) ? $_data['btn_back_login'] : 'Back to login'); ?></span>
          </a>
        </div>
      </form>
    </div>
  </div>

  <div class="rights">© 2025 Zen PMS 2.0. All rights reserved.</div>
</div>

<script type="text/javascript">
function validationForm(){
  var email = document.getElementById('username');
  var role  = document.getElementById('ddlLoginType');

  if(!email || !role) return true;

  if(email.value.trim() === ''){
    alert("<?= e(isset($_data['your_email']) ? $_data['your_email'] : 'Your email'); ?>");
    email.focus(); return false;
  }
  if(role.value.trim() === ''){
    alert("<?= e(isset($_data['select_type']) ? $_data['select_type'] : 'Select type'); ?>");
    role.focus(); return false;
  }
  if(!validateEmail(email.value.trim())){
    alert("<?= e(isset($_data['v2']) ? $_data['v2'] : 'Please enter a valid email'); ?>");
    email.focus(); return false;
  }
  return true;
}
function validateEmail(email){
  var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/i;
  return re.test(email);
}
</script>

</body>
</html>
