<?php
require_once __DIR__ . '/connect_common.php';
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') connect_json(204);
connect_assert_request_size();
$user = connect_user($pdo);
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

try {
    if ($method === 'GET') {
        $postId = (int)($_GET['post_id'] ?? 0);
        if ($postId <= 0) connect_json(400, ['detail' => 'post_id is required.']);
        $stmt = $pdo->prepare("SELECT * FROM connect_post_comments WHERE post_id = ? ORDER BY created_at ASC, id ASC");
        $stmt->execute([$postId]);
        connect_json(200, ['data' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
    }

    if ($method !== 'POST') connect_json(405, ['detail' => 'Only GET and POST are supported for comments.']);

    $postId = (int)($_POST['post_id'] ?? 0);
    $parentId = isset($_POST['parent_id']) && ctype_digit((string)$_POST['parent_id']) ? (int)$_POST['parent_id'] : null;
    $content = connect_text($_POST['content'] ?? '', 2500);
    $imagePath = null;
    $savedAbsolute = null;

    if (isset($_FILES['image']) && ($_FILES['image']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
        $stored = connect_store_upload($_FILES['image'], 'comment');
        $imagePath = $stored['file_path'];
        $savedAbsolute = $stored['absolute_path'];
    }
    if ($postId <= 0) {
        if ($savedAbsolute) @unlink($savedAbsolute);
        connect_json(400, ['detail' => 'A valid post is required.']);
    }
    if ($content === '' && $imagePath === null) {
        if ($savedAbsolute) @unlink($savedAbsolute);
        connect_json(400, ['detail' => 'Write a comment or attach a picture.']);
    }

    $postCheck = $pdo->prepare('SELECT id, author_id, author_name, author_email FROM connect_posts WHERE id = ?');
    $postCheck->execute([$postId]);
    $post = $postCheck->fetch(PDO::FETCH_ASSOC);
    if (!$post) {
        if ($savedAbsolute) @unlink($savedAbsolute);
        connect_json(404, ['detail' => 'Post not found.']);
    }

    $parent = null;
    if ($parentId !== null) {
        $parentCheck = $pdo->prepare('SELECT id, author_id, author_name, author_email FROM connect_post_comments WHERE id = ? AND post_id = ?');
        $parentCheck->execute([$parentId, $postId]);
        $parent = $parentCheck->fetch(PDO::FETCH_ASSOC);
        if (!$parent) $parentId = null;
    }

    $pdo->beginTransaction();
    try {
        $stmt = $pdo->prepare("INSERT INTO connect_post_comments
            (post_id, parent_id, author_id, author_name, author_email, author_profile_picture, content, image_path)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING *");
        $stmt->execute([
            $postId,
            $parentId,
            (int)($user['id'] ?? 0),
            connect_text($user['full_name'] ?? $user['name'] ?? 'Rockview User', 255),
            connect_text($user['email'] ?? '', 255),
            connect_text($user['profile_picture'] ?? '', 0) ?: null,
            $content,
            $imagePath,
        ]);
        $comment = $stmt->fetch(PDO::FETCH_ASSOC);
        $commentId = (int)($comment['id'] ?? 0);

        $actorName = connect_text($user['full_name'] ?? 'Someone', 120);
        $bodyText = $content !== ''
            ? $actorName . ' commented: "' . connect_text($content, 180) . '"'
            : $actorName . ' added a picture comment.';

        connect_notify(
            $pdo,
            (int)($post['author_id'] ?? 0),
            connect_text($post['author_email'] ?? '', 255),
            $user,
            'comment',
            'New comment on your post',
            $bodyText,
            $postId,
            $commentId,
            null,
            'comment:' . $commentId . ':post-author'
        );

        if ($parent && (int)($parent['author_id'] ?? 0) !== (int)($post['author_id'] ?? 0)) {
            connect_notify(
                $pdo,
                (int)($parent['author_id'] ?? 0),
                connect_text($parent['author_email'] ?? '', 255),
                $user,
                'reply',
                'New reply to your comment',
                $actorName . ' replied to your comment.',
                $postId,
                $commentId,
                null,
                'reply:' . $commentId . ':parent-author'
            );
        }

        $pdo->commit();
        connect_json(201, ['message' => 'Comment added.', 'data' => $comment]);
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        if ($savedAbsolute) @unlink($savedAbsolute);
        throw $e;
    }
} catch (Throwable $e) {
    if (isset($savedAbsolute) && $savedAbsolute && is_file($savedAbsolute)) @unlink($savedAbsolute);
    connect_json(500, ['detail' => 'Comment service error: ' . $e->getMessage()]);
}
