<?php
include_once __DIR__ . "/../db.php";

/**
 * Show today's workout from the user's latest plan as an interactive logger.
 */
function showWorkoutLogger($chat_id): void {
    global $pdo, $sessions, $sessionFile;

    $stmt = $pdo->prepare("SELECT plan FROM workout_plans WHERE chat_id = ? ORDER BY id DESC LIMIT 1");
    $stmt->execute([$chat_id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        sendMessage($chat_id,
            "💪 No workout plan found. Generate one first!",
            ["inline_keyboard" => [[
                ["text" => "💪 Get Workout Plan", "callback_data" => "start_workout"],
                ["text" => "🏠 Main Menu",        "callback_data" => "main_menu"],
            ]]]
        );
        return;
    }

    $plan     = json_decode($row['plan'], true);
    $schedule = $plan['schedule'] ?? [];
    if (empty($schedule)) {
        sendMessage($chat_id, "⚠️ Workout plan has no schedule. Please generate a new one.");
        return;
    }

    // Match today's day name to a plan day, fallback to day-of-week index
    $dayName  = date('l'); // e.g. "Monday"
    $dayIndex = 0;
    foreach ($schedule as $i => $day) {
        if (stripos($day['day'] ?? '', $dayName) !== false) {
            $dayIndex = $i;
            break;
        }
        $dayIndex = (date('N') - 1) % count($schedule); // ISO weekday 1=Mon, map to 0-based
    }

    $todayPlan = $schedule[$dayIndex];

    // Check if it's a rest day
    if (empty($todayPlan['exercises'])) {
        sendMessage($chat_id,
            "😴 <b>Rest Day!</b>\n\n" .
            "Today is <b>{$todayPlan['day']}</b> — your scheduled rest day.\n" .
            "Recovery is part of the plan. See you tomorrow! 💪",
            ["inline_keyboard" => [[["text" => "🏠 Main Menu", "callback_data" => "main_menu"]]]]
        );
        return;
    }

    // Init session state
    $doneState = array_fill(0, count($todayPlan['exercises']), false);
    $sessions[$chat_id]['wlog_day_index'] = $dayIndex;
    $sessions[$chat_id]['wlog_plan']      = $plan;
    $sessions[$chat_id]['wlog_done']      = $doneState;
    saveSessions($sessions, $sessionFile);

    buildAndSendWorkoutLogMessage($chat_id, $todayPlan, $doneState);
}

/**
 * Build the workout log keyboard and send (or edit) the message.
 */
function buildAndSendWorkoutLogMessage($chat_id, $dayPlan, $doneState, $msgId = null): void {
    global $config;

    $focus    = $dayPlan['focus'] ?? '';
    $exercises = $dayPlan['exercises'] ?? [];

    $msg  = "📝 <b>Log Today's Workout</b>\n";
    $msg .= "📅 <b>{$dayPlan['day']}</b>" . ($focus ? " — {$focus}" : '') . "\n\n";
    $msg .= "Tap each exercise to mark it done:\n";

    $buttons = [];
    foreach ($exercises as $i => $ex) {
        $done      = $doneState[$i] ?? false;
        $icon      = $done ? '✅' : '⬜';
        $label     = "{$icon} {$ex['name']} ({$ex['sets']}×{$ex['reps']})";
        $buttons[] = [["text" => $label, "callback_data" => "wlog_toggle_{$i}"]];
    }

    $completed = count(array_filter($doneState));
    $total     = count($exercises);

    $buttons[] = [
        ["text" => "✅ Mark All Done",                       "callback_data" => "wlog_all"],
        ["text" => "💾 Save ({$completed}/{$total})",        "callback_data" => "wlog_save"],
    ];
    $buttons[] = [["text" => "❌ Cancel",                    "callback_data" => "main_menu"]];

    $keyboard = ["inline_keyboard" => $buttons];

    if ($msgId) {
        // Edit existing message
        $data = [
            'chat_id'      => $chat_id,
            'message_id'   => $msgId,
            'text'         => $msg,
            'parse_mode'   => 'HTML',
            'reply_markup' => json_encode($keyboard),
        ];
        $ch = curl_init("https://api.telegram.org/bot{$config['telegram_token']}/editMessageText");
        curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_POSTFIELDS => $data]);
        curl_exec($ch);
    } else {
        sendMessage($chat_id, $msg, $keyboard);
    }
}

/**
 * Toggle a single exercise's done state and edit the message.
 */
