<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['ok' => false, 'error' => 'Invalid method']);
    exit;
}

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

$projectId = (int)($input['project_id'] ?? 0);
$comment = trim((string)($input['comment'] ?? ''));
$token = trim((string)($input['csrf_token'] ?? ''));

if (empty($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $token)) {
    echo json_encode(['ok' => false, 'error' => 'CSRF verification failed']);
    exit;
}

if ($projectId <= 0 || $comment === '') {
    echo json_encode(['ok' => false, 'error' => 'Missing data']);
    exit;
}

$uid = gp_current_user_id();
if ($uid <= 0) {
    echo json_encode(['ok' => false, 'error' => 'Not authenticated']);
    exit;
}

$pdo = crm_pdo();
try {
    $stmtInsert = $pdo->prepare("INSERT INTO project_comments (project_id, user_id, comment) VALUES (?, ?, ?)");
    $stmtInsert->execute([$projectId, $uid, $comment]);
    gp_log_action($pdo, 'PROJECT_COMMENT', 'project', $projectId, "Νέο σχόλιο: $comment");

    // Send the user info back so we can render it without reload
    $stmtUser = $pdo->prepare("SELECT username FROM users WHERE id = ?");
    $stmtUser->execute([$uid]);
    $uName = $stmtUser->fetchColumn();

    $newCommentHtml = '
    <div class="timeline-item" style="display:flex; gap:12px; margin-bottom:16px;">
        <div style="background:var(--gp-nav-bg-2); border:1px solid var(--gp-card-border); padding:10px 14px; border-radius:12px; width:100%;">
            <div style="display:flex; justify-content:space-between; margin-bottom:4px;">
                <span style="font-weight:700; font-size:0.85rem;">' . htmlspecialchars((string)($uName ?: 'User')) . '</span>
                <span style="font-size:0.75rem; color:var(--gp-muted);">just now</span>
            </div>
            <div style="font-size:0.9rem; line-height:1.4;">' . nl2br(htmlspecialchars($comment)) . '</div>
        </div>
    </div>';

    echo json_encode(['ok' => true, 'html' => $newCommentHtml]);
} catch (Throwable $e) {
    echo json_encode(['ok' => false, 'error' => 'Database error']);
}
