 <?php
$dir = "webhook_logs";
$file = $dir . "/webhook_data.txt";

// Raw POST input
$input = file_get_contents('php://input');

// Create directory if it doesn't exist
if (!is_dir($dir)) {
    mkdir($dir, 0777, true);
}

// Create log file if not exists
if (!file_exists($file)) {
    file_put_contents($file, "Webhook Log Start:\n");
}

// Log raw webhook input
file_put_contents($file, "Raw webhook data:\n" . $input . PHP_EOL, FILE_APPEND);

// Parse URL-encoded form data into array
parse_str($input, $data);

// Extract required values
$taskId = $data['data']['FIELDS_AFTER']['TASK_ID'] ?? null;
$commentId = $data['data']['FIELDS_AFTER']['ID'] ?? null;
$domain = $data['auth']['domain'];
$authToken = 'up80mdczj9hhglgv'; // Static if webhook token is fixed

if ($taskId && $commentId) {
    $url = "https://$domain/rest/730/$authToken/task.commentitem.get.json";
    $postData = "0=$taskId&1=$commentId";

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postData,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/x-www-form-urlencoded'
        ]
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode === 200 && $response) {
        $commentData = json_decode($response, true);

        if (isset($commentData['result'])) {
            $commentText = $commentData['result']['POST_MESSAGE'] ?? '(No Text)';
            $commentAuthor = $commentData['result']['AUTHOR_ID'] ?? 'Unknown';
            $commentDate = $commentData['result']['CREATED_DATE'] ?? 'Unknown';

            $log = "New Comment Added:\n";
            $log .= "Task ID: $taskId\n";
            $log .= "Comment ID: $commentId\n";
            $log .= "Author ID: $commentAuthor\n";
            $log .= "Date: $commentDate\n";
            $log .= "Text: $commentText\n\n";
            $log .= "Text: $domain\n\n";

            file_put_contents($file, $log, FILE_APPEND);
            echo "✅ Comment fetched and logged.";
        } else {
            file_put_contents($file, "⚠️ API response missing result. Raw: $response\n", FILE_APPEND);
            echo "⚠️ Comment not found in response.";
        }
    } else {
        file_put_contents($file, "❌ API call failed. HTTP Code: $httpCode. Response: $response\n", FILE_APPEND);
        echo "❌ Failed to fetch comment.";
    }
} else {
    file_put_contents($file, "❌ Missing TASK_ID or COMMENT_ID in payload.\n", FILE_APPEND);
    echo "❌ Required data missing.";
}
?>
