<?php
require_once '../config/database.php';

$db = new Database();
$conn = $db->connect();

$method = $_SERVER['REQUEST_METHOD'];
$requestUri = $_SERVER['REQUEST_URI'];

if ($method === 'GET') {
    $username = $_GET['username'] ?? null;

    // Fetch all posts
    $stmt = $conn->prepare('SELECT * FROM posts ORDER BY time DESC');
    $stmt->execute();
    $posts = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Prepare statement once to get user's image by username (assuming username is unique)
    $userImageStmt = $conn->prepare('SELECT image FROM users WHERE username = ? LIMIT 1');

    foreach ($posts as &$post) {
        // Get user image from users table
        $userImageStmt->execute([$post['username']]);
        $userImage = $userImageStmt->fetchColumn();
        
        // Attach user image URL to the post, override if you want
        $post['user_image'] = $userImage ?: null; // fallback null if not found

        // Check if the passed username liked this post
        if ($username) {
            $likeStmt = $conn->prepare('SELECT COUNT(*) FROM likes WHERE post_id = ? AND username = ?');
            $likeStmt->execute([$post['id'], $username]);
            $post['hasLiked'] = $likeStmt->fetchColumn() > 0 ? true : false;
        } else {
            $post['hasLiked'] = false;
        }
    }

    echo json_encode($posts);
    exit;
}


// For POST requests, decode input JSON once
if ($method === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);

    // 1. Delete post
    if (isset($data['delete_post_id'])) {
    $postId = $data['delete_post_id'];

    // Delete related comments first
    $stmt = $conn->prepare('DELETE FROM comments WHERE post_id = ?');
    $stmt->execute([$postId]);

    // Delete related likes
    $stmt = $conn->prepare('DELETE FROM likes WHERE post_id = ?');
    $stmt->execute([$postId]);

    // Delete related reports
    $stmt = $conn->prepare('DELETE FROM post_reports WHERE post_id = ?');
    $stmt->execute([$postId]);

    // Finally, delete the post
    $stmt = $conn->prepare('DELETE FROM posts WHERE id = ?');
    $stmt->execute([$postId]);

    echo json_encode(['success' => true, 'message' => 'Post and related data deleted']);
    exit;
}


    // 2. Report post
    if (isset($data['report_post_id'], $data['reporter_username'], $data['reason'])) {
        $reportId = uniqid();
        $stmt = $conn->prepare(
            'INSERT INTO post_reports (id, post_id, reporter_username, reason, reported_at) 
             VALUES (?, ?, ?, ?, NOW())'
        );

        $stmt->execute([
            $reportId,
            $data['report_post_id'],
            $data['reporter_username'],
            $data['reason']
        ]);

        echo json_encode(['success' => true, 'message' => 'Report submitted']);
        exit;
    }

    // 3. Like/unlike post (URL pattern posts.php/{postId}/like)
    if (preg_match('/posts\.php\/(.+)\/like/', $requestUri, $matches)) {
        $postId = $matches[1];
        $username = $data['username'] ?? 'anonymous';

        // Check if liked
        $stmt = $conn->prepare('SELECT COUNT(*) FROM likes WHERE post_id = ? AND username = ?');
        $stmt->execute([$postId, $username]);
        $likedCount = $stmt->fetchColumn();

        if ($likedCount > 0) {
            // Unlike
            $stmt = $conn->prepare('DELETE FROM likes WHERE post_id = ? AND username = ?');
            $stmt->execute([$postId, $username]);

            $stmt = $conn->prepare('UPDATE posts SET likes = GREATEST(likes - 1, 0) WHERE id = ?');
            $stmt->execute([$postId]);

            $hasLiked = false;
        } else {
            // Like
            $id = uniqid();
            $stmt = $conn->prepare('INSERT INTO likes (id, post_id, username) VALUES (?, ?, ?)');
            $stmt->execute([$id, $postId, $username]);

            $stmt = $conn->prepare('UPDATE posts SET likes = likes + 1 WHERE id = ?');
            $stmt->execute([$postId]);

            $hasLiked = true;
        }

        // Get updated likes count
        $stmt = $conn->prepare('SELECT likes FROM posts WHERE id = ?');
        $stmt->execute([$postId]);
        $likes = (int)$stmt->fetchColumn();

        echo json_encode(['success' => true, 'likes' => $likes, 'hasLiked' => $hasLiked]);
        exit;
    }

    // 4. Create new post (default POST)
    $required = ['username', 'user_image', 'content', 'likes', 'comments', 'time'];
    foreach ($required as $key) {
        if (!isset($data[$key])) {
            http_response_code(400);
            echo json_encode(['error' => "Missing key: $key"]);
            exit;
        }
    }

    $id = uniqid();

    $stmt = $conn->prepare(
        'INSERT INTO posts (id, username, user_image, content, image_url, likes, comments, time) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
    );

    $stmt->execute([
        $id,
        $data['username'],
        $data['user_image'],
        $data['content'],
        $data['image_url'] ?? null,
        $data['likes'],
        $data['comments'],
        $data['time']
    ]);

    http_response_code(201);
    echo json_encode(['id' => $id]);
    exit;
}

// If method not handled
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit;