function handleWorkoutLogToggle($chat_id, $index, $msgId): void {
    global $sessions, $sessionFile;

    if (!isset($sessions[$chat_id]['wlog_plan'])) {
        return;
    }

    $dayIndex  = $sessions[$chat_id]['wlog_day_index'] ?? 0;
    $dayPlan   = $sessions[$chat_id]['wlog_plan']['schedule'][$dayIndex] ?? null;
    if (!$dayPlan) return;

    $doneState = $sessions[$chat_id]['wlog_done'] ?? [];
    $doneState[$index] = !($doneState[$index] ?? false);
    $sessions[$chat_id]['wlog_done'] = $doneState;
    saveSessions($sessions, $sessionFile);

    buildAndSendWorkoutLogMessage($chat_id, $dayPlan, $doneState, $msgId);
}

/**
 * Mark all exercises done and refresh.
 */
function handleWorkoutLogMarkAll($chat_id, $msgId): void {
    global $sessions, $sessionFile;

    if (!isset($sessions[$chat_id]['wlog_plan'])) return;

    $dayIndex  = $sessions[$chat_id]['wlog_day_index'] ?? 0;
    $dayPlan   = $sessions[$chat_id]['wlog_plan']['schedule'][$dayIndex] ?? null;
    if (!$dayPlan) return;

    $count     = count($dayPlan['exercises'] ?? []);
    $doneState = array_fill(0, $count, true);
    $sessions[$chat_id]['wlog_done'] = $doneState;
    saveSessions($sessions, $sessionFile);

    buildAndSendWorkoutLogMessage($chat_id, $dayPlan, $doneState, $msgId);
}

/**
 * Save the completed exercises to DB and show a summary.
 */
function handleWorkoutLogSave($chat_id, $msgId): void {
    global $pdo, $sessions, $sessionFile, $config;

    if (!isset($sessions[$chat_id]['wlog_plan'])) {
        sendMessage($chat_id, "⚠️ No active workout log session. Tap 'Log Workout' to start.");
        return;
    }

    $dayIndex  = $sessions[$chat_id]['wlog_day_index'] ?? 0;
    $dayPlan   = $sessions[$chat_id]['wlog_plan']['schedule'][$dayIndex] ?? null;
    $doneState = $sessions[$chat_id]['wlog_done'] ?? [];

    $exercises = $dayPlan['exercises'] ?? [];
    $dayLabel  = $dayPlan['day'] ?? date('l');
    $saved     = 0;

    foreach ($exercises as $i => $ex) {
        if (!empty($doneState[$i])) {
            $pdo->prepare("INSERT INTO workout_log (chat_id, day_label, exercise_name, sets_done, reps_done) VALUES (?, ?, ?, ?, ?)")
                ->execute([$chat_id, $dayLabel, $ex['name'], $ex['sets'] ?? null, $ex['reps'] ?? null]);
            $saved++;
        }
    }

    unset($sessions[$chat_id]['wlog_plan'], $sessions[$chat_id]['wlog_done'], $sessions[$chat_id]['wlog_day_index']);
    saveSessions($sessions, $sessionFile);

    $total = count($exercises);
    $pct   = $total > 0 ? (int)round($saved / $total * 100) : 0;

    $msg  = "💪 <b>Workout Logged!</b>\n\n";
    $msg .= "Day: <b>{$dayLabel}</b>\n";
    $msg .= "Completed: <b>{$saved}/{$total} exercises</b> ({$pct}%)\n\n";
    if ($pct === 100)      $msg .= "🏆 Perfect session! Full workout complete!\n";
    elseif ($pct >= 75)    $msg .= "🔥 Great effort! Almost there!\n";
    elseif ($pct >= 50)    $msg .= "💪 Solid session! Keep it up!\n";
    else                   $msg .= "✅ Every rep counts — well done!\n";

    // Edit the old message to show result
    $data = [
        'chat_id'      => $chat_id,
        'message_id'   => $msgId,
        'text'         => $msg,
        'parse_mode'   => 'HTML',
        'reply_markup' => json_encode(["inline_keyboard" => [
            [["text" => "📈 My Status",  "callback_data" => "view_status"],
             ["text" => "🏠 Main Menu",  "callback_data" => "main_menu"]],
        ]]),
    ];
    $ch = curl_init("https://api.telegram.org/bot{$config['telegram_token']}/editMessageText");
    curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_POSTFIELDS => $data]);
    curl_exec($ch);
}

/**
 * Get this week's workout log count for a user.
 */
function getWeeklyWorkoutCount($chat_id): int {
    global $pdo;
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM workout_log WHERE chat_id = ? AND logged_at >= NOW() - INTERVAL 7 DAY");
    $stmt->execute([$chat_id]);
    return (int)$stmt->fetchColumn();
}
