<?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';
$userId = (int)($user['id'] ?? 0);

function connect_normalize_post_row(array $row): array {
    $media = $row['media'] ?? [];
    if (is_string($media)) {
        $decoded = json_decode($media, true);
        $media = is_array($decoded) ? $decoded : [];
    }
    if (!is_array($media)) $media = [];
    $row['media'] = array_values($media);
    $row['likes_count'] = (int)($row['likes_count'] ?? 0);
    $row['comments_count'] = (int)($row['comments_count'] ?? 0);
    $row['liked_by_me'] = connect_bool($row['liked_by_me'] ?? false);
    return $row;
}

function connect_fetch_post(PDO $pdo, int $postId, int $viewerId): ?array {
    $sql = "SELECT
                p.*,
                COALESCE((SELECT COUNT(*) FROM connect_post_likes l WHERE l.post_id = p.id), 0)::int AS likes_count,
                EXISTS(SELECT 1 FROM connect_post_likes l2 WHERE l2.post_id = p.id AND l2.user_id = :viewer_id) AS liked_by_me,
                COALESCE((SELECT COUNT(*) FROM connect_post_comments c WHERE c.post_id = p.id), 0)::int AS comments_count,
                COALESCE((
                    SELECT json_agg(
                        json_build_object(
                            'id', m.id,
                            'media_type', m.media_type,
                            'file_path', m.file_path,
                            'original_name', m.original_name,
                            'mime_type', m.mime_type,
                            'size_bytes', m.size_bytes,
                            'sort_order', m.sort_order
                        ) ORDER BY m.sort_order, m.id
                    )
                    FROM connect_post_media m
                    WHERE m.post_id = p.id
                ), '[]'::json) AS media
            FROM connect_posts p
            WHERE p.id = :post_id
            LIMIT 1";
    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':viewer_id', $viewerId, PDO::PARAM_INT);
    $stmt->bindValue(':post_id', $postId, PDO::PARAM_INT);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row ? connect_normalize_post_row($row) : null;
}

try {
    if ($method === 'GET') {
        $page = max(1, (int)($_GET['page'] ?? 1));
        $limit = max(1, min(50, (int)($_GET['limit'] ?? 25)));
        $offset = ($page - 1) * $limit;
        $q = connect_text($_GET['q'] ?? '', 120);

        $where = '';
        $params = [];
        if ($q !== '') {
            $where = 'WHERE (p.content ILIKE :search OR p.author_name ILIKE :search2 OR COALESCE(p.location, \'\') ILIKE :search3)';
            $needle = '%' . $q . '%';
            $params[':search'] = $needle;
            $params[':search2'] = $needle;
            $params[':search3'] = $needle;
        }

        $sql = "SELECT
                    p.*,
                    COALESCE((SELECT COUNT(*) FROM connect_post_likes l WHERE l.post_id = p.id), 0)::int AS likes_count,
                    EXISTS(SELECT 1 FROM connect_post_likes l2 WHERE l2.post_id = p.id AND l2.user_id = :viewer_id) AS liked_by_me,
                    COALESCE((SELECT COUNT(*) FROM connect_post_comments c WHERE c.post_id = p.id), 0)::int AS comments_count,
                    COALESCE((
                        SELECT json_agg(
                            json_build_object(
                                'id', m.id,
                                'media_type', m.media_type,
                                'file_path', m.file_path,
                                'original_name', m.original_name,
                                'mime_type', m.mime_type,
                                'size_bytes', m.size_bytes,
                                'sort_order', m.sort_order
                            ) ORDER BY m.sort_order, m.id
                        )
                        FROM connect_post_media m
                        WHERE m.post_id = p.id
                    ), '[]'::json) AS media
                FROM connect_posts p
                $where
                ORDER BY p.created_at DESC
                LIMIT :limit OFFSET :offset";
        $stmt = $pdo->prepare($sql);
        $stmt->bindValue(':viewer_id', $userId, PDO::PARAM_INT);
        foreach ($params as $key => $value) $stmt->bindValue($key, $value, PDO::PARAM_STR);
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->execute();
        $rows = array_map('connect_normalize_post_row', $stmt->fetchAll(PDO::FETCH_ASSOC));

        connect_json(200, [
            'data' => $rows,
            'page' => $page,
            'limit' => $limit,
            'has_more' => count($rows) === $limit,
        ]);
    }

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

    $content = connect_text($_POST['content'] ?? '', 5000);
    $taggedName = connect_text($_POST['tagged_name'] ?? '', 255);
    $location = connect_text($_POST['location'] ?? '', 255);
    $files = connect_normalize_files('media');

    if ($content === '' && count($files) === 0) {
        connect_json(400, ['detail' => 'Write something or attach a picture or video before posting.']);
    }
    if (count($files) > 6) {
        connect_json(400, ['detail' => 'A post can contain at most 6 pictures or one video.']);
    }

    $stored = [];
    foreach ($files as $file) {
        $stored[] = connect_store_upload($file, 'post');
    }
    $videoCount = count(array_filter($stored, fn($item) => $item['media_type'] === 'video'));
    $imageCount = count(array_filter($stored, fn($item) => $item['media_type'] === 'image'));
    if ($videoCount > 1 || ($videoCount > 0 && $imageCount > 0)) {
        foreach ($stored as $item) @unlink($item['absolute_path']);
        connect_json(400, ['detail' => 'Use either up to 6 pictures or one video in a post.']);
    }

    $authorId = (int)($user['id'] ?? 0);
    $authorName = connect_text($user['full_name'] ?? $user['name'] ?? 'Rockview User', 255);
    $authorEmail = connect_text($user['email'] ?? '', 255);
    $authorPic = connect_text($user['profile_picture'] ?? '', 0);
    $campus = connect_text($user['campus'] ?? '', 255);

    if ($authorId <= 0 || $authorEmail === '') {
        foreach ($stored as $item) @unlink($item['absolute_path']);
        connect_json(401, ['detail' => 'Your user profile could not be verified. Please sign in again.']);
    }

    $pdo->beginTransaction();
    try {
        $stmt = $pdo->prepare("INSERT INTO connect_posts
            (author_id, author_name, author_email, author_profile_picture, campus, content, tagged_name, location)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id");
        $stmt->execute([
            $authorId,
            $authorName,
            $authorEmail,
            $authorPic !== '' ? $authorPic : null,
            $campus !== '' ? $campus : null,
            $content,
            $taggedName !== '' ? $taggedName : null,
            $location !== '' ? $location : null,
        ]);
        $postId = (int)$stmt->fetchColumn();

        if ($stored) {
            $mediaStmt = $pdo->prepare("INSERT INTO connect_post_media
                (post_id, media_type, file_path, original_name, mime_type, size_bytes, sort_order)
                VALUES (?, ?, ?, ?, ?, ?, ?)");
            foreach ($stored as $index => $item) {
                $mediaStmt->execute([
                    $postId,
                    $item['media_type'],
                    $item['file_path'],
                    $item['original_name'],
                    $item['mime_type'],
                    $item['size_bytes'],
                    $index,
                ]);
            }
        }
        $pdo->commit();
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        foreach ($stored as $item) @unlink($item['absolute_path']);
        throw $e;
    }

    $post = connect_fetch_post($pdo, $postId, $userId);
    connect_json(201, [
        'message' => 'Post published successfully.',
        'data' => $post ?? ['id' => $postId],
    ]);
} catch (Throwable $e) {
    connect_json(500, ['detail' => 'Post service error: ' . $e->getMessage()]);
}
