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

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

$corrective_details  = [];
$strength_details    = [];
$flexibility_details = [];
$enabled_videolinks  = '0';
$homework_title      = '';
$weight_by_row       = []; // "{homework_detailsId}|{section}" => ['current' => ?, 'previous' => ?]

if ($homework_id > 0) {
    $ids = [];
    for ($i = $homework_id; $i < ($homework_id + 6); $i++) {
        $ids[] = $i;
    }

    // IDOR guard: only ids that are actually mapped to the logged-in member
    // may be shown/tracked — homework_ids is attacker-controllable via the
    // query string, and other members' programs use the same id sequence.
    $owned_ids = [];
    $stmt = mysqli_prepare(
        $connection,
        "SELECT homework_detailsid FROM homework_detailsmembermap WHERE memberid = ? AND homework_detailsid IN (" .
            implode(',', array_fill(0, count($ids), '?')) . ")"
    );
    $bind_types  = 'i' . str_repeat('i', count($ids));
    $bind_params = array_merge([$member_id], $ids);
    mysqli_stmt_bind_param($stmt, $bind_types, ...$bind_params);
    mysqli_stmt_execute($stmt);
    $owned_result = mysqli_stmt_get_result($stmt);
    while ($row = mysqli_fetch_assoc($owned_result)) {
        $owned_ids[] = (int)$row['homework_detailsid'];
    }
    mysqli_stmt_close($stmt);

    if (!empty($owned_ids)) {
        $homework_class = new Homework_details();
        $homework_list  = $homework_class->GetList([["homework_detailsId IN (" . implode(",", $owned_ids) . ")"]]);

        if (!empty($homework_list)) {
            $current_week  = hw_week_start_date();
            $previous_week = hw_week_start_date('-7 days');

            $weight_stmt = mysqli_prepare(
                $connection,
                "SELECT homework_detailsid, exercise_section, week_start_date, weight
                 FROM member_exercise_weight
                 WHERE member_id = ? AND homework_detailsid IN (" . implode(',', array_fill(0, count($owned_ids), '?')) . ")
                   AND week_start_date IN (?, ?)"
            );
            $weight_bind_types  = 'i' . str_repeat('i', count($owned_ids)) . 'ss';
            $weight_bind_params = array_merge([$member_id], $owned_ids, [$current_week, $previous_week]);
            mysqli_stmt_bind_param($weight_stmt, $weight_bind_types, ...$weight_bind_params);
            mysqli_stmt_execute($weight_stmt);
            $weight_result = mysqli_stmt_get_result($weight_stmt);
            while ($w = mysqli_fetch_assoc($weight_result)) {
                $key = $w['homework_detailsid'] . '|' . $w['exercise_section'];
                if (!isset($weight_by_row[$key])) {
                    $weight_by_row[$key] = ['current' => null, 'previous' => null];
                }
                if ($w['week_start_date'] === $current_week) {
                    $weight_by_row[$key]['current'] = $w['weight'];
                } elseif ($w['week_start_date'] === $previous_week) {
                    $weight_by_row[$key]['previous'] = $w['weight'];
                }
            }
            mysqli_stmt_close($weight_stmt);

            foreach ($homework_list as $hw_value) {
                $enabled_videolinks = $hw_value->enabled_videolinks;
                if ($homework_title === '' && !empty($hw_value->filename)) {
                    $homework_title = $hw_value->filename;
                }
                $hwid = (int)$hw_value->homework_detailsId;
                $corrective_details[] = [
                    'hwid'     => $hwid,
                    'section'  => 'corrective',
                    'exercise' => $hw_value->corrective_exercise,
                    'sets'     => $hw_value->corrective_sets,
                    'reps'     => $hw_value->corrective_reps,
                    'rest'     => $hw_value->corrective_rest,
                    'notes'    => $hw_value->corrective_notes,
                ];
                $strength_details[] = [
                    'hwid'     => $hwid,
                    'section'  => 'strength',
                    'exercise' => $hw_value->strength_exercise,
                    'sets'     => $hw_value->strength_sets,
                    'reps'     => $hw_value->strength_reps,
                    'rest'     => $hw_value->strength_rest,
                    'notes'    => $hw_value->strength_notes,
                ];
                $flexibility_details[] = [
                    'hwid'     => $hwid,
                    'section'  => 'flexibility',
                    'exercise' => $hw_value->flexibility_exercise,
                    'sets'     => $hw_value->flexibility_sets,
                    'reps'     => $hw_value->flexibility_reps,
                    'rest'     => $hw_value->flexibility_rest,
                    'notes'    => $hw_value->flexibility_notes,
                ];
            }
        }
    }
}

