<?php
require_once '../src/AccessToken.php';
header('Content-Type: application/json');

// Reusable: get token and endpoint
function getBitrixAuth($bitrix24user) {
    $tokenData = AccessToken::getAccessTokenByUserId($bitrix24user);
    return [
        'accessToken' => $tokenData['access_token'],
        'clientEndPoint' => $tokenData['client_endpoint'],
        'responsibleId' => $tokenData['repo_id']
    ];
}

// POST = Add Comment
if (isset($_POST['taskId']) && isset($_POST['commentValue']) && isset($_POST['bitrix24Id'])) {
    $taskId = $_POST['taskId'];
    $commentValue = $_POST['commentValue'];
    $bitrix24user = $_POST['bitrix24Id'];

    $auth = getBitrixAuth($bitrix24user);
    $webhookUrl = $auth['clientEndPoint'] . "task.commentitem.add.json?auth=" . $auth['accessToken'];

    $result = addComment($taskId, $commentValue, $webhookUrl);
    echo json_encode($result);
    exit;
}

// GET = Fetch Comments
if (isset($_GET['taskId']) && isset($_GET['bitrix24Id'])) {
    $taskId = $_GET['taskId'];
    $bitrix24user = $_GET['bitrix24Id'];

    $auth = getBitrixAuth($bitrix24user);
    $webhookUrl = $auth['clientEndPoint'] . "task.commentitem.getlist.json?auth=" . $auth['accessToken'];

    $comments = getComments($taskId, $webhookUrl);
    echo json_encode($comments);
    exit;
}

// Function to fetch comments
function getComments($taskId, $webhookUrl) {
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $webhookUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode(['taskId' => $taskId]),
        CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    return json_decode($response, true);
}

// Function to add a comment
function addComment($taskId, $commentText, $webhookUrl) {
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $webhookUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode([
            'taskId' => $taskId,
            'fields' => ['POST_MESSAGE' => $commentText]
        ]),
        CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    return json_decode($response, true);
}
?>
