<?php
/**
 * homework_weight_save.php
 *
 * AJAX endpoint for Feature 7 (Weight Tracking). Saves one exercise weight
 * entry, scoped to the current week (Monday start). Never touches a
 * previous week's row — the UNIQUE key on
 * (member_id, homework_detailsid, exercise_section, week_start_date) means
 * a save this week can only ever insert a new row or update *this week's*
 * row.
 */

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

header('Content-Type: application/json; charset=utf-8');

$member_id           = (int)($_SESSION['memberid'] ?? 0);
$homework_details_id = filter_input(INPUT_POST, 'homework_details_id', FILTER_VALIDATE_INT) ?: 0;
$exercise_section    = $_POST['exercise_section'] ?? '';
$weight              = trim((string)($_POST['weight'] ?? ''));

$allowed_sections = ['corrective', 'strength', 'flexibility'];

if ($member_id <= 0 || $homework_details_id <= 0 || !in_array($exercise_section, $allowed_sections, true) || $weight === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Invalid input']);
    exit;
}

if (strlen($weight) > 50) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Weight value is too long']);
    exit;
}

// IDOR guard: the homework_details row must belong to the logged-in member.
$stmt = mysqli_prepare(
    $connection,
    "SELECT 1 FROM homework_detailsmembermap WHERE memberid = ? AND homework_detailsid = ? LIMIT 1"
);
mysqli_stmt_bind_param($stmt, 'ii', $member_id, $homework_details_id);
mysqli_stmt_execute($stmt);
$owns_row = (bool)mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));
mysqli_stmt_close($stmt);

if (!$owns_row) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Access denied']);
    exit;
}

// Snapshot the program name + resolved exercise label at save time, so a
// member's history stays accurate even if the coach edits the program later.
$homework_class = new Homework_details();
$homework_class->Get($homework_details_id);

$program_name = (string)$homework_class->filename;
$exercise_raw = match ($exercise_section) {
    'corrective'   => $homework_class->corrective_exercise,
    'strength'     => $homework_class->strength_exercise,
    'flexibility'  => $homework_class->flexibility_exercise,
};
$resolved       = hw_resolve_exercise($exercise_raw, $homework_class->enabled_videolinks);
$exercise_label = $resolved['label'] !== '' ? $resolved['label'] : strtoupper((string)$exercise_raw);

$week_start_date = hw_week_start_date();
$now             = date('Y-m-d H:i:s');

$stmt = mysqli_prepare(
    $connection,
    "INSERT INTO member_exercise_weight
        (member_id, homework_detailsid, exercise_section, exercise_label, program_name, week_start_date, weight, created_on, updated_on)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
     ON DUPLICATE KEY UPDATE
        weight = VALUES(weight),
        exercise_label = VALUES(exercise_label),
        program_name = VALUES(program_name),
        updated_on = VALUES(updated_on)"
);
mysqli_stmt_bind_param(
    $stmt,
    'iisssssss',
    $member_id,
    $homework_details_id,
    $exercise_section,
    $exercise_label,
    $program_name,
    $week_start_date,
    $weight,
    $now,
    $now
);

if (mysqli_stmt_execute($stmt)) {
    echo json_encode(['success' => true]);
} else {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Unable to save']);
}
mysqli_stmt_close($stmt);
