<?php require_once('../setup.php'); ?>
<?php
session_start();
ob_start();
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
 <title>Login | <?= $main_name; ?> Secure Online Banking</title>

<meta name="description" content="Access your <?= $main_name; ?> secure online banking account. Manage transactions, view balances, and control your finances safely.">

<meta name="author" content="<?= $main_name; ?>">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta name="robots" content="noindex, nofollow">

<!-- Open Graph -->
<meta property="og:title" content="Login | <?= $main_name; ?> Online Banking">
<meta property="og:description" content="Secure login portal for <?= $main_name; ?> customers. Access your account safely and efficiently.">
<meta property="og:type" content="website">
<meta property="og:url" content="<?= $main_website ?>/login">
<meta property="og:image" content="<?= $main_website ?>/assets/images/og-image.jpg">

<link rel="canonical" href="<?= $main_website ?>/login">
  <!-- plugins:css -->
  <link rel="stylesheet" href="vendors/feather/feather.css">
  <link rel="stylesheet" href="vendors/ti-icons/css/themify-icons.css">
  <link rel="stylesheet" href="vendors/css/vendor.bundle.base.css">
  <!-- endinject -->
  <!-- Plugin css for this page -->
  <!-- End plugin css for this page -->
  <!-- inject:css -->
  <link rel="stylesheet" href="css/vertical-layout-light/style.css">
  <!-- endinject -->
  <link rel="shortcut icon" href="../assets/images/logo.png" />
</head>

