<?php
// ============================================
// Remember-Me: 30-day persistent login
// ============================================
if (!defined('REMEMBER_DAYS')) define('REMEMBER_DAYS', 30);
if (!defined('REMEMBER_COOKIE')) define('REMEMBER_COOKIE', 'nid_remember');

function remember_cookie_path(){
    $p = defined('BASE_URL') ? BASE_URL : '/';
    if ($p === '' || $p[0] !== '/') $p = '/'.$p;
    return $p ?: '/';
}

function remember_issue($pdo, $user_id){
    $selector = bin2hex(random_bytes(9));      // 18 chars
    $validator = bin2hex(random_bytes(32));    // 64 chars
    $hash = password_hash($validator, PASSWORD_BCRYPT);
    $exp  = date('Y-m-d H:i:s', time() + REMEMBER_DAYS*86400);
    $pdo->prepare("INSERT INTO remember_tokens(user_id,selector,token_hash,expires_at) VALUES(?,?,?,?)")
        ->execute([$user_id, $selector, $hash, $exp]);
    $cookie = $selector.':'.$validator;
    setcookie(REMEMBER_COOKIE, $cookie, [
        'expires'  => time() + REMEMBER_DAYS*86400,
        'path'     => remember_cookie_path(),
        'secure'   => !empty($_SERVER['HTTPS']),
        'httponly' => true,
        'samesite' => 'Lax',
    ]);
}

function remember_try_login($pdo){
    if (!empty($_SESSION['uid'])) return;
    if (empty($_COOKIE[REMEMBER_COOKIE])) return;
    $parts = explode(':', $_COOKIE[REMEMBER_COOKIE], 2);
    if (count($parts) !== 2) return;
    [$selector, $validator] = $parts;
    try {
        $s = $pdo->prepare("SELECT * FROM remember_tokens WHERE selector=? LIMIT 1");
        $s->execute([$selector]);
        $row = $s->fetch();
    } catch (Throwable $e) { return; } // table might not exist yet
    if (!$row) return;
    if (strtotime($row['expires_at']) < time()) {
        $pdo->prepare("DELETE FROM remember_tokens WHERE id=?")->execute([$row['id']]);
        return;
    }
    if (!password_verify($validator, $row['token_hash'])) return;
    // rotate token for security
    $pdo->prepare("DELETE FROM remember_tokens WHERE id=?")->execute([$row['id']]);
    $_SESSION['uid'] = (int)$row['user_id'];
    remember_issue($pdo, (int)$row['user_id']);
}

function remember_clear($pdo){
    if (!empty($_COOKIE[REMEMBER_COOKIE])) {
        $parts = explode(':', $_COOKIE[REMEMBER_COOKIE], 2);
        if (count($parts) === 2) {
            try { $pdo->prepare("DELETE FROM remember_tokens WHERE selector=?")->execute([$parts[0]]); }
            catch (Throwable $e) {}
        }
        setcookie(REMEMBER_COOKIE, '', [
            'expires' => time()-3600,
            'path'    => remember_cookie_path(),
        ]);
        unset($_COOKIE[REMEMBER_COOKIE]);
    }
    if (!empty($_SESSION['uid'])) {
        try { $pdo->prepare("DELETE FROM remember_tokens WHERE user_id=?")->execute([$_SESSION['uid']]); }
        catch (Throwable $e) {}
    }
}
