<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Admin Login</title>
  <link rel="stylesheet" href="/css/main.css">
  <script>
    document.addEventListener('DOMContentLoaded', function() {
      document.title = '<%= title %>' || 'Default Title';

      (function setFavicon() {
        const link = document.querySelector("link[rel~='icon']") || document.createElement('link');
        link.rel = 'icon';
        link.href = '<%= favicon %>'; // or your actual favicon path
        document.head.appendChild(link);
      })();
    });
  </script>
    <style>
  body {
    /* Background image setup */
    background: url('/bg.jpg') no-repeat center center fixed;
    background-size: cover;
    background-attachment: fixed;
    background-position: center;
    background-repeat: no-repeat;

    /* Optional: overlay effect for readability */
    position: relative;
  }

  /* Optional overlay to darken/lighten image */
  body::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.35); /* dark overlay for contrast */
    z-index: 0;
  }

  /* Ensure your login card sits above the overlay */
  body > .w-full {
    position: relative;
    z-index: 1;
  }

  /* Optional shadow + transparency for the login box */
  .bg-white {
    background-color: rgba(255, 255, 255, 0.9) !important;
    backdrop-filter: blur(8px);
  }
</style>

  <!-- SweetAlert2 -->
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>

<body class="flex items-center justify-center min-h-screen bg-gray-100">
  <div class="w-full max-w-md p-8 rounded-xl shadow-xl bg-white transition duration-300">

    <!-- Logo -->
    <div class="flex justify-center mb-4">
<img src="<%= login_logo || '/logo.png' %>" 
     alt="Logo" 
     class="w-auto" 
     style="object-fit: contain; height: 140px; max-width: 70%;"
     onerror="this.onerror=null; this.src='/logo.png';">
    </div>

    <h2 class="text-xl font-bold text-center text-gray-800 mb-6">Admin</h2>

    <form id="loginForm" class="space-y-5">
      <div>
        <label for="email" class="block mb-1 text-sm font-medium text-gray-700">Email</label>
        <input type="email" name="email" id="email" class="w-full p-3 border rounded-md text-gray-900 bg-gray-50 
               focus:ring-blue-500 focus:border-blue-500" placeholder="name@company.com" required />
      </div>

      <div>
        <label for="password" class="block mb-1 text-sm font-medium text-gray-700">Password</label>
        <input type="password" name="password" id="password" class="w-full p-3 border rounded-md text-gray-900 bg-gray-50 
               focus:ring-blue-500 focus:border-blue-500" placeholder="••••••••" required />
      </div>

      <div class="flex items-center justify-between">
        <label class="inline-flex items-center text-sm text-gray-600">
          <input type="checkbox" id="rememberMe" class="form-checkbox h-4 w-4 text-blue-600" />
          <span class="ml-2">Remember Me</span>
        </label>
        <!-- Forgot Password Button -->
        <a href="#" id="forgotPassword" class="text-sm text-blue-600 hover:underline">
          Forgot password?
        </a>
      </div>

      <button type="submit" class="w-full px-4 py-3 text-white bg-blue-600 hover:bg-blue-700 rounded-lg font-medium 
               focus:outline-none focus:ring-4 focus:ring-blue-300">
        Login
      </button>
    </form>
  </div>

  <script>
    // Restore saved credentials
    window.addEventListener("DOMContentLoaded", () => {
      const rememberedEmail = localStorage.getItem("rememberedEmail");
      const rememberedPassword = localStorage.getItem("rememberedPassword");
      if (rememberedEmail) {
        document.getElementById("email").value = rememberedEmail;
        document.getElementById("password").value = rememberedPassword;
        document.getElementById("rememberMe").checked = true;
      }
    });

    // Login form submission
    document.getElementById("loginForm").addEventListener("submit", async function (event) {
      event.preventDefault();

      const u_email = document.getElementById("email").value.trim();
      const password = document.getElementById("password").value.trim();
      const remember = document.getElementById("rememberMe").checked;
      localStorage.removeItem("openMenus");

      if (!u_email) return Swal.fire("Error", "Email is required!", "error");
      if (!validateEmail(u_email)) return Swal.fire("Error", "Invalid email format!", "error");
      if (!password) return Swal.fire("Error", "Password is required!", "error");
      if (password.length < 6) return Swal.fire("Error", "Password must be at least 6 characters!", "error");

      try {
        const response = await fetch("/admin/login", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ u_email, password }),
        });

        const data = await response.json();

        if (response.ok) {
          localStorage.setItem("user", JSON.stringify(data.user));
          localStorage.setItem("token", data.token);
          localStorage.setItem("img", JSON.stringify(data.user.img));
          localStorage.setItem("himg", JSON.stringify(data.user.hlogo));

          if (remember) {
            localStorage.setItem("rememberedEmail", u_email);
            localStorage.setItem("rememberedPassword", password);
          } else {
            localStorage.removeItem("rememberedEmail");
            localStorage.removeItem("rememberedPassword");
          }

          window.location.href = "/admin/dashboard";
        } else {
          Swal.fire("Login Failed", data.error || "Invalid credentials", "error");
        }
      } catch (err) {
        Swal.fire("Error", "An error occurred. Please try again!", "error");
      }
    });

 
function validateEmail(email) {
  const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return re.test(email);
}

  </script>
  <script>
// SET THIS TO TRUE FOR DEMO VERSION
const IS_DEMO = false;

// Forgot Password Handler
document.getElementById("forgotPassword").addEventListener("click", async (e) => {
  e.preventDefault();

  if (IS_DEMO) {
    return Swal.fire({
      icon: "warning",
      title: "Feature Disabled",
      text: "Password reset is disabled in demo version!",
      confirmButtonText: "OK"
    });
  }

  const { value: email } = await Swal.fire({
    title: "Forgot Admin Password",
    input: "email",
    inputLabel: "Enter admin email to confirm",
    inputPlaceholder: "admin@example.com",
    confirmButtonText: "Send Temporary Password",
    showCancelButton: true,
    inputValidator: (value) => {
      if (!value) return "Please enter your email!";
      if (!validateEmail(value)) return "Please enter a valid email address!";
      return null;
    },
  });

  if (!email) return; // cancelled

  try {
    const res = await fetch("/admin/reset-temp-password", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email }),
    });

    const data = await res.json();

    if (res.ok) {
      Swal.fire({
        icon: "success",
        title: "Temporary Password Sent",
        text: data.message,
      });
    } else {
      Swal.fire({
        icon: "error",
        title: "Error",
        text: data.message || "Failed to reset password.",
      });
    }
  } catch (error) {
    Swal.fire("Error", "Unable to connect to the server. Please try again.", "error");
  }
});
</script>

</body>
</html>
