<?php
require_once 'config/config.php';
require_once 'includes/db.php';
require_once 'includes/utils.php';
require_once 'includes/persona.php';
require_once 'includes/family_settings.php';

startFamilyHubSession();

$people = migrateAllPeople(normalizePeopleList(readJsonFile('people.json')));
if (getActivePersonId() !== null && getActivePerson($people) === null) {
    clearPersonaSession();
}

$activePerson = getActivePerson($people);
$familySettings = loadFamilySettings();

if (isset($TABS['currency'])) {
    $TABS['currency']['title'] = currencyTabLabel($familySettings);
}

$hasHeadOfHousehold = familyHubHasHeadOfHousehold($people);
$showSettingsTab = !$hasHeadOfHousehold
    || (
        $activePerson !== null
        && ($activePerson['role'] ?? '') === ROLE_HEAD
        && isHohVerified()
    );

$navTabs = $TABS;
if (!$showSettingsTab) {
    unset($navTabs['settings']);
}

$activeTab = isset($_GET['tab']) ? (string) $_GET['tab'] : 'chores';
if (!isset($TABS[$activeTab])) {
    $activeTab = 'chores';
}

if (
    isset($_GET['tab'])
    && (string) $_GET['tab'] === 'settings'
    && !$showSettingsTab
) {
    header('Location: ?tab=chores', true, 303);
    exit;
}

if (!isset($navTabs[$activeTab])) {
    $firstNav = array_key_first($navTabs);
    $activeTab = is_string($firstNav) ? $firstNav : 'chores';
}

$isCalendarTvView = $activeTab === 'calendar' && isset($_GET['view']) && (string) $_GET['view'] === 'tv';

$familyHubApiBase = familyHubWebApiBase();

$favoriteColor = '#4a90e2';
if (
    $activePerson !== null
    && !empty($activePerson['favoriteColor'])
    && preg_match('/^#[0-9A-Fa-f]{6}$/', (string) $activePerson['favoriteColor'])
) {
    $favoriteColor = (string) $activePerson['favoriteColor'];
}
$headerThemeClass = 'header-tone-dark';
if (preg_match('/^#([0-9A-Fa-f]{6})$/', $favoriteColor, $m)) {
    $hex = $m[1];
    $r = hexdec(substr($hex, 0, 2));
    $g = hexdec(substr($hex, 2, 2));
    $b = hexdec(substr($hex, 4, 2));
    $relativeLuminance = (0.2126 * $r + 0.7152 * $g + 0.0722 * $b) / 255;
    if ($relativeLuminance >= 0.62) {
        $headerThemeClass = 'header-tone-light';
    }
}

include 'includes/header.php';
?>

<div class="<?= $isCalendarTvView ? 'container-fluid px-3 py-3' : 'container' ?>">
    <div class="tab-content" id="dashboardContentArea">
        <?php include 'tabs/' . $activeTab . '.php'; ?>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
