<?php include __DIR__ . '/includes/bootstrap.php'; ?>
<?php
include __DIR__ . '/includes/functions.php';
include __DIR__ . '/includes/json_utils.php';

$table_name = "user";

$superusername = getmodsbyid('1') ?? 'superadmin';
$superpassword = getmodsbyid('2') ?? 'superadmin';
$weblink       = getmodsbyid('3') ?? 'https://t.me/RTXshowcase';
$brandname     = getmodsbyid('4') ?? 'RTX Rebrands';

$icon32x32 = getmodsbyid('8')  ?? 'img/ficon/favicon-32x32.png';
$icon16x16 = getmodsbyid('9')  ?? 'img/ficon/favicon-16x16.png';
$iconaplle = getmodsbyid('10') ?? 'img/ficon/apple-touch-icon.png';
$iconmain  = getmodsbyid('11') ?? 'img/ficon/site.webmanifest';

// If already logged in as stored admin user, go straight in
$log_check    = $db->select($table_name, '*', 'id = :id', '', [':id' => 1]);
$loggedinuser = !empty($log_check) ? $log_check[0]['username'] : null;
if (!empty($loggedinuser) && isset($_SESSION['name']) && $_SESSION['name'] === $loggedinuser) {
    redirect('main.php');
    exit;
}

// Ensure a default admin user exists
$db->insertIfEmpty($table_name, ['id' => '1', 'username' => 'admin', 'password' => 'admin']);

$error = '';

if (isset($_POST['login'])) {
    // If captcha is enabled, verify first
    if (captcha_enabled($db) && !captcha_verify($db)) {
        $error = 'Captcha verification failed. Please try again.';
    } else {
        $username = (string)($_POST['username'] ?? '');
        $password = (string)($_POST['password'] ?? '');

        // 1) Superadmin
        if ($username === $superusername && $password === $superpassword) {
            if (session_status() !== PHP_SESSION_ACTIVE) { @session_start(); }
            session_regenerate_id(true);
            $_SESSION['loggedin']     = true;
            $_SESSION['name']         = $username;
            $_SESSION['passwordxyz']  = $password;
            redirect('admin.php');
            exit;
        }

        // 2) DB user
        $userData = $db->select($table_name, '*', 'username = :username', '', [':username' => $username]);
        if ($userData && $password === ($userData[0]['password'] ?? '')) {
            if (session_status() !== PHP_SESSION_ACTIVE) { @session_start(); }
            session_regenerate_id(true);
            $_SESSION['loggedin']     = true;
            $_SESSION['name']         = $username;
            $_SESSION['passwordxyz']  = $password;
            redirect(($username === 'admin') ? 'user.php' : 'main.php');
            exit;
        } else {
            // Stay on the page and show an error (no redirect to /api/index.php)
            $error = 'Invalid username or password.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<meta name="author" content="<?php echo htmlspecialchars($brandname); ?>">

	<link rel="apple-touch-icon" sizes="180x180" href="<?php echo $iconaplle ?>">
	<link rel="icon" type="image/png" sizes="32x32" href="<?php echo $icon32x32 ?>">
	<link rel="icon" type="image/png" sizes="16x16" href="<?php echo $icon16x16 ?>">
	<link rel="manifest" href="<?php echo $iconmain ?>">

	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
	<link rel="stylesheet" href="./css/css.css">
	<title><?php echo htmlspecialchars($brandname); ?></title>

    <?php if (captcha_enabled($db)): ?>
      <!-- Google reCAPTCHA v2 (dark theme) -->
      <script src="https://www.google.com/recaptcha/api.js" async defer></script>
    <?php endif; ?>
</head>
<style>
*{margin:0;padding:0;box-sizing:border-box;font-family:'Poppins',sans-serif}
body{display:flex;justify-content:center;align-items:center;min-height:100vh;background:#131419}
.form{position:relative;width:350px;padding:40px 40px 60px;background:#131419;border-radius:10px;text-align:center;box-shadow:-5px -5px 10px rgba(255,255,255,.05),5px 5px 15px rgba(0,0,0,.5)}
.form h2{color:#c7c7c7;font-weight:500;text-transform:uppercase;letter-spacing:4px}
.form .input{text-align:left;margin-top:40px}
.form .input .inputBox{margin-top:20px}
.form .input .inputBox label{display:block;color:#868686;margin-bottom:5px;font-size:18px}
.form .input .inputBox input{width:100%;height:50px;background:#131419;border:none;outline:none;border-radius:40px;padding:5px 15px;color:#03a9f4;font-size:18px;box-shadow:inset -2px -2px 6px rgba(255,255,255,.1), inset 2px 2px 6px rgba(0,0,0,.8)}
.form .input .inputBox input[type="submit"]{margin-top:20px;box-shadow:-2px -2px 6px rgba(255,255,255,.1), 2px 2px 6px rgba(0,0,0,.8)}
.form .input .inputBox input[type="submit"]:active{color:#006c9c;margin-top:20px;box-shadow:inset -2px -2px 6px rgba(255,255,255,.1), inset 2px 2px 6px rgba(0,0,0,.8)}
.form .input .inputBox input::placeholder{color:#555;font-size:18px}
.forget{margin-top:30px;color:#555}
.forget a{color:#ff0047}
</style>

<br><br>
<div class="form">
  <h2>Login</h2>

  <?php if (!empty($error)): ?>
    <div class="alert alert-danger py-2 px-3 mt-3" role="alert">
      <?php echo htmlspecialchars($error); ?>
    </div>
  <?php endif; ?>

  <form method="post" autocomplete="off">
    <div class="input">
      <div class="inputBox">
        <label>Username</label>
        <input type="text" name="username" placeholder="Username" autocomplete="username">
      </div>
      <div class="inputBox">
        <label>Password</label>
        <input type="password" name="password" placeholder="&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;" autocomplete="current-password">
      </div>

      <?php if (captcha_enabled($db)): ?>
        <div class="mb-3 mt-3" style="display:flex;justify-content:center;">
          <div class="g-recaptcha"
               data-sitekey="<?php echo htmlspecialchars(captcha_site_key($db), ENT_QUOTES, 'UTF-8'); ?>"
               data-theme="dark"></div>
        </div>
      <?php endif; ?>

      <div class="inputBox">
        <input type="submit" name="login" value="LOGIN"/>
      </div>
    </div>
  </form>

  <p class="forget"><a href="<?php echo $weblink; ?>"><?php echo htmlspecialchars($brandname); ?></a></p>
</div>
<br><br>

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>
