<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/config/functions.php';
ensure_session();

/** Decide where to land after login, using normalized role names. */
function login_dest_for_role(?string $role): string {
  $norm = normalize_role_name($role);
  switch ($norm) {
    case 'md':
      return url_modules('dashboard/md.php');
    case 'accounts':
      return url_modules('accounts/index.php');          // Accounts dashboard
    case 'sales':
      return url_modules('dashboard/sales.php');         // Sales dashboard
    case 'admin':
      return url_public('index.php');                    // System Administrator home
    case 'management':
      return url_modules('dashboard/md.php');            // Management -> MD view
    default:
      return url_public('index.php');
  }
}

/* Already logged in? Send to their landing page. */
if (!empty($_SESSION['user']['id'])) {
  $role = $_SESSION['user']['role'] ?? $_SESSION['user']['role_name'] ?? null;
  redirect(login_dest_for_role($role));
}

$errors = [];

/**
 * Flexible password check:
 * - If stored value looks like bcrypt/argon2 hash -> password_verify()
 * - Else compare as PLAIN TEXT with hash_equals()
 */
function verify_password_flexible(string $input, ?string $stored): bool {
  if ($stored === null || $stored === '') return false;
  $looksHashed = (bool)preg_match('/^\$(2y|2a|2b)\$|^\$argon2(id|i|d)\$/i', $stored);
  if ($looksHashed) return password_verify($input, $stored);
  return hash_equals($stored, $input);
}

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

    if ($email === '' || $pass === '') {
      $errors[] = 'Email and password are required.';
    } else {
      // Use LEFT JOIN (safer); select u.password AS password_value
      $stmt = db()->prepare('
        SELECT
          u.id,
          u.name        AS full_name,
          u.email,
          u.password    AS password_value,   -- <- matches your schema
          u.company_id,
          u.role_id,
          u.is_active,
          r.name        AS role_name
        FROM users u
        LEFT JOIN roles r ON r.id = u.role_id
        WHERE u.email = :email
        LIMIT 1
      ');
      $stmt->execute([':email' => $email]);
      $user = $stmt->fetch();

      if (!$user) {
        $errors[] = 'Invalid credentials.';
      } elseif ((int)($user['is_active'] ?? 0) !== 1) {
        $errors[] = 'Your account is disabled. Please contact an administrator.';
      } elseif (!verify_password_flexible($pass, (string)($user['password_value'] ?? ''))) {
        $errors[] = 'Invalid credentials.';
      } else {
        // Success: set session
        session_regenerate_id(true);
        $_SESSION['user'] = [
          'id'         => (int)$user['id'],
          'full_name'  => (string)$user['full_name'],
          'email'      => (string)$user['email'],
          'role'       => $user['role_name'] ?? null,   // keep raw name for display
          'role_id'    => (int)$user['role_id'],
          'company_id' => isset($user['company_id']) ? (int)$user['company_id'] : null,
          'login_at'   => time(),
        ];

        // Best-effort: update last_login
        try {
          $upd = db()->prepare('UPDATE users SET last_login = NOW() WHERE id = :id');
          $upd->execute([':id' => $user['id']]);
        } catch (Throwable $e) { /* ignore */ }

        // Audit
        audit_log('auth.login', 'user', (int)$user['id'], [
          'ip' => client_ip(),
          'ua' => client_ua(),
        ]);

        // Rotate CSRF
        $_SESSION['csrf'] = bin2hex(random_bytes(16));

        // Role-based redirect (normalize for safety)
        $dest = login_dest_for_role($user['role_name'] ?? null);
        redirect($dest);
      }
    }
  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV === 'dev') ? $e->getMessage() : 'Unexpected error. Please try again.';
  }
}

include dirname(__DIR__) . '/includes/header.php';
?>
<div class="row justify-content-center">
  <div class="col-12 col-md-6 col-lg-5">
    <div class="card shadow-sm">
      <div class="card-body p-4">
        <h1 class="h4 mb-3">Sign in</h1>

        <?php if ($errors): ?>
          <div class="alert alert-danger">
            <ul class="mb-0">
              <?php foreach ($errors as $err): ?>
                <li><?= e($err) ?></li>
              <?php endforeach; ?>
            </ul>
          </div>
        <?php endif; ?>

        <form method="post" novalidate>
          <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
          <div class="mb-3">
            <label class="form-label">Email</label>
            <input
              type="email"
              name="email"
              class="form-control"
              required
              autofocus
              value="<?= e($_POST['email'] ?? '') ?>">
          </div>
          <div class="mb-3">
            <label class="form-label">Password</label>
            <input type="password" name="password" class="form-control" required placeholder="Enter your password">
          </div>
          <button class="btn btn-dark w-100" type="submit">Sign in</button>
        </form>
      </div>
    </div>
    <p class="text-center text-muted mt-3 small">© <?= date('Y') ?> Brownhill Group Limited</p>
  </div>
</div>
<?php include dirname(__DIR__) . '/includes/footer.php'; ?>
