<?php
declare(strict_types=1);

require_once __DIR__ . '/../app/init.php';
app_require_login();

$companies = app_current_user_company_options();
$error = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        app_verify_csrf();
        $selectedCompanyId = app_integer($_POST['company_id'] ?? 0);
        if ($selectedCompanyId <= 0) {
            throw new RuntimeException('Please select a company first.');
        }
        if (!app_current_user_can_access_company($selectedCompanyId)) {
            throw new RuntimeException('You do not have access to this company.');
        }

        app_set_context_company_id($selectedCompanyId);
        app_redirect('home.php?company_id=' . urlencode((string) $selectedCompanyId));
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST' && count($companies) === 1) {
    $onlyCompanyId = (int) ($companies[0]['id'] ?? 0);
    if ($onlyCompanyId > 0) {
        app_set_context_company_id($onlyCompanyId);
        app_redirect('home.php?company_id=' . urlencode((string) $onlyCompanyId));
    }
}

$currentCompanyId = app_context_company_id();
$displayName = app_normalize_whitespace((string) (app_current_user()['full_name'] ?? ''));
if ($displayName === '') {
    $displayName = app_current_username();
}
?>
<!doctype html>
<html <?= app_html_attrs() ?>>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= app_escape(app_t((string) app_config('app_name'))) ?> - <?= app_escape(app_t('Select Company')) ?></title>
  <link rel="icon" href="assets/favicon.svg" type="image/svg+xml">
  <link rel="shortcut icon" href="assets/favicon.svg" type="image/svg+xml">
  <link rel="stylesheet" href="assets/styles.css">
</head>
<body>
<?= app_ui_controls_html('auth') ?>
<main class="auth-shell">
  <section class="auth-card company-select-card">
    <div class="auth-hero">
      <img src="assets/logo.svg" alt="Orion Accounts ERP" class="auth-logo">
      <h1><?= app_escape(app_t('Select Company')) ?></h1>
      <p><?= app_escape(app_t('Your account is assigned to more than one company.')) ?></p>
      <div class="auth-meta">
        <span class="chip"><?= app_escape($displayName) ?></span>
        <span class="chip"><?= app_escape(app_t('You can switch company later from the sidebar.')) ?></span>
      </div>
    </div>

    <form class="auth-form" method="post">
      <?= app_csrf_field() ?>
      <div>
        <h2><?= app_escape(app_t('Choose Company')) ?></h2>
        <p class="helper"><?= app_escape(app_t('Choose the company you want to work on.')) ?></p>
      </div>

      <?php if ($error !== null): ?>
        <div class="alert error"><?= app_escape($error) ?></div>
      <?php endif; ?>

      <?php if (!$companies): ?>
        <div class="empty-state"><?= app_escape(app_t('No companies available for this user.')) ?></div>
        <div class="form-actions">
          <a class="btn btn-secondary" href="logout.php"><?= app_escape(app_t('Logout')) ?></a>
        </div>
      <?php else: ?>
        <div class="company-picker-grid" role="radiogroup" aria-label="<?= app_escape(app_t('Available Companies')) ?>">
          <?php foreach ($companies as $index => $company): ?>
            <?php
              $companyId = (int) ($company['id'] ?? 0);
              $isChecked = $currentCompanyId !== null
                  ? $companyId === (int) $currentCompanyId
                  : $index === 0;
            ?>
            <label class="company-picker-card<?= $isChecked ? ' is-current' : '' ?>">
              <input type="radio" name="company_id" value="<?= $companyId ?>" <?= $isChecked ? 'checked' : '' ?> required>
              <span class="company-picker-card__logo">
                <img src="<?= app_escape(app_company_logo_path($company)) ?>" alt="<?= app_escape((string) ($company['name'] ?? 'Company')) ?>">
              </span>
              <span class="company-picker-card__content">
                <strong><?= app_escape((string) ($company['name'] ?? '')) ?></strong>
                <small><?= app_escape((string) ($company['currency_code'] ?? '')) ?></small>
              </span>
            </label>
          <?php endforeach; ?>
        </div>

        <div class="form-actions">
          <button class="btn btn-primary" type="submit"><?= app_escape(app_t('Continue')) ?></button>
          <a class="btn btn-secondary" href="logout.php"><?= app_escape(app_t('Logout')) ?></a>
        </div>
      <?php endif; ?>
    </form>
  </section>
</main>
<script src="assets/app.js"></script>
</body>
</html>

