<?php
session_start(['gc_maxlifetime' => 14400, 'cookie_httponly' => true]);
include('member_session.php');
include('../coach/functions.php');
include('../coach/objects/class.cardio_phase.php');

$member_id = $_SESSION['memberid'] ?? 0;
$cardio_id = (int)($_GET['cardio_ids'] ?? $_POST['cardio_ids'] ?? 0);

$cardio = null;

if ($cardio_id > 0) {
    $cardio_class = new Cardio_phase();
    $rows = $cardio_class->GetList([["cardio_phaseId IN (" . $cardio_id . ")"]]);
    if (!empty($rows)) {
        $cardio = $rows[0];
    }
}

$page_title = ($cardio && !empty($cardio->filename)) ? 'CARDIO ' . $cardio->filename : 'Cardio';

function cc_val($value): string
{
    $value = trim((string)$value);
    return $value !== '' ? strtoupper($value) : '-';
}

/**
 * Builds the 4-zone heart-rate table rows for one program type
 * (steady state or interval training). HRR%/RPE bands are fixed
 * per zone by design, only the heart-rate value is per-member data.
 */
function cc_zone_rows(object $cardio, string $prefix): array
{
    $bands = [
        1 => ['hrr' => '40-60%',  'rpe' => '3-4'],
        2 => ['hrr' => '61-80%',  'rpe' => '5-6'],
        3 => ['hrr' => '81-90%',  'rpe' => '7-8'],
        4 => ['hrr' => '91-100%', 'rpe' => '9-10'],
    ];
    $rows = [];
    foreach ($bands as $zone => $band) {
        $field = $prefix . '_' . $zone . 'heartrate';
        $rows[] = [
            'zone' => $zone,
            'hr'   => cc_val($cardio->$field ?? ''),
            'hrr'  => $band['hrr'],
            'rpe'  => $band['rpe'],
        ];
    }
    return $rows;
}

function render_cardio_zone_table(array $rows): void
{
    ?>
    <div class="cc-table-wrap">
        <table class="cc-zones-table">
            <thead>
                <tr>
                    <th class="cc-th-zone">Zone</th>
                    <th class="cc-th-hr">Heart Rate (BPM)</th>
                    <th class="cc-th-hrr">HRR %</th>
                    <th class="cc-th-rpe">RPE</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rows as $row): ?>
                    <tr>
                        <td class="cc-td-zone">Zone <?php echo (int)$row['zone']; ?></td>
                        <td class="cc-td-hr"><?php echo htmlspecialchars($row['hr']); ?></td>
                        <td class="cc-td-hrr"><?php echo htmlspecialchars($row['hrr']); ?></td>
                        <td class="cc-td-rpe"><?php echo htmlspecialchars($row['rpe']); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php
}

function cc_info_icon(string $key): string
{
    $icons = [
        'phase' => '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M5 21L5 19C5 17.9391 5.42143 16.9217 6.17157 16.1716C6.92172 15.4214 7.93914 15 9 15L15 15C16.0609 15 17.0783 15.4214 17.8284 16.1716C18.5786 16.9217 19 17.9391 19 19L19 21" stroke="black" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round" /><path d="M12 11C9.79086 11 8 9.20914 8 7C8 4.79086 9.79086 3 12 3C14.2091 3 16 4.79086 16 7C16 9.20914 14.2091 11 12 11Z" stroke="black" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round" /></svg>',
        'freq'  => '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M16 2L16 6" stroke="black" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round" /><path d="M8 2L8 6" stroke="black" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round" /><path d="M5 4L19 4C20.1046 4 21 4.89543 21 6L21 20C21 21.1046 20.1046 22 19 22L5 22C3.89543 22 3 21.1046 3 20L3 6C3 4.89543 3.89543 4 5 4Z" stroke="black" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round" /><path d="M21 10L3 10" stroke="black" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round" /></svg>',
        'clock' => '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5229 2 22 6.47715 22 12C22 17.5229 17.5228 22 12 22Z" stroke="black" stroke-linecap="round" stroke-linejoin="round" /><path d="M12 6L12 12L8 14" stroke="black" stroke-linecap="round" stroke-linejoin="round" /></svg>',
        'target' => '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 22C17.5229 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5229 6.47715 22 12 22Z" stroke="black" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round" /><path d="M12 18C15.3137 18 18 15.3137 18 12C18 8.68629 15.3137 6 12 6C8.68629 6 6 8.68629 6 12C6 15.3137 8.68629 18 12 18Z" stroke="black" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round" /><path d="M12 14C13.1046 14 14 13.1046 14 12C14 10.8954 13.1046 10 12 10C10.8954 10 10 10.8954 10 12C10 13.1046 10.8954 14 12 14Z" stroke="black" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round" /></svg>',
    ];
    return $icons[$key] ?? '';
}