<body>
  <div class="container-scroller">
    <div class="container-fluid page-body-wrapper full-page-wrapper">
      <div class="content-wrapper d-flex align-items-center auth px-0">
        <div class="row w-100 mx-0">
          <div class="col-lg-4 mx-auto">
            <div class="auth-form-light text-left py-5 px-4 px-sm-5">
              <div class="brand-logo">
                <img src="../assets/images/logo.png" style="width: 50px; display: block; margin-left: auto; margin-right: auto;" alt="logo">
              </div>
              <h4 class="text-center"><?= $main_capital_name; ?></h4>
              <h6 class="font-weight-light text-center"> <small><b>Hello! let's get started</b><br>Log In to continue.</small></h6>
              <hr>
              <div class="row">
                <div class="col-md-12">
                  <?php
                  if (isset($_POST['login'])) {
                      require_once("conn.php");

                      // Make sure session is available (keeps your existing $_SESSION usage working)
                      if (session_status() !== PHP_SESSION_ACTIVE) {
                          session_start();
                      }

                      // Basic input cleanup (same parameters: username + password)
                      $username = trim($_POST['username'] ?? '');
                      $password = (string)($_POST['password'] ?? '');

                      if ($username === '' || $password === '') {
                          echo '<div align="center" class="alert alert-danger">Please enter your username and password.</div>';
                          return;
                      }

                      // Helper: supports BOTH hashed passwords and legacy plain-text passwords
                      $verifyPassword = function (string $inputPassword, string $storedPassword): bool {
                          // If stored password looks like a modern hash, verify properly
                          $info = password_get_info($storedPassword);
                          if (!empty($info['algo'])) {
                              return password_verify($inputPassword, $storedPassword);
                          }
                          // Legacy fallback (keeps compatibility with your current DB)
                          return hash_equals($storedPassword, $inputPassword);
                      };

                      // ===== 1) Admin login (keeps your existing admin_pass table logic) =====
                      $dbadminpass = null;

                      if ($stmt = $dbconfig->prepare("SELECT password FROM admin_pass LIMIT 1")) {
                          if ($stmt->execute()) {
                              $res = $stmt->get_result();
                              if ($res && $res->num_rows > 0) {
                                  $dbadminpass = (string)$res->fetch_assoc()['password'];
                              }
                          }
                          $stmt->close();
                      }

                      if ($username === 'admin' && $dbadminpass !== null && $verifyPassword($password, $dbadminpass)) {
                          // Better session hygiene
                          session_regenerate_id(true);

                          date_default_timezone_set("Africa/Lagos");
                          $randdate = date('dmyhis');

                          // Stronger random hash (still keeps $_SESSION['hash'] behavior)
                          $hash = $randdate . bin2hex(random_bytes(16));
                          $_SESSION['hash'] = $hash;

                          // Keep your existing UX (message + timed redirect)
                          header("Refresh: 3; url=controls/florence");
                          echo '<div align="center" class="alert alert-success"><b>Welcome Back Admin</b> <br>Redirecting, Please wait...</div>';
                          exit();
                      }

                      // ===== 2) Customer login =====
                      $row = null;

                      if ($stmt = $dbconfig->prepare("SELECT id, username, password, status FROM accounts WHERE username = ? LIMIT 1")) {
                          $stmt->bind_param("s", $username);
                          if ($stmt->execute()) {
                              $res = $stmt->get_result();
                              if ($res && $res->num_rows === 1) {
                                  $row = $res->fetch_assoc();
                              }
                          }
                          $stmt->close();
                      }

                      if (!$row) {
                          echo '<div align="center" class="alert alert-danger">Incorrect Login Details</div>';
                          return;
                      }

                      $dbstatus   = (string)$row['status'];
                      $dbusername = (string)$row['username'];
                      $dbpassword = (string)$row['password'];

                      if ($dbstatus === 'disabled') {
                          echo '<div align="center" class="alert alert-danger"><b>Account Disabled!</b><br>Kindly Contact An Administrator.</div>';
                          return;
                      }

                      if ($dbstatus === 'pending') {
                          echo '<div align="center" class="alert alert-danger"><b>Pending Account!</b><br>Your account is currently awaiting approval.</div>';
                          return;
                      }

                      // Validate credentials (supports hashed + legacy plain)
                      if ($dbusername === $username && $verifyPassword($password, $dbpassword)) {
                          // Keep your existing flow: base64 id -> authenticate?i=
                          $id = base64_encode((string)$row['id']);

                          // Optional: session hardening, doesn’t break your existing project
                          session_regenerate_id(true);

                          header("Refresh: 2; url=authenticate?i=$id");
                          echo '<div align="center" class="alert alert-success"><b>SUCCESSFUL!</b><br>Redirecting, Please wait...</div>';
                          exit();
                      }

                      echo '<div align="center" class="alert alert-danger">Incorrect Login Details</div>';
                  }
                  ?>
                </div>
              </div>
              <form class="pt-3" action="" method="POST">
                <div class="form-group">
                  <input type="text" class="form-control form-control-lg" id="exampleInputEmail1" placeholder="Username" name="username" maxlength="100" value="<?php if (isset($_GET['u'])) {
                                                                                                                                                                  echo base64_decode($_GET['u']);
                                                                                                                                                                } ?>" required>
                </div>
                <div class="form-group">
                  <input type="password" class="form-control form-control-lg" id="exampleInputPassword1" placeholder="Password" name="password" maxlength="50" required>
                </div>
                <div class="mt-3">
                  <button type="submit" name="login" class="btn btn-block btn-primary btn-lg font-weight-medium auth-form-btn">LOG IN</button>
                </div>
                <div class="my-2 d-flex justify-content-between align-items-center">
                  <div class="form-check">
                    <label class="form-check-label text-muted">
                      <input type="checkbox" class="form-check-input">
                      Keep me signed in
                    </label>
                  </div>
                </div>
                <div class="text-center mt-4 font-weight-light">
                  Don't have an account? <a href="register" class="text-primary">Create</a>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
      <!-- content-wrapper ends -->
    </div>
    <!-- page-body-wrapper ends -->
  </div>
  <!-- container-scroller -->
  <!-- plugins:js -->
  <script src="vendors/js/vendor.bundle.base.js"></script>
  <!-- endinject -->
  <!-- Plugin js for this page -->
  <!-- End plugin js for this page -->
  <!-- inject:js -->
  <script src="js/off-canvas.js"></script>
  <script src="js/hoverable-collapse.js"></script>
  <script src="js/template.js"></script>
  <script src="js/settings.js"></script>
  <script src="js/todolist.js"></script>
  <!-- endinject -->
  <?php include('../chat.php'); ?>
</body>

</html>
