<?php

include_once __DIR__ . '/../secrets.php';
header('Content-Type: application/json; charset=utf-8');
include '../db_connect.php';

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

$data = $jsonArray[0];
$userid = $data['userid'];
$friend_userid = $data['friend_userid'];
$key = $data['key'];

$response = array();

$security_key = decrypData($key);

if ($security_key === false) {
    echo json_encode(['error' => 'Invalid encryption data']);
    exit;
}

if ($security_key == SECURITY_KEY_PLAIN) {

    $con = dbConnect();
    $url = 'https://app.bpluspro.xyz/social/post/';
    $profileurl = 'https://app.bpluspro.xyz/social/';
    $postArray = array();

    // Modified SQL query to handle both Profile and Page types
    $postSql = "
    SELECT 
        p.*,
        CASE 
            WHEN p.account_type = 'Profile' THEN s.name
            WHEN p.account_type = 'Page' THEN pg.name
        END AS name,
        CASE 
            WHEN p.account_type = 'Profile' THEN s.image
            WHEN p.account_type = 'Page' THEN pg.image
        END AS image,
        CASE 
            WHEN p.account_type = 'Profile' THEN s.bpay
            WHEN p.account_type = 'Page' THEN pg.bpay
        END AS bpay,
        CASE 
            WHEN p.account_type = 'Profile' THEN s.token
            WHEN p.account_type = 'Page' THEN pg.token
        END AS token,
        p.account_type,
        IF(f.id IS NULL, 0, 1) AS isFavorite
    FROM post_table p 
    LEFT JOIN signup s ON p.account_type = 'Profile' AND p.userid = s.userid
    LEFT JOIN page_table pg ON p.account_type = 'Page' AND p.userid = pg.userid
    LEFT JOIN favorite_posts f 
        ON f.post_id = p.id 
        AND f.user_id = '$userid'
    WHERE p.type = 'Public'
    ORDER BY RAND()
    ";

    $postResult = mysqli_query($con, $postSql);

    while ($item = mysqli_fetch_assoc($postResult)) {
        $postId = $item['id'];
        $postOwnerId = $item['userid'];
        $accountType = $item['account_type'];
        $friendStatus = 'none';

        // Images
        $imgPath = $item['images'];
        $imageList = [];
        if ($imgPath) {
            $images = explode(',', $imgPath);
            foreach ($images as $img) {
                $imageList[] = $url . trim($img);
            }
        } else {
            $imageList = null;
        }

        // Get reactions count per type
        $reactionCounts = [];
        $totalReacts = 0;
        $reactionSql = "SELECT reaction_type, COUNT(*) AS total 
                        FROM post_reactions 
                        WHERE post_id = '$postId' 
                        GROUP BY reaction_type";
        $reactionResult = mysqli_query($con, $reactionSql);
        while ($r = mysqli_fetch_assoc($reactionResult)) {
            $reactionCounts[$r['reaction_type']] = (int)$r['total'];
            $totalReacts += (int)$r['total'];
        }

        // Get user reaction
        $userReaction = '';
        $userReactionSql = "SELECT reaction_type FROM post_reactions 
                            WHERE post_id = '$postId' 
                            AND user_id = '$userid' LIMIT 1";
        $userReactionResult = mysqli_query($con, $userReactionSql);
        if (mysqli_num_rows($userReactionResult) > 0) {
            $row = mysqli_fetch_assoc($userReactionResult);
            $userReaction = $row['reaction_type'];
        }
        
        arsort($reactionCounts);

        // Take only top 3 reactions
        $top3Reactions = array_slice($reactionCounts, 0, 3, true);
        
        // Get comment count for this post
        $commentCount = 0;
        $commentSql = "SELECT COUNT(*) as total_comments FROM comment_table WHERE postid = '$postId'";
        $commentResult = mysqli_query($con, $commentSql);
        if ($commentResult) {
            $commentRow = mysqli_fetch_assoc($commentResult);
            $commentCount = (int)$commentRow['total_comments'];
        }
        
            // Check pending request only for Profile posts
            $checkPendingSql = "SELECT status FROM friends_request
                        WHERE
                        (
                            sender_id = '$userid' AND receiver_id = '$postOwnerId'
                        )
                        OR
                        (
                            sender_id = '$postOwnerId' AND receiver_id = '$userid'
                        )
                        LIMIT 1";

            $pendingResult = mysqli_query($con, $checkPendingSql);

            if (mysqli_num_rows($pendingResult) > 0) {
                $row = mysqli_fetch_assoc($pendingResult);
                $friendStatus = $row['status'];  // pending / accepted / rejected
            }
       

        $postArray[] = array(
            'id'            => $postId,
            'userid'        => $item['userid'],
            'name'          => $item['name'],
            'profile'       => $profileurl.$item['image'],
            'text'          => $item['text'],
            'images'        => $imageList,
            'time'          => $item['time'],
            'type'          => $item['type'],
            'account_type'  => $accountType,
            'bpay'          => $item['bpay'],
            'token'         => $item['token'],
            'userReaction'  => $userReaction,
            'reactionCounts'=> $reactionCounts,
            'totalReacts'   => $totalReacts,
            'top3'          => $top3Reactions,
            'commentCount'  => $commentCount,
            'friendStatus'  => $friendStatus,
            'isFavorite'    => (bool)$item['isFavorite']
        );
    }

    $response[] = array(
        'post' => $postArray
    );

    echo json_encode($response, JSON_UNESCAPED_SLASHES); 
}
?>