<?php
/**
 * User Login
 */
require_once __DIR__ . '/includes/init.php';

if (SessionManager::isLoggedIn()) {
    $role = SessionManager::getUserRole();
    if (in_array($role, [ROLE_ADMIN, ROLE_COUNTER, ROLE_CHECKER, ROLE_CONTROLLER])) {
        redirect(APP_URL . '/index.php');
    }
    // Invalid role in session - destroy session and show login form
    logout_user();
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::check();

    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    if (empty($username) || empty($password)) {
        $error = 'Please enter both username and password.';
    } else {
        $db = Database::getInstance();
        $user = $db->fetch("SELECT * FROM users WHERE (username = ? OR email = ?) AND status = 'active'", [$username, $username]);

        if ($user && verify_password($password, $user['password_hash'])) {
            login_user($user['id'], $user['username'], $user['role'], $user['full_name']);
            $db->update('users', ['last_login' => date('Y-m-d H:i:s')], 'id = ?', [$user['id']]);
            log_action($user['id'], 'login', 'users', $user['id']);
            set_success('Welcome back, ' . $user['full_name'] . '!');

            // Direct role-based dashboard redirect
            switch ($user['role']) {
                case ROLE_ADMIN:
                    redirect(APP_URL . '/admin/dashboard.php');
                    break;
                case ROLE_CONTROLLER:
                    redirect(APP_URL . '/controller/dashboard.php');
                    break;
                case ROLE_COUNTER:
                    redirect(APP_URL . '/counter/dashboard.php');
                    break;
                case ROLE_CHECKER:
                    redirect(APP_URL . '/checker/dashboard.php');
                    break;
                default:
                    redirect(APP_URL . '/index.php');
            }
        } else {
            $error = 'Invalid username or password.';
        }
    }
}

$pageTitle = 'Login';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= e($pageTitle) ?> - <?= APP_NAME ?></title>
    <link rel="stylesheet" href="<?= APP_URL ?>/assets/css/style.css">
    <link rel="stylesheet" href="<?= APP_URL ?>/assets/css/responsive.css">

    <!-- ======================  PWA — MANIFEST  ========================= -->
    <link rel="manifest" href="/invcount/manifest.json">
    <meta name="theme-color" content="#16213e">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="InvCounter">
    <!-- ================================================================= -->
</head>
<body class="auth-body">
<?php
$flashMessages = get_flash();
if (!empty($flashMessages)):
    foreach ($flashMessages as $flash):
?>
<div class="alert alert-<?= e($flash['type']) ?>" style="position:fixed;top:20px;left:50%;transform:translateX(-50%);z-index:9999;min-width:300px;max-width:500px" onclick="this.remove()">
    <span><?= e($flash['message']) ?></span>
    <button type="button" class="alert-close">&times;</button>
</div>
<?php endforeach; endif; ?>

<div class="auth-container">
    <div class="auth-card">
        <div class="auth-header">
<div class="brand">
    <img src="<?= APP_URL ?>/uploads/logos/report_logo_1_1775098149.png" alt="<?= APP_NAME ?> Logo" class="login-logo">
</div>
            <p>Inventory Count Management System</p>
        </div>

        <?php if ($error): ?>
        <div class="alert alert-error" style="margin-bottom:20px">
            <span><?= e($error) ?></span>
        </div>
        <?php endif; ?>

        <form method="POST" action="">
            <?= Csrf::field() ?>
            <div class="form-group">
                <label class="form-label" for="username">Username or Email</label>
                <input type="text" id="username" name="username" class="form-control" placeholder="Enter username or email" value="<?= e($username ?? '') ?>" required autofocus>
            </div>
            <div class="form-group">
                <label class="form-label" for="password">Password</label>
                <input type="password" id="password" name="password" class="form-control" placeholder="Enter password" required>
            </div>
            <button type="submit" class="btn btn-primary btn-block btn-lg">Sign In</button>
        </form>

        <!-- ======================  PWA — INSTALL BUTTON  ==================== -->
        <div id="install-pwa-wrap" style="display:none;margin-top:1.5rem;text-align:center">
            <p style="font-size:.875rem;color:var(--text-muted);margin-bottom:.75rem">
                Install Inventory Counter on your device for faster access and offline use.
            </p>
            <button id="install-pwa-btn"
                    style="display:inline-block;padding:.65rem 1.5rem;background:#16213e;color:#fff;
                           border:none;border-radius:8px;cursor:pointer;font-size:1rem;
                           transition:opacity .15s"
                    aria-label="Install Inventory Counter PWA">
                &#128279; Install Inventory Counter
            </button>
        </div>
        <!-- =================================================================== -->
        <div class="auth-footer">
            <p>Contact your administrator for account access.</p>
        </div>
    </div>
</div>
        <!-- PWA install logic — embedded directly because login.php is a standalone page -->
    <script>
        (function () {
            if (!('serviceWorker' in navigator)) return;

            // Register SW so the browser can detect installability
            navigator.serviceWorker.register('/invcount/assets/js/sw.js', { scope: '/invcount/' })
                .catch(function (err) {
                    console.warn('[PWA] SW registration failed:', err);
                });

            // Show button when Chrome / Android signals install readiness
            window.addEventListener('beforeinstallprompt', function (e) {
                e.preventDefault();
                window.__deferredInstallPrompt = e;
                var wrap = document.getElementById('install-pwa-wrap');
                var btn  = document.getElementById('install-pwa-btn');
                if (wrap) wrap.style.display = 'block';
                if (btn) {
                    btn.style.display  = 'inline-block';
                    btn.style.opacity  = '1';
                    btn.addEventListener('click', function () {
                        var promptEvent = window.__deferredInstallPrompt;
                        if (!promptEvent) return;
                        promptEvent.prompt();
                        promptEvent.userChoice.then(function (result) {
                            console.log('[PWA] Install outcome =', result.outcome);
                            window.__deferredInstallPrompt = null;
                            if (wrap) wrap.style.display = 'none';
                        });
                    });
                }
            });

            // Button is irrelevant after the app is placed on home-screen
            window.addEventListener('appinstalled', function () {
                console.info('[PWA] Inventory Counter installed.');
                window.__deferredInstallPrompt = null;
                var wrap = document.getElementById('install-pwa-wrap');
                if (wrap) wrap.style.display = 'none';
            });
        })();
    </script>
</body>
</html>
