<?php



session_start();
require_once "db_connect.php"; // DB connection file
$website = "https://abc.xyz/";
// Security: Limit login attempts
if (!isset($_SESSION['login_attempts'])) {
    $_SESSION['login_attempts'] = 0;
}
$max_attempts = 5;
$lockout_time = 300; // 5 minutes

if (isset($_SESSION['last_attempt']) && (time() - $_SESSION['last_attempt'] < $lockout_time) && $_SESSION['login_attempts'] >= $max_attempts) {
    die("Too many failed attempts. Please try again after 5 minutes.");
}

$error = "";

// Generate CSRF Token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}


// Check if user already logged in
if (isset($_SESSION['staff_logged_in']) && $_SESSION['staff_logged_in'] === true) {
    header("Location: " . $website . strtolower($_SESSION['staff_role']) . "-dashboard.php");
    exit;
}

// Check Remember Me cookie if session not active
if (!isset($_SESSION['staff_logged_in']) && isset($_COOKIE['remember_me'])) {
    $cookie_token = $_COOKIE['remember_me'];

    $sql = "SELECT staff_id, staff_username, staff_role, remember_token, remember_expiry FROM staff WHERE remember_token IS NOT NULL";
    $result = $conn->query($sql);

    while ($row = $result->fetch_assoc()) {
        // Verify token hash
        if (password_verify($cookie_token, $row['remember_token']) && strtotime($row['remember_expiry']) > time()) {
            // Auto-login
            session_regenerate_id(true);
            $_SESSION['staff_logged_in'] = true;
            $_SESSION['staff_id'] = $row['staff_id'];
            $_SESSION['staff_username'] = $row['staff_username'];
            $_SESSION['staff_role'] = $row['staff_role'];

            header("Location: " . $website . strtolower($_SESSION['staff_role']) . "-dashboard.php");
            exit;
        }
    }
}


?>
<!doctype html>
<html lang="en">
  <head>
    <!-- Meta tags  -->
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta
      name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
    />

    <title>Lineone - Sign In v2</title>
    <link rel="icon" type="image/png" href="images/favicon.png" />

    <!-- CSS Assets -->
    <link rel="stylesheet" href="css/app.css" />

    <!-- Javascript Assets -->
    <script src="js/app.js" defer></script>

    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Poppins:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&display=swap"
      rel="stylesheet"
    />
    <script>
      /**
       * THIS SCRIPT REQUIRED FOR PREVENT FLICKERING IN SOME BROWSERS
       */
      localStorage.getItem("_x_darkMode_on") === "true" &&
        document.documentElement.classList.add("dark");
    </script>
  </head>
  <body x-data class="is-header-blur" x-bind="$store.global.documentBody">
    <!-- App preloader-->
    <div
      class="app-preloader fixed z-50 grid h-full w-full place-content-center bg-slate-50 dark:bg-navy-900"
    >
      <div class="app-preloader-inner relative inline-block size-48"></div>
    </div>

    <!-- Page Wrapper -->
    <div
      id="root"
      class="min-h-100vh flex grow bg-slate-50 dark:bg-navy-900"
      x-cloak
    >
      <div class="fixed top-0 hidden p-6 lg:block lg:px-12">
        <a href="#" class="flex items-center space-x-2">
          <img class="size-12" src="images/app-logo.svg" alt="logo" />
          <p
            class="text-xl font-semibold uppercase text-slate-700 dark:text-navy-100"
          >
            lineone
          </p>
        </a>
      </div>
      <div class="hidden w-full place-items-center lg:grid">
        <div class="w-full max-w-lg p-6">
          <img
            class="w-full"
            x-show="!$store.global.isDarkModeEnabled"
            src="images/illustrations/dashboard-check.svg"
            alt="image"
          />
          <img
            class="w-full"
            x-show="$store.global.isDarkModeEnabled"
            src="images/illustrations/dashboard-check-dark.svg"
            alt="image"
          />
        </div>
      </div>
      <main
        class="flex w-full flex-col items-center bg-white dark:bg-navy-700 lg:max-w-md"
      >
        <div class="flex w-full max-w-sm grow flex-col justify-center p-5">
          <div class="text-center">
            <img
              class="mx-auto size-16 lg:hidden"
              src="images/app-logo.svg"
              alt="logo"
            />
            <div class="mt-4">
              <h2
                class="text-2xl font-semibold text-slate-600 dark:text-navy-100"
              >
                Welcome Back
              </h2>
              <p class="text-slate-400 dark:text-navy-300">
                Please sign in to continue
              </p>
            </div>
          </div><form method="post">
          <input type="hidden" name="login_form" value="1">
          <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
          <div class="mt-16">
            <label class="relative flex">
              <input
                class="form-input peer w-full rounded-lg bg-slate-150 px-3 py-2 pl-9 ring-primary/50 placeholder:text-slate-400 hover:bg-slate-200 focus:ring-3 dark:bg-navy-900/90 dark:ring-accent/50 dark:placeholder:text-navy-300 dark:hover:bg-navy-900 dark:focus:bg-navy-900"
                placeholder="Username"
                type="text"
                name="username"
              />
              <span
                class="pointer-events-none absolute flex h-full w-10 items-center justify-center text-slate-400 peer-focus:text-primary dark:text-navy-300 dark:peer-focus:text-accent"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  class="size-5 transition-colors duration-200"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="1.5"
                    d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
                  />
                </svg>
              </span>
            </label>
            <label class="relative mt-4 flex">
              <input
                class="form-input peer w-full rounded-lg bg-slate-150 px-3 py-2 pl-9 ring-primary/50 placeholder:text-slate-400 hover:bg-slate-200 focus:ring-3 dark:bg-navy-900/90 dark:ring-accent/50 dark:placeholder:text-navy-300 dark:hover:bg-navy-900 dark:focus:bg-navy-900"
                placeholder="Password"
                type="password"
                name="password" 
              />
              <span
                class="pointer-events-none absolute flex h-full w-10 items-center justify-center text-slate-400 peer-focus:text-primary dark:text-navy-300 dark:peer-focus:text-accent"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  class="size-5 transition-colors duration-200"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="1.5"
                    d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
                  />
                </svg>
              </span>
            </label>
            <div class="mt-4 flex items-center justify-between space-x-2">
              <label class="inline-flex items-center space-x-2">
                <input
                  class="form-checkbox is-outline size-5 rounded-sm border-slate-400/70 bg-slate-100 before:bg-primary checked:border-primary hover:border-primary focus:border-primary dark:border-navy-500 dark:bg-navy-900 dark:before:bg-accent dark:checked:border-accent dark:hover:border-accent dark:focus:border-accent"
                  type="checkbox"
                  name="remember_me"
                />
                <span class="line-clamp-1">Remember me</span>
              </label>
              <a
                href="#"
                class="text-xs text-slate-400 transition-colors line-clamp-1 hover:text-slate-800 focus:text-slate-800 dark:text-navy-300 dark:hover:text-navy-100 dark:focus:text-navy-100"
                >Forgot Password?</a
              >
            </div>
            <button
              class="btn mt-10 h-10 w-full bg-primary font-medium text-white hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90 dark:bg-accent dark:hover:bg-accent-focus dark:focus:bg-accent-focus dark:active:bg-accent/90"
            type="submit" 
            >
              Sign In
            </button>
            <div class="mt-4 text-center text-xs-plus">
              <p class="line-clamp-1">
                <span>Dont have Account?</span>

                <a
                  class="text-primary transition-colors hover:text-primary-focus dark:text-accent-light dark:hover:text-accent"
                  href="pages-singup-2.html"
                  >Create account</a
                >
              </p>
            </div>
            <div class="my-7 flex items-center space-x-3">
              <div class="h-px flex-1 bg-slate-200 dark:bg-navy-500"></div>
              <p>OR</p>
              <div class="h-px flex-1 bg-slate-200 dark:bg-navy-500"></div>
            </div>
            <div class="flex space-x-4">
              <button
                class="btn w-full space-x-3 border border-slate-300 font-medium text-slate-800 hover:bg-slate-150 focus:bg-slate-150 active:bg-slate-150/80 dark:border-navy-450 dark:text-navy-50 dark:hover:bg-navy-500 dark:focus:bg-navy-500 dark:active:bg-navy-500/90"
              >
                <img
                  class="size-5.5"
                  src="images/logos/google.svg"
                  alt="logo"
                />
                <span>Google</span>
              </button>
              <button
                class="btn w-full space-x-3 border border-slate-300 font-medium text-slate-800 hover:bg-slate-150 focus:bg-slate-150 active:bg-slate-150/80 dark:border-navy-450 dark:text-navy-50 dark:hover:bg-navy-500 dark:focus:bg-navy-500 dark:active:bg-navy-500/90"
              >
                <img
                  class="size-5.5"
                  src="images/logos/github.svg"
                  alt="logo"
                />
                <span>Github</span>
              </button>
            </div>
          </div></form>
        </div>
        <div
          class="my-5 flex justify-center text-xs text-slate-400 dark:text-navy-300"
        >
          <a href="#">Privacy Notice</a>
          <div class="mx-3 my-1 w-px bg-slate-200 dark:bg-navy-500"></div>
          <a href="#">Term of service</a>
        </div>
      </main>
    </div>
            <?php if ($error) echo "<p style='color:red;'>$error</p>"; ?>
