<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once '../src/AccessToken.php';
require_once '../src/Database.php';

class BitrixTaskCommentHandler
{
    private static $conn;

    public static function init()
    {
        if (!self::$conn) {
            self::$conn = Database::getInstance();
        }
    }

    // 1. Get Access Token from bitrix24_token table by domain
    public static function getAccessTokenByDomain($domain)
    {
        $stmt = self::$conn->prepare("SELECT acsess_token, client_endpoint, bitrix24_user_id FROM bitrix24_token WHERE domain = ? LIMIT 1");
        $stmt->bind_param("s", $domain);
        $stmt->execute();
        $stmt->bind_result($accessToken, $clientEndpoint, $bitrix24UserId);

        if ($stmt->fetch()) {
            return [
                'acsess_token' => $accessToken,
                'client_endpoint' => $clientEndpoint,
                'bitrix24_user_id' => $bitrix24UserId
            ];
        }

        return null;
    }

    // 2. Get external ticket data from external_ticket table
    public static function getExternalTickets($taskId, $bitrix24UserId)
    {
        $stmt = self::$conn->prepare("SELECT OWNER_ID,OWNER_TYPE_ID,email,responsible_id,task_status,id FROM external_ticket WHERE task_id = ? AND bitrix_user_id = ? LIMIT 1");
        $stmt->bind_param("ii", $taskId, $bitrix24UserId);
        $stmt->execute();
        $result = $stmt->get_result();

        return $result->fetch_all(MYSQLI_ASSOC);
    }

    // 3. Get comments from a Bitrix task
    public static function getTaskComments($taskId,$commentId, $accessToken, $clientEndpoint)
    {
        $url = $clientEndpoint . "task.commentitem.get.json?auth=$accessToken&0=$taskId&1=$commentId";
        return self::curlGet($url);
    }

    // 4. Add comment to CRM activity
    public static function addCommentToActivity($activityData, $accessToken, $clientEndpoint)
    {
        $url = $clientEndpoint . "crm.activity.add.json?auth=$accessToken";
        return self::curlPost($url, ["fields" => $activityData]);
    }

    // 5. Get task status from Bitrix
    public static function getTaskById($taskId, $accessToken, $clientEndpoint)
    {
        $url = $clientEndpoint . "tasks.task.get.json?auth=$accessToken&taskId=$taskId";
        return self::curlGet($url);
    }

    // 6. Utility function: curl GET
    private static function curlGet($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($ch);
        curl_close($ch);
        return json_decode($response, true);
    }

    // 7. Utility function: curl POST
    private static function curlPost($url, $postData)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json'
        ]);
        $response = curl_exec($ch);
        curl_close($ch);
        return json_decode($response, true);
    }

    // 8. Optional check for task processing
    private static function isTaskInDB($taskId)
    {
        return true; // placeholder
    }

    // 9. Main handler
    public static function handle($domain, $taskId, $commentId)
{
    self::init();

    $tokenData = self::getAccessTokenByDomain($domain);
    if (!$tokenData) {
        return ['error' => 'Access token not found for domain'];
    }

    $accessToken = $tokenData['acsess_token'];
    $clientEndpoint = $tokenData['client_endpoint'];
    $bitrix24UserId = $tokenData['bitrix24_user_id'];

    $tickets = self::getExternalTickets($taskId, $bitrix24UserId);

    if (!$tickets) {
        return ['error' => 'No tickets found for task and user'];
    }

    $entityId = $tickets[0]['OWNER_ID'];
    $responsible_id = $tickets[0]['responsible_id'];
    $email = $tickets[0]['email'];
    $OWNER_TYPE_ID = $tickets[0]['OWNER_TYPE_ID'];
    $task_status = $tickets[0]['task_status'];
    $rowId = $tickets[0]['id'];

    $responses = [];

    $commentData = self::getTaskComments($taskId, $commentId, $accessToken, $clientEndpoint);
    if ($commentData['result']) {
        $commentMsg = $commentData['result']['POST_MESSAGE'];
        $activityData = [
            "OWNER_TYPE_ID" => $OWNER_TYPE_ID,
            "OWNER_ID" => $entityId,
            "TYPE_ID" => 4,
            "COMMUNICATIONS" => [[
                "VALUE" => $email,
                "ENTITY_ID" => $entityId,
                "ENTITY_TYPE_ID" => $OWNER_TYPE_ID
            ]],
            "SUBJECT" => "Re: Send Mail to This Task Owner  $taskId",
            "COMPLETED" => "Y",
            "RESPONSIBLE_ID" => 730,
            "DESCRIPTION" => "$commentMsg",
            "DESCRIPTION_TYPE" => 3,
            "DIRECTION" => 2,
            "PRIORITY" => 1
        ];
        $response = self::addCommentToActivity($activityData, $accessToken, $clientEndpoint);
        $responses[] = $response;
    }

    $taskDetails = self::getTaskById($taskId, $accessToken, $clientEndpoint);
    $status = (int)($taskDetails['result']['task']['status'] ?? 0);

    if ($status != $task_status) {
        $statusMessages = [
            1 => "Your task is new.",
            2 => "Task is pending approval.",
            3 => "Task is in progress.",
            4 => "Task is waiting for control.",
            5 => "Task is completed.",
            6 => "Task is deferred.",
            7 => "Task is declined."
        ];

        $descriptionMessage = $statusMessages[$status] ?? "Task status is unknown.";

        $activityData = [
            "OWNER_TYPE_ID" => $OWNER_TYPE_ID,
            "OWNER_ID" => $entityId,
            "TYPE_ID" => 4,
            "COMMUNICATIONS" => [[
                "VALUE" => $email,
                "ENTITY_ID" => $entityId,
                "ENTITY_TYPE_ID" => $OWNER_TYPE_ID
            ]],
            "SUBJECT" => "Status Updated for Task ID $taskId",
            "COMPLETED" => "Y",
            "RESPONSIBLE_ID" => 730,
            "DESCRIPTION" => "<h4>$descriptionMessage</h4>",
            "DESCRIPTION_TYPE" => '3',
            "DIRECTION" => 2,
            "PRIORITY" => 1
        ];

        $response = self::addCommentToActivity($activityData, $accessToken, $clientEndpoint);
        $responses[] = $response;

        if (isset($response['result'])) {
            $stmt = self::$conn->prepare("UPDATE external_ticket SET task_status = ? WHERE id = ?");
            $stmt->execute([$status, $rowId]);
        }
    }

    return $responses;
}
}
// Example usage:
 echo "<pre>";
$result = BitrixTaskCommentHandler::handle("notademo.bitrix24.com", 8746,19840);
print_r($result);