function render_cardio_week_card(string $title, string $phaseLevel, string $frequency, string $warmup, string $targetTime, string $cooldown): void
{
    ?>
    <div class="cc-week-card">
        <div class="cc-week-header">
            <h3 class="cc-week-title"><?php echo htmlspecialchars($title); ?></h3>
        </div>
        <div class="cc-week-body">
            <div class="cc-info-row">
                <div class="cc-info-label">
                    <span class="cc-info-icon"><?php echo cc_info_icon('phase'); ?></span>
                    <span class="cc-info-text">Phase/Level</span>
                </div>
                <div class="cc-info-value"><?php echo htmlspecialchars($phaseLevel !== '' ? $phaseLevel : '-'); ?></div>
            </div>
            <div class="cc-info-row">
                <div class="cc-info-label">
                    <span class="cc-info-icon"><?php echo cc_info_icon('freq'); ?></span>
                    <span class="cc-info-text">Frequency/Wk</span>
                </div>
                <div class="cc-info-value"><?php echo htmlspecialchars($frequency !== '' ? $frequency . 'X' : '-'); ?></div>
            </div>
            <div class="cc-info-row">
                <div class="cc-info-label">
                    <span class="cc-info-icon"><?php echo cc_info_icon('clock'); ?></span>
                    <span class="cc-info-text">Warm-Up</span>
                </div>
                <div class="cc-info-value"><?php echo htmlspecialchars($warmup !== '' ? $warmup : '-'); ?></div>
            </div>
            <div class="cc-info-row">
                <div class="cc-info-label">
                    <span class="cc-info-icon"><?php echo cc_info_icon('target'); ?></span>
                    <span class="cc-info-text">Target Time</span>
                </div>
                <div class="cc-info-value"><?php echo htmlspecialchars($targetTime !== '' ? $targetTime : '-'); ?></div>
            </div>
            <div class="cc-info-row">
                <div class="cc-info-label">
                    <span class="cc-info-icon"><?php echo cc_info_icon('phase'); ?></span>
                    <span class="cc-info-text">Cool Down</span>
                </div>
                <div class="cc-info-value"><?php echo htmlspecialchars($cooldown !== '' ? $cooldown : '-'); ?></div>
            </div>
        </div>
    </div>
    <?php
}

function render_cardio_section(string $title, array $zoneRows, array $weeks12, array $weeks34, string $collapse_id, bool $is_open): void
{
    ?>
    <div class="accordion-item">
        <h2 class="accordion-header">
            <button class="accordion-button<?php echo $is_open ? '' : ' collapsed'; ?>" type="button" data-bs-toggle="collapse"
                data-bs-target="#<?php echo $collapse_id; ?>" aria-expanded="<?php echo $is_open ? 'true' : 'false'; ?>">
                <div class="ph-accordion-left"><?php echo htmlspecialchars($title); ?></div>
                <div class="ph-accordion-right">
                    <svg class="edit-ph-section-chevron" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M6 9L12 15L18 9" stroke="black" stroke-opacity="0.5" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round" />
                    </svg>
                </div>
            </button>
        </h2>
        <div id="<?php echo $collapse_id; ?>" class="accordion-collapse collapse<?php echo $is_open ? ' show' : ''; ?>"
            data-bs-parent="#portalHomeworkAccordion">
            <div class="accordion-body">
                <div class="ph-accordion-content">
                    <?php render_cardio_zone_table($zoneRows); ?>
                    <div class="cc-weeks-grid">
                        <?php
                        render_cardio_week_card('Weeks 1-2', $weeks12['phaseLevel'], $weeks12['frequency'], $weeks12['warmup'], $weeks12['targettime'], $weeks12['cooldown']);
                        render_cardio_week_card('Weeks 3-4', $weeks34['phaseLevel'], $weeks34['frequency'], $weeks34['warmup'], $weeks34['targettime'], $weeks34['cooldown']);
                        ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php
}

