<?php

declare(strict_types=1);

require __DIR__ . '/app/bootstrap.php';

function dental_login_destination(array $user): string
{
    $ready = !app_update_pending();
    $destination = $ready && ($user['role'] ?? '') === 'dentist'
        ? 'clinical_day.php'
        : ($ready ? 'dashboard.php' : (($user['role'] ?? '') === 'super_admin' ? 'system_setup.php?tab=updates' : 'dashboard.php'));
    if ($ready && function_exists('staff_profile_dual_role_schema_ready') && staff_profile_dual_role_schema_ready()) {
        $profileCheck = db()->prepare('SELECT profile_completed_at FROM `' . table('users') . '` WHERE id=? LIMIT 1');
        $profileCheck->execute([(int)$user['id']]);
        if (!$profileCheck->fetchColumn()) $destination = 'my_profile.php?complete=1';
    }
    return $destination;
}

function dental_login_complete(array $user, bool $mfaVerified, string $destination): never
{
    session_regenerate_id(true);
    $_SESSION['user'] = [
        'id' => (int)$user['id'],
        'branch_id' => $user['branch_id'] !== null ? (int)$user['branch_id'] : null,
        'name' => (string)$user['name'],
        'email' => (string)$user['email'],
        'role' => (string)$user['role'],
    ];
    if (function_exists('user_assigned_role_codes')) {
        $_SESSION['user']['role_codes'] = user_assigned_role_codes((int)$user['id']);
    }
    if (function_exists('dental_mfa_initialize_staff_session')) {
        dental_mfa_initialize_staff_session($_SESSION['user'], $mfaVerified);
    }
    if (!app_demo_read_only()) {
        db()->prepare('UPDATE `' . table('users') . '` SET last_login_at=NOW(),updated_at=NOW() WHERE id=?')->execute([(int)$user['id']]);
        if (function_exists('dental_security_record_login_attempt')) {
            dental_security_record_login_attempt((string)$user['email'], true, (int)$user['id']);
        }
        if (function_exists('dental_security_track_current_session')) {
            dental_security_track_current_session($_SESSION['user']);
        }
        audit('login', 'user', (int)$user['id'], ['mfa_verified'=>$mfaVerified]);
    }
    if (function_exists('dental_mfa_enrollment_required_for_current_user')
        && dental_mfa_enrollment_required_for_current_user()) {
        $destination = 'my_profile.php?security=1&enroll_mfa=1';
    } elseif (function_exists('dental_mfa_user_requires_enrollment')
        && dental_mfa_user_requires_enrollment($_SESSION['user'])
        && function_exists('dental_mfa_bootstrap_access_allowed')
        && dental_mfa_bootstrap_access_allowed($_SESSION['user'])) {
        flash('warning', 'MFA rollout recovery is active for the signed-in Superuser. You can use the system and return to the Superuser workspace, but enroll an authenticator before enabling strict enforcement for other privileged accounts.');
    } elseif (function_exists('dental_mfa_dentist_limited_access_allowed')
        && dental_mfa_dentist_limited_access_allowed($_SESSION['user'])) {
        flash('warning', 'Dentist workspace opened in limited mode. You can review schedules, patients, and complete your profiles, but clinical editing and prescribing remain locked until MFA enrollment is complete.');
    }
    header('Location: ' . $destination);
    exit;
}

if (current_user()) {
    $ready = !app_update_pending();
    $destination = $ready && actual_role() === 'dentist' ? 'clinical_day.php' : ($ready ? 'dashboard.php' : (has_role('super_admin') ? 'system_setup.php?tab=updates' : 'dashboard.php'));
    header('Location: ' . $destination);
    exit;
}

