<?php
/**
 * Mobile login for data collection team (phones/tablets).
 */
require_once __DIR__ . '/init.php';
require_once __DIR__ . '/../includes/auth.php';

if (!empty($_SESSION['user_id'])) {
    $role = $_SESSION['role'] ?? '';
    if ($role === 'data_collector') {
        require_once __DIR__ . '/../includes/collect-routing.php';
        header('Location: ' . nazareth_url(nazareth_data_collector_home_route()));
    } else {
        header('Location: ' . BASE_PATH . '/dashboard');
    }
    exit;
}

$error = null;
$urlToastError = trim((string)($_GET['toast_error'] ?? ''));
$next = trim((string)($_GET['next'] ?? ''));
if ($next === '' || strpos($next, '//') !== false || strpos($next, "\n") !== false) {
    $next = BASE_PATH . '/mobile';
}
// Only allow internal redirects
if ($next !== '' && strpos($next, BASE_PATH) !== 0) {
    $next = BASE_PATH . '/mobile';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    if (empty($username) || empty($password)) {
        $error = 'Please enter username and password.';
    } else {
        $result = attemptLogin($pdo, $username, $password);
        if ($result['success']) {
            if (($result['role'] ?? '') !== 'data_collector') {
                logout();
                $error = 'This login is for data collection accounts only. Use the desktop sign-in for other roles.';
            } elseif (!empty($result['must_change_password'])) {
                header('Location: ' . BASE_PATH . '/mobile/change-password');
                exit;
            } else {
                $redir = trim((string)($_POST['next'] ?? $next));
                if ($redir === '' || strpos($redir, BASE_PATH) !== 0) {
                    $redir = BASE_PATH . '/mobile';
                }
                $establish = BASE_PATH . '/mobile/establish?next=' . rawurlencode($redir);
                header('Location: ' . $establish);
                exit;
            }
        } else {
            $error = $result['error'];
        }
    }
}

$showLoginSplash = ($error === null && $urlToastError === '' && ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET');
$mobileAppIcon = BASE_PATH . '/mobile/assets/img/192.png';
$mobileAppIconV = @filemtime(__DIR__ . '/assets/img/192.png');
if ($mobileAppIconV) {
    $mobileAppIcon .= '?v=' . (int) $mobileAppIconV;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <script>try{sessionStorage.removeItem('naz_m_pwa');}catch(e){}</script>
    <title>Data collection — <?= htmlspecialchars(SITE_NAME) ?></title>
    <link rel="icon" href="<?= htmlspecialchars($mobileAppIcon, ENT_QUOTES, 'UTF-8') ?>" type="image/png" sizes="192x192">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?= nazareth_asset('css/style.css') ?>?v=<?= @filemtime(__DIR__ . '/../public/css/style.css') ?>">
    <link rel="stylesheet" href="<?= nazareth_mobile_asset('mobile.css') ?>?v=<?= @filemtime(__DIR__ . '/mobile.css') ?>">
    <?php require_once __DIR__ . '/pwa-head.php';
    nazareth_mobile_pwa_head(); ?>
</head>
<body class="mobile-collect-body mobile-collect-login-body">
    <?php if ($showLoginSplash): ?>
    <div class="mobile-login-splash" aria-hidden="true">
        <div class="mobile-login-splash__glow mobile-login-splash__glow--1"></div>
        <div class="mobile-login-splash__glow mobile-login-splash__glow--2"></div>
        <div class="mobile-login-splash__inner">
            <img src="<?= nazareth_asset('img/logo.png') ?>" alt="" class="mobile-login-splash__logo" width="96" height="96">
            <p class="mobile-login-splash__site"><?= htmlspecialchars(SITE_NAME) ?></p>
            <p class="mobile-login-splash__title">Data collection</p>
            <div class="mobile-login-splash__track" role="presentation">
                <div class="mobile-login-splash__fill"></div>
            </div>
        </div>
    </div>
    <?php endif; ?>
    <div class="mobile-collect-login">
        <div class="mobile-collect-login-content">
            <div class="mobile-collect-brand">
                <img src="<?= nazareth_asset('img/logo.png') ?>" alt="" class="mobile-collect-logo">
                <h1 class="mobile-collect-title">Data collection</h1>
            </div>

            <?php if ($error): ?>
                <div class="mobile-collect-alert"><?= htmlspecialchars($error) ?></div>
            <?php elseif ($urlToastError !== ''): ?>
                <div class="mobile-collect-alert"><?= htmlspecialchars($urlToastError) ?></div>
            <?php endif; ?>

            <form method="post" action="" class="mobile-collect-form">
                <input type="hidden" name="next" value="<?= htmlspecialchars($next) ?>">
                <div class="mobile-collect-field">
                    <label for="username">Username</label>
                    <div class="mobile-collect-input-wrap">
                        <span class="mobile-collect-input-leading" aria-hidden="true">
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
                        </span>
                        <input type="text" id="username" name="username" class="mobile-collect-input" required autocomplete="username"
                            value="<?= htmlspecialchars($_POST['username'] ?? '') ?>">
                    </div>
                </div>
                <div class="mobile-collect-field">
                    <label for="password">Password</label>
                    <div class="mobile-collect-input-wrap mobile-collect-input-wrap--password">
                        <span class="mobile-collect-input-leading" aria-hidden="true">
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
                        </span>
                        <input type="password" id="password" name="password" class="mobile-collect-input" required autocomplete="current-password">
                        <button type="button" class="mobile-collect-password-toggle" id="mobile_login_toggle_pw" aria-label="Show password" aria-pressed="false">
                            <span class="mobile-collect-password-toggle__icon mobile-collect-password-toggle__show">
                                <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>
                            </span>
                            <span class="mobile-collect-password-toggle__icon mobile-collect-password-toggle__hide" hidden>
                                <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/><line x1="2" x2="22" y1="2" y2="22"/></svg>
                            </span>
                        </button>
                    </div>
                </div>
                <button type="submit" class="mobile-collect-btn">Sign in</button>
            </form>
            <p class="mobile-collect-login-link">
                <a href="<?= htmlspecialchars(BASE_PATH . '/mobile/forgot-password', ENT_QUOTES, 'UTF-8') ?>">Forgot password?</a>
                <span class="mobile-collect-login-link-sep" aria-hidden="true"> · </span>
                <a href="<?= htmlspecialchars(nazareth_url('login'), ENT_QUOTES, 'UTF-8') ?>">Main church sign-in</a>
            </p>
            <script>
            (function () {
                var btn = document.getElementById('mobile_login_toggle_pw');
                var input = document.getElementById('password');
                if (!btn || !input) return;
                var showIcon = btn.querySelector('.mobile-collect-password-toggle__show');
                var hideIcon = btn.querySelector('.mobile-collect-password-toggle__hide');
                btn.addEventListener('click', function () {
                    var revealing = input.type === 'password';
                    input.type = revealing ? 'text' : 'password';
                    btn.setAttribute('aria-pressed', revealing ? 'true' : 'false');
                    btn.setAttribute('aria-label', revealing ? 'Hide password' : 'Show password');
                    if (showIcon && hideIcon) {
                        showIcon.hidden = revealing;
                        hideIcon.hidden = !revealing;
                    }
                });
            })();
            </script>
        </div>

        <footer class="mobile-collect-login-footer">
            <p class="mobile-collect-login-church"><?= htmlspecialchars(SITE_FULL_NAME) ?></p>
            <p class="mobile-collect-login-system">Church Management System</p>
        </footer>
    </div>
    <?php nazareth_mobile_pwa_scripts(); ?>
</body>
</html>
