<?php
// Login — Single-file page that renders the form AND handles authentication
session_start();

// ------------------------
// CONFIG (edit to your setup)
// ------------------------
$DB_HOST = 'localhost';
$DB_NAME = 'lands';
$DB_USER = 'root';
$DB_PASS = '';
$AFTER_LOGIN = 'default.php';

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

// Flash helper
function set_flash($key, $msg){ $_SESSION[$key] = $msg; }
function get_flash($key){ $m = $_SESSION[$key] ?? null; unset($_SESSION[$key]); return $m; }

$error = get_flash('flash_error');

// ------------------------
// HANDLE POST (auth)
// ------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $u = trim($_POST['username'] ?? '');
    $p = $_POST['password'] ?? '';
    $csrf = $_POST['csrf_token'] ?? '';

    if (!hash_equals((string)($_SESSION['csrf_token'] ?? ''), (string)$csrf)) {
        set_flash('flash_error', 'Security check failed. Please refresh and try again.');
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    }

    if ($u === '' || $p === '') {
        set_flash('flash_error', 'Please enter both username/email and password.');
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    }

    try {
        $dsn = "mysql:host={$DB_HOST};dbname={$DB_NAME};charset=utf8mb4";
        $pdo = new PDO($dsn, $DB_USER, $DB_PASS, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]);
        
        $sql = "SELECT userid, username, `password`, roleid, `status` FROM users WHERE (username = :u ) LIMIT 1";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([':u' => $u]);
        $user = $stmt->fetch();
        
        if (!$user || $p!==$user['password']) {
            set_flash('flash_error', 'Invalid credentials.');
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit;
        }

        if (isset($user['status']) && strtolower((string)$user['status']) !== 'active') {
            set_flash('flash_error', 'Your account is not active. Contact the administrator.');
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit;
        }

        

        // Role mapping: roleid == 1 => superadmin
        $roleName = ((int)$user['roleid'] === 1) ? 'superadmin' : 'user';
        $isSuper = ((int)$user['roleid'] === 1);

        // Session
        session_regenerate_id(true);
        $_SESSION['auth'] = [
            'user_id' => (int)$user['id'],
            'username' => $user['username'],
            'email' => $user['email'],
            'roleid' => (int)$user['roleid'],
            'role' => $roleName,
            'is_superadmin' => $isSuper,
            'logged_in_at' => time(),
        ];

        header('Location: ' . $AFTER_LOGIN);
        exit;
    } catch (Throwable $e) {
        error_log('Login error: ' . $e->getMessage());
        set_flash('flash_error', 'Service unavailable. Please try again later.');
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    }
}
?>
<!doctype html>
<html lang="en" class="theme-dark">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Ebonyi State Lands Information System — Sign In</title>
  <!-- Bootstrap 5.3.x -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <!-- Bootstrap Icons -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
  <!-- Inter font -->
  <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@300;400;500;600;700&display=swap" rel="stylesheet">
  <!-- Custom CSS -->
  <link href="css/style2.css" rel="stylesheet">
