<?php

$tokenRec = require_valid_token();

if ($method !== 'POST') {
    json_error('METHOD_NOT_ALLOWED', 'Method not allowed', 405);
}

$body = read_json_body();
require_fields($body, ['clientCode', 'scheduledDate', 'programCycleNumber', 'programSessionNumber']);

$clientCode = trim((string)$body['clientCode']);
$scheduledDate = trim((string)$body['scheduledDate']);
$programCycleNumber = max(1, (int)$body['programCycleNumber']);
$programSessionNumber = max(1, (int)$body['programSessionNumber']);
$programSessionID = isset($body['programSessionID'])
    ? trim((string)$body['programSessionID'])
    : null;
if ($programSessionID === '') {
    $programSessionID = null;
}

try {
    $opened = qdb_open_write_or_fail();
    [$pdo, $tmpDb, $lockFp] = $opened;

    require_role(['coach'], $tokenRec);
    [$rbacClause, $rbacParams] = rbac_client_filter($tokenRec, 'cl');
    $clStmt = $pdo->prepare(
        "SELECT cl.clientCode FROM client cl WHERE cl.clientCode = :cc AND ($rbacClause)"
    );
    $clStmt->execute(array_merge([':cc' => $clientCode], $rbacParams));
    if (!$clStmt->fetch()) {
        qdb_discard($tmpDb, $lockFp);
        json_error('NOT_FOUND', 'Client not found or not authorized', 404);
    }

    require_once __DIR__ . '/../lib/session_schedule.php';
    qdb_upsert_client_session_schedule(
        $pdo,
        $clientCode,
        $scheduledDate,
        $programCycleNumber,
        $programSessionNumber,
        $programSessionID
    );

    qdb_save($tmpDb, $lockFp);

    json_success([
        'scheduled' => true,
        'schedule'  => qdb_get_client_session_schedule($pdo, $clientCode),
    ]);
} catch (Throwable $e) {
    qdb_handler_fail($e, 'Save session schedule', null, $tmpDb ?? null, $lockFp ?? null);
}
