<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/api_auth.php';

try {
    $session = get_active_family_session();

    if (!$session) {
        api_json([
            'success' => true,
            'authenticated' => false,
            'message' => 'No active caregiver session.',
            'session' => null,
            'family' => null,
            'caregiver' => null,
            'clients' => [],
            'caregivers' => []
        ], 200);
    }

    $familyId = (int)($session['family_id'] ?? 0);
    $caregiverId = (int)($session['user_id'] ?? 0);
    $familySlug = trim((string)($session['family_slug'] ?? ''));
    $familyName = trim((string)($session['family_name'] ?? ''));
    $caregiverName = trim((string)($session['caregiver_name'] ?? ''));
    $caregiverUsername = trim((string)($session['caregiver_username'] ?? ''));

    $clientsStmt = db()->prepare('
        SELECT id, client_name, is_active, created_at, updated_at
        FROM clients
        WHERE family_id = ?
          AND is_active = 1
        ORDER BY client_name ASC
    ');
    $clientsStmt->execute([$familyId]);
    $clients = array_map(static function (array $row): array {
        return [
            'id' => (int)$row['id'],
            'client_name' => (string)($row['client_name'] ?? ''),
            'name' => (string)($row['client_name'] ?? ''),
            'is_active' => (int)($row['is_active'] ?? 0),
            'created_at' => $row['created_at'] ?? null,
            'updated_at' => $row['updated_at'] ?? null,
        ];
    }, $clientsStmt->fetchAll(PDO::FETCH_ASSOC));

    $caregivers = [];
    try {
        $caregiversStmt = db()->prepare('
            SELECT id, name, username, is_active
            FROM caregiver_accounts
            WHERE family_id = ?
            ORDER BY name ASC, username ASC
        ');
        $caregiversStmt->execute([$familyId]);
        $caregivers = array_map(static function (array $row): array {
            return [
                'id' => (int)$row['id'],
                'name' => (string)($row['name'] ?? $row['username'] ?? ''),
                'caregiver_name' => (string)($row['name'] ?? ''),
                'username' => (string)($row['username'] ?? ''),
                'is_active' => isset($row['is_active']) ? (int)$row['is_active'] : 1,
            ];
        }, $caregiversStmt->fetchAll(PDO::FETCH_ASSOC));
    } catch (Throwable $inner) {
        $caregivers = [];
    }

    api_json([
        'success' => true,
        'authenticated' => true,
        'message' => 'Session loaded.',
        'session' => [
            'family_id' => $familyId,
            'caregiver_id' => $caregiverId,
            'username' => $caregiverUsername,
            'name' => $caregiverName,
            'family_slug' => $familySlug,
            'family_name' => $familyName,
        ],
        'family' => [
            'id' => $familyId,
            'family_slug' => $familySlug,
            'family_name' => $familyName,
        ],
        'caregiver' => [
            'id' => $caregiverId,
            'username' => $caregiverUsername,
            'name' => $caregiverName,
        ],
        'clients' => $clients,
        'caregivers' => $caregivers
    ]);
} catch (Throwable $e) {
    error_log('bootstrap_data.php error: ' . $e->getMessage());

    api_json([
        'success' => false,
        'authenticated' => false,
        'message' => 'server error',
        'error' => $e->getMessage(),
        'session' => null,
        'family' => null,
        'caregiver' => null,
        'clients' => [],
        'caregivers' => []
    ], 500);
}