<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_documentation_schema();
require DENTAL_ROOT . '/app/layout.php';

$portalReauthentication = (string)($_GET['portal_reauth'] ?? '') === '1';
if ($portalReauthentication) {
    // A portal request that could not read its session must terminate the old
    // portal state instead of bouncing back to the portal automatically.
    unset($_SESSION['patient_user'], $_SESSION['portal_patient_id'], $_SESSION['patient_last_activity']);
} elseif (patient_portal_user()) {
    header('Location: ' . dental_clean_url('patient-portal.php'), true, 303);
    exit;
}

$error='';
if ($_SERVER['REQUEST_METHOD']==='POST') {
    verify_csrf();
    $email=strtolower(trim((string)($_POST['email']??'')));
    if (!filter_var($email, FILTER_VALIDATE_EMAIL) || (string)($_POST['password'] ?? '') === '') {
        $error='Enter a valid email address and password.';
    }
    $throttle = function_exists('dental_security_login_throttle_status') ? dental_security_login_throttle_status('patient:' . $email) : ['blocked' => false];
    if ($error === '' && !empty($throttle['blocked'])) {
        $waitMinutes=max(1,(int)ceil(((int)($throttle['remaining_seconds']??60))/60));
        $error='Too many failed sign-in attempts. Try again in about ' . $waitMinutes . ' minute' . ($waitMinutes===1?'':'s') . '.';
    }
    $stmt=db()->prepare('SELECT * FROM `' . table('patient_portal_accounts') . '` WHERE LOWER(email)=? LIMIT 1');
    if ($error === '') $stmt->execute([$email]);
    $account=$error === '' ? $stmt->fetch() : false;
    if($error === '' && (!$account||$account['status']!=='active'||empty($account['password_hash'])||!password_verify((string)($_POST['password']??''),(string)$account['password_hash']))){
        if (function_exists('dental_security_record_login_attempt')) dental_security_record_login_attempt('patient:' . $email, false, null, 'patient_portal_invalid_credentials');
        $error='The email or password is incorrect.';
    } else {
        $patients=patient_portal_account_patients((int)$account['id']);
        if(!$patients){
            $error='This portal account has no active patient authorization. Contact the clinic.';
        } else {
            session_regenerate_id(true);
            $selected=$patients[0];
            $_SESSION['patient_user']=[
                'id'=>(int)$account['id'],
                'patient_id'=>(int)$selected['patient_id'],
                'name'=>trim((string)$selected['first_name'].' '.(string)$selected['last_name']),
                'email'=>(string)$account['email'],
                'is_guardian'=>empty($selected['is_self']),
            ];
            $_SESSION['portal_patient_id']=(int)$selected['patient_id'];
            $_SESSION['patient_last_activity']=time();
            if(!app_demo_read_only())db()->prepare('UPDATE `' . table('patient_portal_accounts') . '` SET last_login_at=NOW() WHERE id=?')->execute([(int)$account['id']]);
            if (function_exists('dental_security_record_login_attempt')) dental_security_record_login_attempt('patient:' . $email, true, null);
            header('Location: ' . dental_clean_url('patient-portal.php?signed_in=1'), true, 303);
            exit;
        }
    }
}

render_header('Patient Portal',true);render_public_nav();
?>
<main class="portal-main"><section class="card portal-login-card"><h1>Patient and Guardian Portal</h1><p>Securely review authorized appointments, treatment plans, statements, prescriptions, and shared documents.</p><?php if(app_demo_read_only()):?><div class="alert info"><strong>Read-only demo:</strong> use <code>patient@demo.dentalcare.local</code> with password <code>DentalDemo2026!</code>. Patient actions are disabled.</div><?php endif;?><?php if($error):?><div class="alert error"><?=e($error)?></div><?php endif;?><form method="post" class="form-grid"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><label class="wide">Email<input type="email" name="email" required></label><label class="wide">Password<input type="password" name="password" required></label><button class="btn primary">Sign in</button></form><p><small>Portal access is created by the dental clinic. Guardians must be verified and specifically authorized for each dependent.</small></p></section></main>
<?php render_public_footer();render_footer(true); ?>
