<?php
// api/public/auth.php - For public user authentication

require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../../helpers/response.php';
require_once __DIR__ . '/../../helpers/request.php';

function requirePublicAuth() {
    $token = getBearerToken();
    
    if (!$token) {
        error_log('requirePublicAuth: no bearer token found in request');
        sendError('Authentication required', 401);
    }
    
    global $pdo;
    $stmt = $pdo->prepare("
        SELECT u.*, t.token 
        FROM public_users u
        JOIN public_user_tokens t ON t.user_id = u.id
        WHERE t.token = ? AND (t.expires_at IS NULL OR t.expires_at > NOW()) AND u.status = 'active'
    ");
    $stmt->execute([$token]);
    $user = $stmt->fetch();
    
    if (!$user) {
        $short = strlen($token) > 16 ? substr($token,0,16) . '...' : $token;
        error_log('requirePublicAuth: token not found or expired in DB: ' . $short);
        sendError('Invalid or expired token', 401);
    }
    
    return $user;
}

function isPublicUserLoggedIn() {
    $headers = getallheaders();
    $token = str_replace('Bearer ', '', $headers['Authorization'] ?? '');
    
    if (!$token) return false;
    
    global $pdo;
    $stmt = $pdo->prepare("
        SELECT user_id FROM public_user_tokens 
        WHERE token = ? AND (expires_at IS NULL OR expires_at > NOW())
    ");
    $stmt->execute([$token]);
    
    return $stmt->fetch() !== false;
}
?>