</head>
<body>
  <!-- Decorative background shapes -->
  <div class="bg-blur-blob blob-1"></div>
  <div class="bg-blur-blob blob-2"></div>
  <div class="noise-overlay"></div>

  <main class="auth-wrap container-fluid">
    <div class="row g-0 min-vh-100">
      <!-- Left Hero Section (optional)—you can paste the hero from earlier versions here -->
      <aside class="col-lg-6 d-none d-lg-flex align-items-center justify-content-center hero-col p-5">
        <div class="hero-card rounded-5 p-4 p-xl-5 w-100" style="max-width: 760px;">
          <div class="d-flex align-items-center gap-3 mb-4">
            <img class="brand-logo" src="assets/nigeria-coat-of-arms.svg" alt="Nigerian Coat of Arms logo" />
            <div>
              <h1 class="h4 mb-1 fw-bold text-heading">Ebonyi State Lands Information System</h1>
              <div class="d-inline-flex align-items-center gap-2">
                <span class="badge rounded-pill badge-env">Production</span>
                <small class="text-secondary">Secure Access</small>
              </div>
            </div>
          </div>
          <div class="row g-4 align-items-center">
            <div class="col-7">
              <h2 class="display-6 fw-semibold mb-3 text-heading">Trusted land records for a modern Ebonyi</h2>
              <p class="lead text-sub mb-4">GIS-backed workflows for <strong>C of O</strong> processing, deed registration, cadastral indexing, and audit-ready reporting.</p>
              <div class="row g-3">
                <div class="col-sm-6">
                  <div class="feature-tile h-100 p-3 rounded-4">
                    <div class="feature-ico mb-2"><i class="bi bi-map"></i></div>
                    <div class="fw-semibold text-heading">GIS Dashboard</div>
                    <div class="small-muted">Parcel layers & ownership overlays.</div>
                  </div>
                </div>
                <div class="col-sm-6">
                  <div class="feature-tile h-100 p-3 rounded-4">
                    <div class="feature-ico mb-2"><i class="bi bi-file-earmark-text"></i></div>
                    <div class="fw-semibold text-heading">Digitized Records</div>
                    <div class="small-muted">Secure PDF vault & audit trail.</div>
                  </div>
                </div>
                <div class="col-sm-6">
                  <div class="feature-tile h-100 p-3 rounded-4">
                    <div class="feature-ico mb-2"><i class="bi bi-fingerprint"></i></div>
                    <div class="fw-semibold text-heading">2FA Ready</div>
                    <div class="small-muted">TOTP & device checks.</div>
                  </div>
                </div>
                <div class="col-sm-6">
                  <div class="feature-tile h-100 p-3 rounded-4">
                    <div class="feature-ico mb-2"><i class="bi bi-lock"></i></div>
                    <div class="fw-semibold text-heading">Role-based Access</div>
                    <div class="small-muted">Registrar, GIS, Audit, Admin.</div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-5 text-center">
              <div class="hero-illustration mx-auto">
                <!-- Inline SVG illustration from earlier versions could be placed here -->
              </div>
            </div>
          </div>
        </div>
      </aside>

      <!-- Right: Auth form -->
      <section class="col-lg-6 d-flex align-items-center justify-content-center p-4 p-md-5">
        <div class="auth-card glass rounded-5 p-4 p-lg-5 w-100" style="max-width: 520px;">
          <div class="d-flex align-items-center justify-content-between mb-4">
            <div class="d-flex align-items-center gap-3">
              <img class="brand-logo d-lg-none" src="assets/nigeria-coat-of-arms.svg" alt="Coat of Arms logo small" />
              <div>
                <h2 class="h4 mb-0 fw-semibold text-heading">Welcome back</h2>
                <div class="small text-sub">Sign in to continue</div>
              </div>
            </div>
            <div class="form-check form-switch">
              <input class="form-check-input" type="checkbox" role="switch" id="darkSwitch" checked>
              <label class="form-check-label small-muted" for="darkSwitch">Dark</label>
            </div>
          </div>

          <?php if ($error): ?>
            <div class="alert alert-danger" role="alert">
              <?php echo htmlspecialchars($error); ?>
            </div>
          <?php endif; ?>

          <!-- SIGN-IN FORM (posts to the same page) -->
          <form id="loginForm" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST" class="needs-validation" novalidate>
            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">

            <div class="form-floating mb-3">
              <input type="text" class="form-control" id="username" name="username" placeholder="Username or Email" required>
              <label for="username"><i class="bi bi-person"></i> Username or Email</label>
              <div class="invalid-feedback">Username or Email is required.</div>
            </div>

            <div class="form-floating mb-3 position-relative">
              <input type="password" class="form-control" id="password" name="password" placeholder="Password" minlength="6" required>
              <label for="password"><i class="bi bi-shield-lock"></i> Password</label>
              <button class="btn btn-sm btn-outline-light position-absolute top-50 end-0 translate-middle-y me-2" type="button" id="togglePass" aria-label="Show password"><i class="bi bi-eye"></i></button>
              <div class="invalid-feedback">Password must be at least 6 characters.</div>
            </div>

            <div class="d-flex justify-content-between align-items-center mb-3">
              <div class="form-check">
                <input class="form-check-input" type="checkbox" value="1" id="remember">
                <label class="form-check-label small" for="remember">Remember me</label>
              </div>
              <a href="#" class="link-muted small" data-bs-toggle="modal" data-bs-target="#forgotModal">Forgot password?</a>
            </div>

            <button class="btn btn-primary w-100 py-2 mb-2" type="submit"><i class="bi bi-box-arrow-in-right me-1"></i> Sign in</button>
            <button class="btn btn-outline-light w-100 py-2 mb-3" type="button" disabled>
              <i class="bi bi-shield-check me-1"></i> Sign in with Gov SSO
            </button>

            <div class="text-center small-muted">
              By continuing, you agree to the <a href="#">Terms</a> and <a href="#">Privacy Policy</a>.
            </div>
          </form>

          <p class="gov-footer small text-center mt-3 mb-0">
            Need access? <a href="#" data-bs-toggle="modal" data-bs-target="#requestAccessModal">Request an account</a>
          </p>
        </div>
      </section>
    </div>
  </main>

  <!-- (Optional) Modals and Toast can be included here as in earlier versions -->

  <!-- Bootstrap JS -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    // Theme toggle on <html>
    const darkSwitch = document.getElementById('darkSwitch');
    function setTheme(isDark){
      const root = document.documentElement; // <html>
      root.classList.toggle('theme-dark', isDark);
      root.classList.toggle('theme-light', !isDark);
    }
    setTheme(true);
    darkSwitch?.addEventListener('change', (e) => setTheme(e.target.checked));

    // Toggle password visibility
    const pass = document.getElementById('password');
    const togglePass = document.getElementById('togglePass');
    togglePass?.addEventListener('click', () => {
      const isText = pass.type === 'text';
      pass.type = isText ? 'password' : 'text';
      togglePass.innerHTML = isText ? '<i class="bi bi-eye"></i>' : '<i class="bi bi-eye-slash"></i>';
      togglePass.setAttribute('aria-label', isText ? 'Show password' : 'Hide password');
    });

    // Client-side validation
    (() => {
      const form = document.getElementById('loginForm');
      form.addEventListener('submit', (event) => {
        if (!form.checkValidity()){
          event.preventDefault();
          event.stopPropagation();
        }
        form.classList.add('was-validated');
      }, false);
    })();
  </script>
</body>
</html>