function cc_phase_level(object $cardio, string $phaseField, string $levelField): string
{
    $phase = trim((string)($cardio->$phaseField ?? ''));
    $level = trim((string)($cardio->$levelField ?? ''));
    if ($phase === '' && $level === '') {
        return '';
    }
    return $phase . ($level !== '' ? '/Level ' . $level : '');
}

if ($cardio) {
    $steadyZones = cc_zone_rows($cardio, 'steadystate');
    $intervalZones = cc_zone_rows($cardio, 'training');

    $steadyWeeks12 = [
        'phaseLevel' => cc_phase_level($cardio, 'steadystate_phasefirst', 'steadystate_levelfirst'),
        'frequency'  => trim((string)$cardio->steadystate_week12_frequency),
        'warmup'     => trim((string)$cardio->steadystate_week12_warmup),
        'targettime' => trim((string)$cardio->steadystate_week12_targettime),
        'cooldown'   => trim((string)$cardio->steadystate_week12_cooldown),
    ];
    $steadyWeeks34 = [
        'phaseLevel' => cc_phase_level($cardio, 'training_phasethird', 'training_levelthird'),
        'frequency'  => trim((string)$cardio->steadystate_week34_frequency),
        'warmup'     => trim((string)$cardio->steadystate_week34_warmup),
        'targettime' => trim((string)$cardio->steadystate_week34_targettime),
        'cooldown'   => trim((string)$cardio->steadystate_week34_cooldown),
    ];
    $intervalWeeks12 = [
        'phaseLevel' => cc_phase_level($cardio, 'steadystate_phasesecond', 'steadystate_levelsecond'),
        'frequency'  => trim((string)$cardio->training_week12_frequency),
        'warmup'     => trim((string)$cardio->training_week12_warmup),
        'targettime' => trim((string)$cardio->training_week12_targettime),
        'cooldown'   => trim((string)$cardio->training_week12_cooldown),
    ];
    $intervalWeeks34 = [
        'phaseLevel' => cc_phase_level($cardio, 'training_phasefourth', 'training_levelfourth'),
        'frequency'  => trim((string)$cardio->training_week34_frequency),
        'warmup'     => trim((string)$cardio->training_week34_warmup),
        'targettime' => trim((string)$cardio->training_week34_targettime),
        'cooldown'   => trim((string)$cardio->training_week34_cooldown),
    ];
}

include('member-header.php');
?>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
<link href="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.snow.css" rel="stylesheet">
<link rel="stylesheet" href="./new.css">

<!-- Mobile Top Bar (logo centered) -->
<div class="mobile-top-bar">
    <img src="./assets/images/logo.png" alt="Brand Logo">
</div>

<div class="app-layout">
    <?php include('menu.php'); ?>

    <main class="main-content">
        <header class="page-header">
            <div class="page-header-meta">
                <div>
                    <h1 class="page-header-title"><?php echo htmlspecialchars($page_title); ?></h1>
                    <p class="page-header-subtitle">Your coach-prescribed cardio program</p>
                </div>
            </div>
        </header>

        <div class="body-content">
            <div class="">
                <?php if (!$cardio): ?>
                    <div class="empty-state">
                        <p class="empty-state-text">No cardio program found.</p>
                    </div>
                <?php else: ?>
                    <div class="accordion ph-accordion" id="portalHomeworkAccordion">
                        <?php
                        render_cardio_section('STEADY STATE', $steadyZones, $steadyWeeks12, $steadyWeeks34, 'collapseSteadyState', true);
                        render_cardio_section('INTERVAL TRAINING', $intervalZones, $intervalWeeks12, $intervalWeeks34, 'collapseIntervalTraining', false);
                        ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </main>
</div>

<div id="mobile-nav-placeholder"></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="./js/layout.js"></script>

<?php include('member-footer.php'); ?>
