<?php
require_once __DIR__ . '/config.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!function_exists('h')) {
    function h($value): string {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('app_setting')) {
    function app_setting(PDO $pdo, string $key, string $default = ''): string {
        try {
            $stmt = $pdo->prepare("SELECT setting_value FROM app_settings WHERE setting_key = ? LIMIT 1");
            $stmt->execute([$key]);
            $value = $stmt->fetchColumn();
            return ($value !== false && $value !== null && $value !== '') ? (string)$value : $default;
        } catch (Throwable $e) {
            return $default;
        }
    }
}

$appName = app_setting($pdo, 'app_name', 'I Am Yielded Men');
$ministryName = app_setting($pdo, 'ministry_name', 'Yielded Vessels Ministries');
$loginLogo = app_setting($pdo, 'login_logo_path', '/men/images/iamyielded.jpg');
$dashboardHeading = app_setting($pdo, 'dashboard_heading', 'Welcome');
$dashboardSubtitle = app_setting($pdo, 'dashboard_subtitle', 'Private ministry community platform.');

$themeBackground = app_setting($pdo, 'theme_background', '#0b1220');
$themeForeground = app_setting($pdo, 'theme_foreground', '#eef4ff');
$themeAccent = app_setting($pdo, 'theme_color', '#d4af37');
$themeSecondary = app_setting($pdo, 'theme_accent', '#6a0dad');
$themePanel = app_setting($pdo, 'theme_panel', '#121c2e');

$error = '';

if (!empty($_SESSION['user_id'])) {
    header('Location: dashboard.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = (string)($_POST['password'] ?? '');

    try {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? OR email = ? LIMIT 1");
        $stmt->execute([$username, $username]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'] ?? $username;
            $_SESSION['role'] = $user['role'] ?? 'member';

            header('Location: dashboard.php');
            exit;
        }

        $error = 'Invalid login. Please try again.';
    } catch (Throwable $e) {
        $error = 'Login error: ' . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login - <?php echo h($appName); ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="assets/css/styles.css?v=140">
<style>
:root {
  --bg: <?php echo h($themeBackground); ?>;
  --text: <?php echo h($themeForeground); ?>;
  --panel: <?php echo h($themePanel); ?>;
  --accent: <?php echo h($themeAccent); ?>;
  --purple: <?php echo h($themeSecondary); ?>;
}
body {
  background: var(--bg);
  color: var(--text);
}
.login-wrap {
  min-height: 100vh;
  display: grid;
  place-items: center;
  padding: 2rem;
}
.login-card {
  width: min(460px, 100%);
  background: linear-gradient(180deg, rgba(255,255,255,.08), rgba(255,255,255,.025));
  border: 1px solid rgba(255,255,255,.15);
  border-radius: 24px;
  padding: 2rem;
  box-shadow: 0 20px 60px rgba(0,0,0,.25);
}
.login-logo {
  max-width: 240px;
  max-height: 110px;
  display: block;
  margin: 0 auto 1.25rem;
  background: #fff;
  border-radius: 12px;
  padding: .35rem;
}
.login-title {
  text-align: center;
  margin: .25rem 0 .5rem;
}
.login-subtitle {
  text-align: center;
  color: rgba(238,244,255,.75);
  margin-bottom: 1.25rem;
}
.login-card input {
  width: 100%;
  padding: .9rem;
  border-radius: 13px;
  border: 1px solid rgba(255,255,255,.15);
  background: rgba(255,255,255,.08);
  color: var(--text);
  margin-bottom: .8rem;
}
.login-card label {
  display: block;
  font-weight: 700;
  margin-bottom: .25rem;
}
.login-card button {
  width: 100%;
  padding: .95rem;
  border: 0;
  border-radius: 14px;
  font-weight: 800;
  cursor: pointer;
  background: linear-gradient(135deg,var(--purple),var(--accent));
  color: #fff;
}
.error {
  padding: .85rem;
  border-radius: 13px;
  background: rgba(226,91,82,.16);
  border: 1px solid rgba(226,91,82,.35);
  margin-bottom: 1rem;
}
.small-note {
  text-align: center;
  color: rgba(238,244,255,.65);
  font-size: .9rem;
  margin-top: 1rem;
}
</style>
</head>
<body>

<div class="login-wrap">
  <div class="login-card">
    <?php if ($loginLogo): ?>
      <img src="<?php echo h($loginLogo); ?>?v=140" alt="<?php echo h($appName); ?>" class="login-logo">
    <?php endif; ?>

    <h1 class="login-title"><?php echo h($appName); ?></h1>
    <p class="login-subtitle"><?php echo h($ministryName); ?></p>

    <?php if ($error): ?>
      <div class="error"><?php echo h($error); ?></div>
    <?php endif; ?>

    <form method="post">
      <label>Username or Email</label>
      <input type="text" name="username" required autocomplete="username">

      <label>Password</label>
      <input type="password" name="password" required autocomplete="current-password">

      <button type="submit">Login</button>
    </form>

    <p class="small-note"><?php echo h($dashboardSubtitle); ?></p>
  </div>
</div>

</body>
</html>
