<?php
/**
 * homework_functions.php
 *
 * Shared helpers for the member-portal "Remote Program" (homework) views —
 * used by homework-mom.php (render) and homework_weight_save.php (AJAX
 * weight save), so exercise-label resolution stays in one place.
 */

/**
 * Converts a YouTube URL (youtu.be/ID, youtube.com/watch?v=ID, or an
 * already-embed URL) into an embed URL with autoplay + continuous loop.
 * Non-YouTube URLs are returned unchanged.
 */
function hw_youtube_embed_url(string $url): string
{
    $id = '';
    if (preg_match('~youtu\.be/([A-Za-z0-9_-]{11})~', $url, $m)) {
        $id = $m[1];
    } elseif (preg_match('~[?&]v=([A-Za-z0-9_-]{11})~', $url, $m)) {
        $id = $m[1];
    } elseif (preg_match('~youtube\.com/embed/([A-Za-z0-9_-]{11})~', $url, $m)) {
        $id = $m[1];
    }

    if ($id === '') {
        return $url;
    }

    return 'https://www.youtube.com/embed/' . $id . '?autoplay=1&loop=1&playlist=' . $id;
}

/**
 * Resolves an exercise field to a display label (+ optional video url).
 * When video links are enabled the stored value is an exercise id that
 * must be looked up; otherwise it's already the plain exercise name.
 */
function hw_resolve_exercise($value, $enabled_videolinks): array
{
    $value = trim((string)$value);
    if ($value === '') {
        return ['label' => '', 'url' => ''];
    }
    if ((string)$enabled_videolinks === '1' && ctype_digit($value)) {
        $exercise = get_exercise((int)$value);
        if ($exercise && !empty($exercise->name)) {
            $url = (string)$exercise->videourl;
            return ['label' => strtoupper($exercise->name), 'url' => $url !== '' ? hw_youtube_embed_url($url) : ''];
        }
        return ['label' => '', 'url' => ''];
    }
    return ['label' => strtoupper($value), 'url' => ''];
}

/**
 * Monday of the ISO week containing $date (defaults to today), as Y-m-d.
 * Used to key weight-tracking entries by week without the
 * strtotime('monday this week') off-by-one-on-Mondays gotcha.
 */
function hw_week_start_date(?string $date = null): string
{
    $dt = $date !== null ? new DateTime($date) : new DateTime();
    $dow = (int)$dt->format('N'); // 1 (Mon) .. 7 (Sun)
    if ($dow > 1) {
        $dt->modify('-' . ($dow - 1) . ' days');
    }
    return $dt->format('Y-m-d');
}