$error = '';
$pendingMfa = function_exists('dental_mfa_pending_login') ? dental_mfa_pending_login() : null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        $action = (string)($_POST['action'] ?? 'password_login');

        if ($action === 'cancel_mfa') {
            if (function_exists('dental_mfa_clear_pending_login')) dental_mfa_clear_pending_login();
            header('Location: login.php');
            exit;
        }

        if ($action === 'verify_mfa') {
            $pendingMfa = function_exists('dental_mfa_pending_login') ? dental_mfa_pending_login() : null;
            if (!$pendingMfa || !is_array($pendingMfa['user'] ?? null)) {
                throw new RuntimeException('The MFA sign-in session expired. Enter your email and password again.');
            }
            $_SESSION['mfa_pending_login']['attempts'] = (int)($_SESSION['mfa_pending_login']['attempts'] ?? 0) + 1;
            $code = trim((string)($_POST['mfa_code'] ?? ''));
            $user = $pendingMfa['user'];
            if (!function_exists('dental_mfa_verify_user_code') || !dental_mfa_verify_user_code((int)$user['id'], $code, true)) {
                if (function_exists('dental_security_record_event')) {
                    dental_security_record_event('mfa_login_failure', 'warning', ['attempt'=>(int)$_SESSION['mfa_pending_login']['attempts']], (int)$user['id'], 'user', (int)$user['id']);
                }
                throw new RuntimeException('The authenticator or recovery code is incorrect.');
            }
            $destination = (string)($pendingMfa['destination'] ?? dental_login_destination($user));
            if (function_exists('dental_mfa_clear_pending_login')) dental_mfa_clear_pending_login();
            if (function_exists('dental_security_record_event')) {
                dental_security_record_event('mfa_login_success', 'info', [], (int)$user['id'], 'user', (int)$user['id']);
            }
            dental_login_complete($user, true, $destination);
        }

        $email = strtolower(trim((string)($_POST['email'] ?? '')));
        $password = (string)($_POST['password'] ?? '');
        if (!filter_var($email, FILTER_VALIDATE_EMAIL) || $password === '') {
            throw new RuntimeException('Enter a valid email address and password.');
        }
        if (function_exists('dental_security_login_throttle_status')) {
            $throttle = dental_security_login_throttle_status($email);
            if (!empty($throttle['blocked'])) {
                $waitMinutes = max(1, (int)ceil(((int)($throttle['remaining_seconds'] ?? 60)) / 60));
                throw new RuntimeException('Too many failed sign-in attempts. Try again in about ' . $waitMinutes . ' minute' . ($waitMinutes === 1 ? '' : 's') . '.');
            }
        }

        $stmt = db()->prepare(
            'SELECT u.id,u.name,u.email,u.password_hash,u.status,u.branch_id,r.code AS role '
            . 'FROM `' . table('users') . '` u JOIN `' . table('roles') . '` r ON r.id=u.role_id '
            . 'WHERE LOWER(u.email)=? LIMIT 1'
        );
        $stmt->execute([$email]);
        $user = $stmt->fetch();
        $failureReason = (!$user || !is_array($user)) ? 'unknown_account' : ((string)($user['status'] ?? '') !== 'active' ? 'inactive_or_locked' : 'invalid_password');
        if (!$user || (string)$user['status'] !== 'active' || !password_verify($password, (string)$user['password_hash'])) {
            if (function_exists('dental_security_record_login_attempt')) {
                dental_security_record_login_attempt($email, false, $user && is_array($user) ? (int)$user['id'] : null, $failureReason);
            }
            throw new RuntimeException('Invalid email or password.');
        }

        $destination = dental_login_destination($user);
        if (function_exists('dental_mfa_user_enabled') && dental_mfa_user_enabled((int)$user['id'])) {
            dental_mfa_begin_pending_login($user, $destination);
            if (function_exists('dental_security_record_event')) {
                dental_security_record_event('password_verified_mfa_required', 'info', [], (int)$user['id'], 'user', (int)$user['id']);
            }
            header('Location: login.php?mfa=1');
            exit;
        }

        dental_login_complete($user, false, $destination);
    } catch (Throwable $exception) {
        $error = $exception->getMessage();
        $pendingMfa = function_exists('dental_mfa_pending_login') ? dental_mfa_pending_login() : null;
    }
}

$appName = (string)app_config('app.name', 'Dental Appointment and Records System');
$isMfaStage = is_array($pendingMfa) && is_array($pendingMfa['user'] ?? null);
?><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="public/assets/css/app.css">
    <link rel="icon" href="public/favicon.svg" type="image/svg+xml">
    <link rel="alternate icon" href="public/favicon.ico">
    <title><?= $isMfaStage ? 'Verify sign-in' : 'Staff Login' ?> · <?=e($appName)?></title>
</head>
<body class="public-page login-page">
<section class="login-shell">
    <div class="login-brand">
        <a class="brand" href="index.php"><span class="mark">DC</span><span><?=e($appName)?></span></a>
        <h1><?= $isMfaStage ? 'Verify your identity' : 'Welcome back' ?></h1>
        <p><?= $isMfaStage ? 'Enter the current code from your authenticator app or one unused recovery code.' : 'Sign in to your role-specific clinic workspace.' ?></p>
        <?php if(app_demo_read_only()):?><div class="demo-login-note"><strong>Read-only demonstration</strong><span>No record can be added, changed, deleted, imported, reset, emailed, or processed.</span></div><?php endif;?>
    </div>
    <?php if($isMfaStage):?>
    <form method="post" class="login-card" autocomplete="off">
        <input type="hidden" name="csrf" value="<?=e(csrf_token())?>">
        <?php if($error !== ''):?><div class="flash error"><?=e($error)?></div><?php endif;?>
        <p><strong><?=e((string)($pendingMfa['user']['name'] ?? 'Staff account'))?></strong><br><small><?=e((string)($pendingMfa['user']['email'] ?? ''))?></small></p>
        <label>Authenticator or recovery code<input name="mfa_code" inputmode="numeric" autocomplete="one-time-code" autofocus required maxlength="20"></label>
        <button class="btn primary" type="submit" name="action" value="verify_mfa">Verify and sign in</button>
        <button class="btn ghost" type="submit" name="action" value="cancel_mfa" formnovalidate>Use another account</button>
    </form>
    <?php else:?>
    <form method="post" class="login-card" autocomplete="on">
        <input type="hidden" name="csrf" value="<?=e(csrf_token())?>">
        <input type="hidden" name="action" value="password_login">
        <?php if($error !== ''):?><div class="flash error"><?=e($error)?></div><?php endif;?>
        <?php if(app_demo_read_only()):?><div class="demo-credentials"><strong>Demo accounts</strong><code>dentist@demo.dentalcare.local</code><code>admin@demo.dentalcare.local</code><small>Password for all demo accounts: <b>DentalDemo2026!</b></small></div><?php endif;?>
        <label>Email<input type="email" name="email" required autofocus autocomplete="username"></label>
        <label>Password<input type="password" name="password" required autocomplete="current-password"></label>
        <button class="btn primary" type="submit">Sign in</button>
        <a href="index.php">Return to public site</a>
    </form>
    <?php endif;?>
</section>
<footer class="login-developer-footer">Developer &amp; Programmer: <a href="mailto:mtbcustomprints@gmail.com">MTBCustoms</a> <span>mtbcustomprints@gmail.com</span></footer>
</body>
</html>