<?php






// Handle Login Form
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['login_form'])) {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $remember = isset($_POST['remember_me']);

    $sql = "SELECT staff_id, staff_username, staff_password, staff_role FROM staff WHERE staff_username=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $stmt->bind_result($staff_id, $staff_username, $hashed_password, $staff_role);
        $stmt->fetch();

        if (password_verify($password, $hashed_password)) {
            // Set session
            session_regenerate_id(true);
            $_SESSION['staff_logged_in'] = true;
            $_SESSION['staff_id'] = $staff_id;
            $_SESSION['staff_username'] = $staff_username;
            $_SESSION['staff_role'] = $staff_role;

            // Handle Remember Me
            if ($remember) {
                $token = bin2hex(random_bytes(32));  // Random token
                $hashed_token = password_hash($token, PASSWORD_DEFAULT); // Hash for DB
                $expiry = date('Y-m-d H:i:s', strtotime('+30 days'));

                // Save to DB
                $update = $conn->prepare("UPDATE staff SET remember_token=?, remember_expiry=? WHERE staff_id=?");
                $update->bind_param("ssi", $hashed_token, $expiry, $staff_id);
                $update->execute();

                // Save to cookie
                setcookie('remember_me', $token, time() + (86400*30), "/", "", isset($_SERVER['HTTPS']), true);
            }

            // Redirect to role-based dashboard
        header("Location: " . $website . strtolower($_SESSION['staff_role']) . "-dashboard.php");
            exit;
        } else {
            $error = "Invalid username or password.";
        }
    } else {
        $error = "Invalid username or password.";
    }
}
?>





    <!-- 
        This is a place for Alpine.js Teleport feature 
        @see https://alpinejs.dev/directives/teleport
      -->
    <div id="x-teleport-target"></div>
    <script>
      window.addEventListener("DOMContentLoaded", () => Alpine.start());
    </script>
  </body>
</html>