<?php
// public/index.php
declare(strict_types=1);

require_once __DIR__ . "/../config/db.php";
require_once __DIR__ . "/../config/auth.php";

// If already logged in, go dashboard
if (is_logged_in()) {
    header("Location: /school-crm/public/dashboard.php");
    exit;
}

$error = "";

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

    if (!csrf_validate($token)) {
        $error = "Invalid request. Please try again.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Enter a valid email.";
    } elseif ($password === '') {
        $error = "Enter your password.";
    } else {
        $stmt = $pdo->prepare("SELECT id, name, email, password_hash, role, active FROM users WHERE email = ? LIMIT 1");
        $stmt->execute([$email]);
        $user = $stmt->fetch();

        if (!$user) {
            $error = "Wrong email or password.";
        } elseif ((int)$user['active'] !== 1) {
            $error = "Your account is inactive. Contact admin.";
        } elseif (!password_verify($password, $user['password_hash'])) {
            $error = "Wrong email or password.";
        } else {
            // login success
            session_regenerate_id(true);
            $_SESSION['user'] = [
                'id'    => (int)$user['id'],
                'name'  => (string)$user['name'],
                'email' => (string)$user['email'],
                'role'  => (string)$user['role'],
            ];

            header("Location: /school-crm/public/dashboard.php");
            exit;
        }
    }
}

?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>School CRM - Login</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body{font-family:Arial,Helvetica,sans-serif;background:#f5f6fa;margin:0}
    .wrap{min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px}
    .card{background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:22px;max-width:380px;width:100%;box-shadow:0 8px 30px rgba(0,0,0,.06)}
    .title{font-size:20px;margin:0 0 6px}
    .sub{color:#6b7280;margin:0 0 18px;font-size:13px}
    label{display:block;margin:12px 0 6px;font-size:13px}
    input{width:100%;padding:10px 12px;border:1px solid #d1d5db;border-radius:10px;font-size:14px}
    button{width:100%;margin-top:14px;padding:10px 12px;border:0;border-radius:10px;background:#111827;color:#fff;font-size:14px;cursor:pointer}
    .err{background:#fee2e2;border:1px solid #fecaca;color:#991b1b;padding:10px;border-radius:10px;margin:0 0 12px;font-size:13px}
    .hint{color:#6b7280;font-size:12px;margin-top:10px}
  </style>
</head>
<body>
<div class="wrap">
  <div class="card">
    <h1 class="title">School CRM</h1>
    <p class="sub">Login with your team account</p>

    <?php if ($error !== ''): ?>
      <div class="err"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <form method="post" autocomplete="off">
      <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token()) ?>">

      <label>Email</label>
      <input type="email" name="email" placeholder="you@example.com" required>

      <label>Password</label>
      <input type="password" name="password" placeholder="••••••••" required>

      <button type="submit">Login</button>
      <div class="hint">Admin can create Rep accounts later.</div>
    </form>
  </div>
</div>
</body>
</html>
