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

header("Content-Type: application/json");

try {
    require_once __DIR__ . "/../auth/require-auth.php";
    require_once __DIR__ . "/../services/db.php";

    $conn = db();

    if (!$conn) {
        http_response_code(500);
        echo json_encode(["error" => "Database connection failed"]);
        exit;
    }

    $data = json_decode(file_get_contents("php://input"), true);

    $taskId = isset($data['task_id']) ? (int)$data['task_id'] : null;
    $comment = trim($data['comment'] ?? $data['text'] ?? '');
    $attachmentDataUrl = isset($data['attachment_url']) ? $data['attachment_url'] : null;
    $userId = $_SESSION['user']['id'] ?? 1;

    if (!$taskId || (!$comment && !$attachmentDataUrl)) {
        http_response_code(400);
        echo json_encode(["error" => "task_id and comment text or screenshot are required"]);
        exit;
    }

    // 1. Combine comment text with Base64 Image Tag directly
    $finalContent = $comment;
    if ($attachmentDataUrl) {
        $finalContent .= ($finalContent ? "\n\n" : "") . "[IMAGE]" . $attachmentDataUrl . "[/IMAGE]";
    }

    // 2. Inspect columns in 'comments' table
    $colSql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'comments'";
    $colStmt = sqlsrv_query($conn, $colSql);
    $existingCols = [];

    if ($colStmt !== false) {
        while ($r = sqlsrv_fetch_array($colStmt, SQLSRV_FETCH_ASSOC)) {
            $existingCols[] = strtolower($r['COLUMN_NAME']);
        }
    }

    // Determine target text column
    $textCol = 'comment';
    $textCandidates = ['comment', 'content', 'body', 'message', 'text', 'description'];
    foreach ($textCandidates as $cand) {
        if (in_array($cand, $existingCols)) {
            $textCol = $cand;
            break;
        }
    }

    $hasUserId = in_array('user_id', $existingCols) || in_array('author_id', $existingCols);
    $userCol = in_array('author_id', $existingCols) ? 'author_id' : 'user_id';
    $hasCreatedAt = in_array('created_at', $existingCols);

    // 3. Build dynamic query
    if ($hasUserId && $hasCreatedAt) {
        $sql = "INSERT INTO comments (task_id, $userCol, $textCol, created_at) VALUES (?, ?, ?, GETDATE())";
        $params = [$taskId, $userId, $finalContent];
    } elseif ($hasCreatedAt) {
        $sql = "INSERT INTO comments (task_id, $textCol, created_at) VALUES (?, ?, GETDATE())";
        $params = [$taskId, $finalContent];
    } else {
        $sql = "INSERT INTO comments (task_id, $textCol) VALUES (?, ?)";
        $params = [$taskId, $finalContent];
    }

    $stmt = sqlsrv_query($conn, $sql, $params);

    if ($stmt === false) {
        $errors = sqlsrv_errors();
        http_response_code(500);
        echo json_encode([
            "error" => "SQL INSERT failed for comments",
            "message" => $errors[0]['message'] ?? 'Failed to insert comment'
        ]);
        exit;
    }

    $resId = sqlsrv_query($conn, "SELECT SCOPE_IDENTITY() AS id");
    $idRow = sqlsrv_fetch_array($resId, SQLSRV_FETCH_ASSOC);

    echo json_encode([
        "success" => true,
        "comment" => [
            "id" => (int)($idRow['id'] ?? 0),
            "task_id" => $taskId,
            "text" => $finalContent,
            "user" => $_SESSION['user']['name'] ?? "Khyn Alfiler",
            "time" => "Just now"
        ]
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        "error" => "Server error",
        "message" => $e->getMessage()
    ]);
}