<?php

$tokenRec = require_valid_token_web();

$callerRole     = $tokenRec['role'];
$callerEntityID = $tokenRec['entityID'] ?? '';

switch ($method) {

case 'GET':
    try {
        [$pdo, $tmpDb, $lockFp] = qdb_open_read_or_fail();

        if ($callerRole === 'admin') {
            $coaches = $pdo->query(
                "SELECT c.coachID, c.username, c.supervisorID, sv.username AS supervisorUsername
                 FROM coach c
                 LEFT JOIN supervisor sv ON sv.supervisorID = c.supervisorID
                 ORDER BY sv.username, c.username"
            )->fetchAll(PDO::FETCH_ASSOC);
        } else {
            $stmt = $pdo->prepare(
                "SELECT c.coachID, c.username, c.supervisorID, sv.username AS supervisorUsername
                 FROM coach c
                 LEFT JOIN supervisor sv ON sv.supervisorID = c.supervisorID
                 WHERE c.supervisorID = :sid ORDER BY c.username"
            );
            $stmt->execute([':sid' => $callerEntityID]);
            $coaches = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }

        [$clause, $params] = rbac_client_filter($tokenRec, 'cl');
        $clientStmt = $pdo->prepare(
            "SELECT cl.clientCode, cl.coachID, co.username AS coachUsername
             FROM client cl
             LEFT JOIN coach co ON co.coachID = cl.coachID
             WHERE $clause
             ORDER BY cl.coachID, cl.clientCode"
        );
        foreach ($params as $k => $v) $clientStmt->bindValue($k, $v);
        $clientStmt->execute();
        $clients = $clientStmt->fetchAll(PDO::FETCH_ASSOC);

        qdb_discard($tmpDb, $lockFp);
        json_success(['coaches' => $coaches, 'clients' => $clients]);
    } catch (Throwable $e) {
        qdb_handler_fail($e, 'assignments', null, $tmpDb ?? null, $lockFp ?? null);
    }
    break;

case 'POST':
    $body        = read_json_body();
    $clientCodes = $body['clientCodes'] ?? [];
    $coachID     = trim($body['coachID'] ?? '');

    if (empty($clientCodes) || $coachID === '') {
        json_error('MISSING_FIELDS', 'clientCodes and coachID are required', 400);
    }
    if (!is_array($clientCodes)) $clientCodes = [$clientCodes];

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

        if ($callerRole === 'supervisor') {
            $chk = $pdo->prepare("SELECT coachID FROM coach WHERE coachID = :cid AND supervisorID = :sid");
            $chk->execute([':cid' => $coachID, ':sid' => $callerEntityID]);
        } else {
            $chk = $pdo->prepare("SELECT coachID FROM coach WHERE coachID = :cid");
            $chk->execute([':cid' => $coachID]);
        }
        if (!$chk->fetch()) {
            qdb_discard($tmpDb, $lockFp);
            json_error('NOT_FOUND', 'Counselor not found or not authorized', 404);
        }

        [$rbacClause, $rbacParams] = rbac_client_filter($tokenRec);
        $pdo->beginTransaction();
        $updStmt = $pdo->prepare(
            "UPDATE client SET coachID = :cid WHERE clientCode = :cc AND ($rbacClause)"
        );
        $count = 0;
        foreach ($clientCodes as $cc) {
            $cc = trim($cc);
            if ($cc === '') continue;
            $updStmt->execute(array_merge([':cid' => $coachID, ':cc' => $cc], $rbacParams));
            $count += $updStmt->rowCount();
        }
        $pdo->commit();
        qdb_save($tmpDb, $lockFp);

        json_success(['assigned' => $count]);
    } catch (Throwable $e) {
        qdb_handler_fail($e, 'assignments', $pdo ?? null, $tmpDb ?? null, $lockFp ?? null);
    }
    break;

default:
    json_error('METHOD_NOT_ALLOWED', 'Method not allowed', 405);
}