$page_title = $homework_title !== '' ? 'HOMEWORK ' . $homework_title : 'Homework';

function hw_section_notes(array $rows): string
{
    foreach ($rows as $row) {
        if (trim((string)$row['notes']) !== '') {
            return $row['notes'];
        }
    }
    return '';
}

function hw_visible_rows(array $rows): array
{
    return array_values(array_filter($rows, function ($row) {
        return trim((string)$row['exercise']) !== '';
    }));
}

function render_homework_section(string $title, array $rows, $enabled_videolinks, string $collapse_id, bool $is_open, array $weight_by_row = []): void
{
    $visible_rows = hw_visible_rows($rows);
    $notes        = hw_section_notes($rows);
    ?>
    <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">
                    <div class="ph-accordion-note">
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <g clip-path="url(#clip0_3249_19014)">
                                <path d="M8.93329 1.33331H3.99996C3.64634 1.33331 3.3072 1.47379 3.05715 1.72384C2.8071 1.97389 2.66663 2.31302 2.66663 2.66665V13.3333C2.66663 13.6869 2.8071 14.0261 3.05715 14.2761C3.3072 14.5262 3.64634 14.6666 3.99996 14.6666H12C12.3536 14.6666 12.6927 14.5262 12.9428 14.2761C13.1928 14.0261 13.3333 13.6869 13.3333 13.3333V8.39998" stroke="#4C78CE" stroke-linecap="round" stroke-linejoin="round" />
                                <path d="M1.33337 4H4.00004" stroke="#4C78CE" stroke-linecap="round" stroke-linejoin="round" />
                                <path d="M1.33337 6.66669H4.00004" stroke="#4C78CE" stroke-linecap="round" stroke-linejoin="round" />
                                <path d="M1.33337 9.33331H4.00004" stroke="#4C78CE" stroke-linecap="round" stroke-linejoin="round" />
                                <path d="M1.33337 12H4.00004" stroke="#4C78CE" stroke-linecap="round" stroke-linejoin="round" />
                                <path d="M14.2519 3.75068C14.5175 3.48511 14.6667 3.12492 14.6667 2.74935C14.6667 2.37378 14.5175 2.01359 14.2519 1.74802C13.9864 1.48245 13.6262 1.33325 13.2506 1.33325C12.875 1.33325 12.5148 1.48245 12.2493 1.74802L8.90928 5.08935C8.75078 5.24777 8.63476 5.44357 8.57194 5.65868L8.01394 7.57202C7.99721 7.62938 7.99621 7.69019 8.01104 7.74808C8.02587 7.80596 8.05599 7.8588 8.09824 7.90105C8.1405 7.94331 8.19333 7.97343 8.25122 7.98826C8.3091 8.00309 8.36991 8.00208 8.42728 7.98535L10.3406 7.42735C10.5557 7.36454 10.7515 7.24852 10.9099 7.09002L14.2519 3.75068Z" stroke="#4C78CE" stroke-linecap="round" stroke-linejoin="round" />
                            </g>
                            <defs>
                                <clipPath id="clip0_3249_19014">
                                    <rect width="16" height="16" fill="white" />
                                </clipPath>
                            </defs>
                        </svg>
                        <span class="ph-accordion-note-text"><?php echo $is_open ? 'Hide Notes' : 'Notes'; ?></span>
                    </div>
                    <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 if ($notes !== ''): ?>
                        <div class="ph-accordion-list hide-on-mobile"><?php echo $notes; ?></div>
                    <?php endif; ?>

                    <?php if (!empty($visible_rows)): ?>
                        <div class="ph-exercise-table-wrap hide-on-mobile">
                            <table class="ph-exercise-table">
                                <thead>
                                    <tr>
                                        <th class="ph-th-exercise">Exercise</th>
                                        <th class="ph-th-sets">Sets</th>
                                        <th class="ph-th-reps">Reps</th>
                                        <th class="ph-th-rest">Rest</th>
                                        <th class="ph-th-weight">Weight</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($visible_rows as $row):
                                        $ex = hw_resolve_exercise($row['exercise'], $enabled_videolinks);
                                        $w  = $weight_by_row[$row['hwid'] . '|' . $row['section']] ?? ['current' => null, 'previous' => null];
                                    ?>
                                        <tr>
                                            <td class="ph-td-exercise"><?php echo htmlspecialchars($ex['label']); ?></td>
                                            <td class="ph-td-sets"><span class="ph-col-value<?php echo $row['sets'] === '' ? ' is-empty' : ''; ?>"><?php echo htmlspecialchars($row['sets'] !== '' ? $row['sets'] : '-'); ?></span></td>
                                            <td class="ph-td-reps"><span class="ph-col-value<?php echo $row['reps'] === '' ? ' is-empty' : ''; ?>"><?php echo htmlspecialchars($row['reps'] !== '' ? $row['reps'] : '-'); ?></span></td>
                                            <td class="ph-td-rest"><span class="ph-col-value<?php echo $row['rest'] === '' ? ' is-empty' : ''; ?>"><?php echo htmlspecialchars($row['rest'] !== '' ? $row['rest'] : '-'); ?></span></td>
                                            <td class="ph-td-weight">
                                                <input type="text" inputmode="decimal" class="ph-weight-input" maxlength="50"
                                                    data-homework-id="<?php echo (int)$row['hwid']; ?>"
                                                    data-section="<?php echo htmlspecialchars($row['section']); ?>"
                                                    value="<?php echo htmlspecialchars($w['current'] ?? ''); ?>"
                                                    placeholder="<?php echo $w['previous'] !== null ? 'Last: ' . htmlspecialchars($w['previous']) : ''; ?>">
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <div class="ph-table-container hide-on-desktop">
                            <div class="ph-thead">
                                <span class="ph-thead-cell">Exercise</span>
                                <span class="ph-thead-cell hide-on-mob">Sets</span>
                                <span class="ph-thead-cell hide-on-mob">Reps</span>
                                <span class="ph-thead-cell hide-on-mob">Rest</span>
                                <span class="ph-thead-cell">Weight</span>
                            </div>
                            <?php foreach ($visible_rows as $row):
                                $ex = hw_resolve_exercise($row['exercise'], $enabled_videolinks);
                                $setsEmpty = $row['sets'] === '';
                                $repsEmpty = $row['reps'] === '';
                                $restEmpty = $row['rest'] === '';
                                $w  = $weight_by_row[$row['hwid'] . '|' . $row['section']] ?? ['current' => null, 'previous' => null];
                            ?>
                                <div class="ph-row">
                                    <div class="ph-ex-cell">
                                        <?php if ($ex['url'] !== ''): ?>
                                            <a class="ph-ex-link" href="<?php echo htmlspecialchars($ex['url']); ?>" target="_blank" rel="noopener"><?php echo htmlspecialchars($ex['label']); ?></a>
                                        <?php else: ?>
                                            <a href="#" class="ph-ex-link"><?php echo htmlspecialchars($ex['label']); ?></a>
                                        <?php endif; ?>
                                    </div>
                                    <span class="ph-val-cell<?php echo $setsEmpty ? ' is-empty' : ''; ?>"><?php echo htmlspecialchars($setsEmpty ? '-' : $row['sets']); ?></span>
                                    <span class="ph-val-cell<?php echo $repsEmpty ? ' is-empty' : ''; ?>"><?php echo htmlspecialchars($repsEmpty ? '-' : $row['reps']); ?></span>
                                    <span class="ph-val-cell<?php echo $restEmpty ? ' is-empty' : ''; ?>"><?php echo htmlspecialchars($restEmpty ? '-' : $row['rest']); ?></span>
                                    <div class="ph-mob-vals">
                                        <div class="ph-mv-item"><span class="ph-mv-lbl">SETS</span><span class="ph-mv-val<?php echo $setsEmpty ? ' is-empty' : ''; ?>"><?php echo htmlspecialchars($setsEmpty ? '-' : $row['sets']); ?></span></div>
                                        <div class="ph-mv-item"><span class="ph-mv-lbl">REPS</span><span class="ph-mv-val<?php echo $repsEmpty ? ' is-empty' : ''; ?>"><?php echo htmlspecialchars($repsEmpty ? '-' : $row['reps']); ?></span></div>
                                        <div class="ph-mv-item"><span class="ph-mv-lbl">REST</span><span class="ph-mv-val<?php echo $restEmpty ? ' is-empty' : ''; ?>"><?php echo htmlspecialchars($restEmpty ? '-' : $row['rest']); ?></span></div>
                                    </div>
                                    <div class="ph-mv-item ph-mv-weight">
                                        <span class="ph-mv-lbl">WEIGHT</span>
                                        <input type="text" inputmode="decimal" class="ph-weight-input" maxlength="50"
                                            data-homework-id="<?php echo (int)$row['hwid']; ?>"
                                            data-section="<?php echo htmlspecialchars($row['section']); ?>"
                                            value="<?php echo htmlspecialchars($w['current'] ?? ''); ?>"
                                            placeholder="<?php echo $w['previous'] !== null ? 'Last: ' . htmlspecialchars($w['previous']) : ''; ?>">
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <p class="text-muted mb-0">No <?php echo htmlspecialchars(strtolower($title)); ?> exercises assigned.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <?php
}

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 homework program</p>
                </div>
            </div>
        </header>

        <div class="body-content">
            <div class="">
                <?php if ($homework_id <= 0 || (empty($corrective_details) && empty($strength_details) && empty($flexibility_details))): ?>
                    <div class="empty-state">
                        <p class="empty-state-text">No homework details found.</p>
                    </div>
                <?php else: ?>
                    <div class="accordion ph-accordion" id="portalHomeworkAccordion">
                        <?php
                        render_homework_section('CORRECTIVE', $corrective_details, $enabled_videolinks, 'collapseCorrective', false, $weight_by_row);
                        render_homework_section('STRENGTH', $strength_details, $enabled_videolinks, 'collapseStrength', true, $weight_by_row);
                        render_homework_section('FLEXIBILITY', $flexibility_details, $enabled_videolinks, 'collapseFlexibility', false, $weight_by_row);
                        ?>
                    </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>
