<?php
/**
 * API: Post Comment on a Submission
 * POST /api/post-comment.php
 * Requires: login, submission_id, comment_text, csrf_token
 */
session_start();
header('Content-Type: application/json');

require_once __DIR__ . '/../config.php';

// Auth check
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['ok' => false, 'error' => 'You must be logged in to comment.']);
    exit;
}

// CSRF check
if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'] ?? '', $_POST['csrf_token'])) {
    echo json_encode(['ok' => false, 'error' => 'Invalid security token.']);
    exit;
}

$user_id       = intval($_SESSION['user_id']);
$submission_id = intval($_POST['submission_id'] ?? 0);
$comment_text  = trim($_POST['comment_text'] ?? '');

if ($submission_id <= 0 || $comment_text === '') {
    echo json_encode(['ok' => false, 'error' => 'Comment text is required.']);
    exit;
}

// Sanitize
$comment_text = htmlspecialchars($comment_text, ENT_QUOTES, 'UTF-8');

// Verify submission exists
$chk = $conn->prepare("SELECT id FROM submissions WHERE id = ?");
$chk->bind_param("i", $submission_id);
$chk->execute();
if ($chk->get_result()->num_rows === 0) {
    echo json_encode(['ok' => false, 'error' => 'Submission not found.']);
    exit;
}
$chk->close();

// Insert comment
$stmt = $conn->prepare("INSERT INTO submission_comments (submission_id, user_id, comment_text, created_at) VALUES (?, ?, ?, NOW())");
$stmt->bind_param("iis", $submission_id, $user_id, $comment_text);

if ($stmt->execute()) {
    $comment_id = $stmt->insert_id;
    $stmt->close();

    // Fetch the newly created comment with user info
    $fetch = $conn->prepare("SELECT c.id, c.comment_text, c.created_at, u.organization_name, u.email
                             FROM submission_comments c
                             JOIN users u ON c.user_id = u.id
                             WHERE c.id = ?");
    $fetch->bind_param("i", $comment_id);
    $fetch->execute();
    $row = $fetch->get_result()->fetch_assoc();
    $fetch->close();

    $display_name = !empty($row['organization_name']) ? $row['organization_name'] : explode('@', $row['email'])[0];

    echo json_encode([
        'ok' => true,
        'comment' => [
            'id'           => $row['id'],
            'text'         => $row['comment_text'],
            'author'       => $display_name,
            'created_at'   => date('M j, Y g:i A', strtotime($row['created_at']))
        ]
    ]);
} else {
    echo json_encode(['ok' => false, 'error' => 'Failed to save comment.']);
}
