<?php
require_once '../src/Database.php';
require_once '../src/AccessToken.php';
$conn = Database::getInstance();

function call_api($endpoint, $params = [], $accessToken, $clientEndPoint) {
    $url = $clientEndPoint . $endpoint;
    
    // Add access token to parameters
    $params['auth'] = $accessToken;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 30 second timeout
    $response = curl_exec($ch);

    // Check if cURL returned an error
    if (curl_errno($ch)) {
        curl_close($ch);
        return ['error' => curl_error($ch)];
    }

    curl_close($ch);
    return json_decode($response, true);
}

function create_bitrix_task($bitrix_data, $access_token, $clientEndPoint) {
    $bitrix_api_url = $clientEndPoint . "tasks.task.add.json?auth=" . $access_token;
     //return $bitrix_api_url;
   $retry = 0;
    $max_retries = 3;
    $task_id = null;

    // Retry logic for task creation in Bitrix24
    while ($retry < $max_retries) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $bitrix_api_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($bitrix_data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            $retry++;
            curl_close($ch);
            sleep(1); // delay before retrying
            continue;
        }

        curl_close($ch);
        $bitrix_response = json_decode($response, true);

        // Check if the task was created successfully
        if (isset($bitrix_response["result"]["task"]["id"])) {
            $task_id = $bitrix_response["result"]["task"]["id"];
            break; // Task created successfully, exit the loop
        } else {
            $retry++;
            sleep(1); // delay before retrying
        }
    }

    return $task_id;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Extract POST data
    $ticket_id = strtoupper(substr(md5(time()), 0, 15));
    $ticketUser = intval($_POST['ticketUserId']);
    $issue_type = htmlspecialchars(trim($_POST['issueType']));
    $priority = intval($_POST['priority']);
    $description = htmlspecialchars(trim($_POST['description']));
    $status = 1;
    $project_id = htmlspecialchars(trim($_POST['project_id']));
    $bitrix_user_id = htmlspecialchars(trim($_POST['bitrix24_user']));
    $folderIdPos = htmlspecialchars(trim($_POST['folder_id']));
    $fileId = null;

    // Get access token and client endpoint
    $tokenData = AccessToken::getAccessTokenByUserId($bitrix_user_id);
    $accessToken = $tokenData['access_token'];
    $clientEndPoint = $tokenData['client_endpoint'];
    $responsibleId = $tokenData['repo_id'];

    // Upload file if exists
    if (isset($_FILES['attachment']) && is_uploaded_file($_FILES['attachment']['tmp_name'])) {
        $fileTmpPath = $_FILES['attachment']['tmp_name'];
        $fileName = $_FILES['attachment']['name'];
        $fileType = $_FILES['attachment']['type'];
        
        // Prepare file upload parameters
        $parm = [
            'id' => $folderIdPos,
            'data[NAME]' => $fileName,
            'generateUniqueName' => true
        ];

        // Call API to get the upload URL
        $uploadUrlData = call_api('disk.folder.uploadfile.json', $parm, $accessToken, $clientEndPoint);
        if (!empty($uploadUrlData['result']['uploadUrl'])) {
            $uploadUrl = $uploadUrlData['result']['uploadUrl'];
            $fieldName = $uploadUrlData['result']['field'];

            // Upload the file
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $uploadUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, [
                $fieldName => curl_file_create($fileTmpPath, $fileType, $fileName)
            ]);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            $uploadResult = curl_exec($ch);
            curl_close($ch);

            $resultData = json_decode($uploadResult, true);
            if (!empty($resultData['result']['ID'])) {
                $fileId = $resultData['result']['ID'];
            }
        }
    }

    // Insert ticket into database
    $stmt = $conn->prepare("INSERT INTO tickets (ticket_id, issue_type, priority, description, status, project_id, bitrix_user_id, ticket_user_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssisiiii", $ticket_id, $issue_type, $priority, $description, $status, $project_id, $bitrix_user_id, $ticketUser);

    if ($stmt->execute()) {
        // Prepare Bitrix task data
        $bitrix_data = [
            "fields" => [
                "TITLE" => "New Ticket: " . $ticket_id,
                "DESCRIPTION" => $description,
                "RESPONSIBLE_ID" => $responsibleId,
                "GROUP_ID" => $project_id,
                "PRIORITY" => $priority,
                "STATUS" => 1,
                "TAGS" => ["HelpDesk", "Ticket"]
            ]
        ];
        $task_id = create_bitrix_task($bitrix_data, $accessToken, $clientEndPoint);
        if ($task_id) {
            if ($fileId) {
                call_api('tasks.task.files.attach', ["taskId" => $task_id, "fileId" => $fileId], $accessToken, $clientEndPoint);
            }

            // Update ticket with task ID
            $update_stmt = $conn->prepare("UPDATE tickets SET task_id = ? WHERE ticket_id = ?");
            $update_stmt->bind_param("is", $task_id, $ticket_id);
            $update_stmt->execute();

            echo json_encode([
                'success' => true,
                'message' => "Ticket Created & Task Added in Bitrix24!",
                'task_id' => $task_id
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => "Task creation failed after retries in Bitrix24!"
            ]);
        }
    } else {
        echo json_encode([
            'success' => false,
            'message' => "Ticket creation failed in the database!"
        ]);
    }
}
?>
