<?php
declare(strict_types=1);

require_once __DIR__ . '/config.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_name(defined('SESSION_COOKIE_NAME') ? SESSION_COOKIE_NAME : 'cg_platform_session');
    session_start();
}

function api_json(array $payload, int $status = 200): void
{
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($payload);
    exit;
}

function get_active_family_session(): ?array
{
    if (empty($_SESSION['caregiver_session_token'])) {
        return null;
    }

    $token = (string) $_SESSION['caregiver_session_token'];

    $stmt = db()->prepare("
        SELECT s.*, f.family_name, f.family_slug, c.name AS caregiver_name, c.username AS caregiver_username
        FROM app_sessions s
        LEFT JOIN families f ON f.id = s.family_id
        LEFT JOIN caregiver_accounts c ON c.id = s.user_id
        WHERE s.session_token = ?
          AND s.user_type = 'caregiver'
          AND (s.expires_at IS NULL OR s.expires_at > NOW())
        LIMIT 1
    ");
    $stmt->execute([$token]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    return $row ?: null;
}

function require_family_session(): array
{
    $session = get_active_family_session();

    if (!$session) {
        api_json([
            'success' => false,
            'message' => 'Family session required.'
        ], 403);
    }

    return $session;
}