<script>
document.querySelectorAll('.ph-accordion .accordion-collapse').forEach(function (collapseEl) {
    var button = document.querySelector('[data-bs-target="#' + collapseEl.id + '"]');
    var label = button ? button.querySelector('.ph-accordion-note-text') : null;
    if (!label) return;
    collapseEl.addEventListener('shown.bs.collapse', function () { label.textContent = 'Hide Notes'; });
    collapseEl.addEventListener('hidden.bs.collapse', function () { label.textContent = 'Notes'; });
});

// Save a weight entry when the member leaves the field (blur) or presses
// Enter. Saves are scoped to the current week server-side, so this never
// touches a previous week's saved value.
document.querySelectorAll('.ph-weight-input').forEach(function (input) {
    input.dataset.savedValue = input.value;
    function saveWeight() {
        var value = input.value.trim();
        input.title = '';
        if (value === '' || value === input.dataset.savedValue) return;
        fetch('homework_weight_save.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'homework_details_id=' + encodeURIComponent(input.dataset.homeworkId) +
                '&exercise_section=' + encodeURIComponent(input.dataset.section) +
                '&weight=' + encodeURIComponent(value)
        })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (data && data.success) {
                    input.dataset.savedValue = value;
                } else {
                    input.title = 'Could not save this weight. Please try again.';
                }
            })
            .catch(function () { input.title = 'Could not save this weight. Please try again.'; });
    }
    input.addEventListener('blur', saveWeight);
    input.addEventListener('keydown', function (e) {
        if (e.key === 'Enter') { e.preventDefault(); input.blur(); }
    });
});
</script>

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