<?php
require __DIR__ . '/../vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->safeLoad();
require __DIR__ . '/i18n.php';

use App\Auth;
use App\Csrf;
Auth::init();

$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!Csrf::verify($_POST['_csrf'] ?? '')) {
        $errors[] = t('invalid_csrf');
    } else {
        $identifier = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';

        if (!$identifier) $errors[] = t('staff_user');
        if (!$password) $errors[] = t('staff_pass');

        if (empty($errors)) {
            $res = Auth::attempt($identifier, $password);
            if ($res === 'success') {
                header('Location: /dashboard.php');
                exit;
            } elseif ($res === 'inactive') {
                $errors[] = t('inactive_err');
            } else {
                $errors[] = t('login_err');
            }
        }
    }
}
$csrf = Csrf::token();

// handle multi-action (login/register/patient)
$info = '';
$active = 'login';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'login';
    $active = $action;
    if (!Csrf::verify($_POST['_csrf'] ?? '')) {
        $errors[] = t('invalid_csrf');
    } else {
        if ($action === 'login') {
            $identifier = trim($_POST['email'] ?? '');
            $password = $_POST['password'] ?? '';
            if (!$identifier) $errors[] = t('staff_user');
            if (!$password) $errors[] = t('staff_pass');
            if (empty($errors)) {
                $res = Auth::attempt($identifier, $password);
                if ($res === 'success') {
                    header('Location: /dashboard.php'); exit;
                } elseif ($res === 'inactive') {
                    $errors[] = t('inactive_err');
                } else {
                    $errors[] = t('login_err');
                }
            }
        } elseif ($action === 'register') {
            $name = trim($_POST['name'] ?? '');
            $email = trim($_POST['email'] ?? '');
            $password = $_POST['password'] ?? '';
            if (!$name) $errors[] = 'Name is required';
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = t('staff_user');
            if (strlen($password) < 6) $errors[] = 'Password must be at least 6 characters';
            if (empty($errors)) {
                $pdo = App\Database::getConnection();
                try {
                    $stmt = $pdo->prepare('SELECT id FROM roles WHERE name = :name LIMIT 1');
                    $stmt->execute([':name' => 'user']);
                    $r = $stmt->fetch(PDO::FETCH_ASSOC);
                    $role_id = $r['id'] ?? null;
                    $ins = $pdo->prepare('INSERT INTO users (name,full_name,username,email,password,password_hash,role_id,status) VALUES (:name,:full_name,:username,:email,:password,:password_hash,:role_id,:status)');
                    $username = preg_replace('/[^a-z0-9_.-]+/i', '', explode('@',$email)[0]);
                    $ins->execute([
                        ':name' => $name,
                        ':full_name' => $name,
                        ':username' => $username,
                        ':email' => $email,
                        ':password' => password_hash($password, PASSWORD_DEFAULT),
                        ':password_hash' => password_hash($password, PASSWORD_DEFAULT),
                        ':role_id' => $role_id,
                        ':status' => 'pending',
                    ]);
                    $info = t('reg_submitted');
                } catch (\PDOException $e) {
                    $errors[] = 'Registration failed (email may already exist)';
                }
            }
        } elseif ($action === 'patient') {
            $errors[] = t('patient_no_table');
        }
    }
}

// Hide global topbar for auth page
$no_topbar = true;
include __DIR__ . '/header.php';
?>
<div class="auth-card" aria-live="polite">
  <div class="auth-lang-top">
    <form method="get" class="lang-form" aria-label="<?=t('choose_lang')?>">
      <label for="auth-lang-select" class="sr-only"><?=t('choose_lang')?></label>
      <select id="auth-lang-select" name="lang" class="lang-select" onchange="this.form.submit()">
        <option value="tr" <?= ($lang==='tr') ? 'selected' : '' ?>>Türkçe</option>
        <option value="en" <?= ($lang==='en') ? 'selected' : '' ?>>English</option>
      </select>
      <i class="bi bi-translate lang-icon" aria-hidden="true"></i>
    </form>
  </div>

  <div class="auth-logo">
    <img src="/images/logo.png" alt="Logo" class="auth-logo-img larger">
  </div>

  <div class="tabs">
    <a href="#" class="tab-link <?php if($active==='login') echo 'active'?>" data-target="pane-login"><i class="bi bi-person-heart me-1" aria-hidden="true"></i><?=t('login_title')?></a>
    <a href="#" class="tab-link <?php if($active==='register') echo 'active'?>" data-target="pane-register"><i class="bi bi-person-plus me-1" aria-hidden="true"></i><?=t('register_title')?></a>
    <a href="#" class="tab-link <?php if($active==='patient') echo 'active'?>" data-target="pane-patient"><i class="bi bi-journal-text me-1" aria-hidden="true"></i><?=t('tab_patient')?></a>
  </div>

  <div class="tab-pane <?php if($active==='login') echo 'active'?>" id="pane-login">
    <h2><?=t('login_title')?></h2>
    <div class="sub"><?=t('login_sub')?></div>
    <?php if($errors): ?>
      <div class="errors"><?php foreach($errors as $e) echo '<div>'.htmlspecialchars($e).'</div>'; ?></div>
    <?php endif; ?>
    <form method="post" novalidate data-auth>
      <input type="hidden" name="_csrf" value="<?=htmlspecialchars($csrf)?>">
      <input type="hidden" name="action" value="login">
      <div class="form-group">
        <label for="email"><?=t('staff_user')?></label>
        <input id="email" class="form-input" name="email" type="text" data-required value="<?=htmlspecialchars($_POST['email'] ?? '')?>" required>
      </div>
      <div class="form-group">
        <label for="password"><?=t('staff_pass')?></label>
        <input id="password" class="form-input" type="password" name="password" data-required required>
      </div>
      <div class="form-actions">
        <label class="muted" style="font-size:13px"><input type="checkbox" name="remember"> <?=t('remember')?></label>
        <a class="muted" href="#"><?=t('forgot')?></a>
      </div>
      <div style="margin-top:14px">
        <button class="btn full-width" type="submit"><i class="bi bi-person-check me-2" aria-hidden="true"></i><?=t('btn_login')?></button>
      </div>
    </form>
  </div>

  <div class="tab-pane <?php if($active==='register') echo 'active'?>" id="pane-register">
    <h2><?=t('register_title')?></h2>
    <div class="sub"><?=t('register_sub')?></div>
    <?php if($info): ?><div class="info"><?=htmlspecialchars($info)?></div><?php endif; ?>
    <?php if($errors && $active==='register'): ?>
      <div class="errors"><?php foreach($errors as $e) echo '<div>'.htmlspecialchars($e).'</div>'; ?></div>
    <?php endif; ?>
    <form method="post" novalidate>
      <input type="hidden" name="_csrf" value="<?=htmlspecialchars($csrf)?>">
      <input type="hidden" name="action" value="register">
      <div class="form-group">
        <label for="name"><?=t('register_title')?></label>
        <input id="name" class="form-input" name="name" data-required value="<?=htmlspecialchars($_POST['name'] ?? '')?>" required>
      </div>
      <div class="form-group">
        <label for="email_reg"><?=t('staff_user')?></label>
        <input id="email_reg" class="form-input" name="email" type="email" data-required value="<?=htmlspecialchars($_POST['email'] ?? '')?>" required>
      </div>
      <div class="form-group">
        <label for="password_reg"><?=t('staff_pass')?> <small style="color:var(--muted)"> (min 6 chars)</small></label>
        <input id="password_reg" class="form-input" type="password" name="password" data-required required>
      </div>
      <div style="margin-top:12px">
        <button class="btn full-width" type="submit"><i class="bi bi-person-plus me-2" aria-hidden="true"></i><?=t('btn_register')?></button>
      </div>
    </form>
  </div>

  <div class="tab-pane <?php if($active==='patient') echo 'active'?>" id="pane-patient">
    <h2><?=t('tab_patient')?></h2>
    <div class="sub"><?=t('subtitle')?></div>
    <?php if($errors && $active==='patient'): ?>
      <div class="errors"><?php foreach($errors as $e) echo '<div>'.htmlspecialchars($e).'</div>'; ?></div>
    <?php endif; ?>
    <form method="post" novalidate>
      <input type="hidden" name="_csrf" value="<?=htmlspecialchars($csrf)?>">
      <input type="hidden" name="action" value="patient">
      <div class="form-group">
        <label for="tc"><?=t('patient_tc')?></label>
        <input id="tc" class="form-input" name="tc" type="text">
      </div>
      <div class="form-group">
        <label for="birth"><?=t('patient_birth')?></label>
        <input id="birth" class="form-input" name="birth" type="date">
      </div>
      <div style="margin-top:12px">
        <button class="btn full-width" type="submit"><i class="bi bi-box-arrow-in-right me-2" aria-hidden="true"></i><?=t('patient_enter')?></button>
      </div>
    </form>
  </div>

</div>

<script>
  (function(){
    const tabs = document.querySelectorAll('.tab-link');
    const panes = document.querySelectorAll('.tab-pane');
    tabs.forEach(t=>t.addEventListener('click',e=>{
      e.preventDefault();
      tabs.forEach(x=>x.classList.remove('active'));
      panes.forEach(p=>p.classList.remove('active'));
      t.classList.add('active');
      const id = t.getAttribute('data-target');
      document.getElementById(id).classList.add('active');
      // move focus to first input in pane
      const first = document.getElementById(id).querySelector('input,button,select,textarea');
      if(first) first.focus();
    }));
    // open active tab from server
    const active = '<?=addslashes($active)?>';
    const sel = document.querySelector('.tab-link[data-target="pane-'+active+'"]');
    if(sel) sel.click();
  })();
</script>


<!-- Log info note below auth card -->
<div class="auth-log-note">
  <i class="bi bi-shield-lock"></i> <?= t('log_info') ?>
</div>

<?php include __DIR__ . '/footer.php'; ?>
