<?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];
$key = $data['key'] ?? '';
$userid = $data['userid'] ?? '';
$postid = $data['type'] ?? ''; // টাইপ: image / Followers / Following

$security_key = decryptData($key);
$response = [];

if ($security_key === 'Jobayer121415' && !empty($userid)) {

    $con = dbConnect();
    $followersArray = [];

    // Followers / Following অনুযায়ী SQL
    if ($postid === 'image' || $postid === 'Followers') {
        $followersSql = "SELECT s.id, s.name, s.image 
                         FROM followers f 
                         JOIN singup_table s ON f.follower_id = s.id 
                         WHERE f.following_id = ? 
                         ORDER BY f.id DESC" . ($postid === 'image' ? ' LIMIT 8' : '');
    } else if ($postid === 'Following') {
        $followersSql = "SELECT s.id, s.name, s.image 
                         FROM followers f 
                         JOIN singup_table s ON f.following_id = s.id 
                         WHERE f.follower_id = ? 
                         ORDER BY f.id DESC";
    }

    // Followers Query চালানো
    if (!empty($followersSql)) {
        $stmt = $con->prepare($followersSql);
        $stmt->bind_param('i', $userid);
        $stmt->execute();
        $result = $stmt->get_result();

        while ($row = $result->fetch_assoc()) {
            $target_user_id = $row['id'];

            // ইউজার ফলো করছে কিনা
            $follow_sql = 'SELECT id FROM followers WHERE follower_id = ? AND following_id = ?';
            $follow_stmt = $con->prepare($follow_sql);
            $follow_stmt->bind_param('ii', $userid, $target_user_id);
            $follow_stmt->execute();
            $follow_result = $follow_stmt->get_result();
            $is_following = ($follow_result->num_rows > 0);

            // পোস্ট সংখ্যা
            $post_stmt = $con->prepare('SELECT COUNT(*) FROM post_table WHERE userid = ?');
            $post_stmt->bind_param('i', $target_user_id);
            $post_stmt->execute();
            $post_stmt->bind_result($post_count);
            $post_stmt->fetch();
            $post_stmt->close();

            // ফলোয়ার সংখ্যা
            $followers_stmt = $con->prepare('SELECT COUNT(*) FROM followers WHERE following_id = ?');
            $followers_stmt->bind_param('i', $target_user_id);
            $followers_stmt->execute();
            $followers_stmt->bind_result($followers_count);
            $followers_stmt->fetch();
            $followers_stmt->close();

            // স্ট্যাটাস (signup_table থেকে)
            $status = "";
            $status_stmt = $con->prepare("SELECT status FROM singup_table WHERE id = ?");
            $status_stmt->bind_param("i", $target_user_id);
            $status_stmt->execute();
            $status_result = $status_stmt->get_result();
            if ($status_row = $status_result->fetch_assoc()) {
                $status = $status_row['status'];
            }

            $followersArray[] = [
                'id' => $row['id'],
                'name' => $row['name'],
                'image' => $row['image'],
                'is_following' => $is_following,
                'post_count' => $post_count,
                'followers_count' => $followers_count,
                'status' => $status
            ];
        }
    }

    // ==========================
    // Comments Section
    // ==========================
    $commentArray = [];

    if (!empty($postid)) {
        $sql = 'SELECT * FROM comment_table WHERE postid = ? ORDER BY id DESC';
        $stmt = $con->prepare($sql);
        $stmt->bind_param('s', $postid);
        $stmt->execute();
        $result = $stmt->get_result();

        while ($row = $result->fetch_assoc()) {
            $comment_user_id = $row['userid'];

            // ইউজার ফলো করছে কিনা
            $follow_sql = 'SELECT id FROM followers WHERE follower_id = ? AND following_id = ?';
            $follow_stmt = $con->prepare($follow_sql);
            $follow_stmt->bind_param('ii', $userid, $comment_user_id);
            $follow_stmt->execute();
            $follow_result = $follow_stmt->get_result();
            $is_following = ($follow_result->num_rows > 0);

            // স্ট্যাটাস (signup_table থেকে)
            $comment_status = "";
            $status_stmt = $con->prepare("SELECT status FROM singup_table WHERE id = ?");
            $status_stmt->bind_param("i", $comment_user_id);
            $status_stmt->execute();
            $status_result = $status_stmt->get_result();
            if ($status_row = $status_result->fetch_assoc()) {
                $comment_status = $status_row['status'];
            }
        

            $commentArray[] = [
                'id' => $row['id'],
                'userid' => $comment_user_id,
                'postid' => $row['postid'],
                'comment' => $row['comment'],
                'time' => $row['time'],
                'name' => $row['name'],
                'profile' => $row['profile'],
                'is_following' => $is_following,
                'status' => $comment_status
            ];
        }
    }

    // ✅ Final JSON Response
    $response[] = array(
        'followers' => $followersArray,
        'comment' => $commentArray
    );

    echo json_encode($response);

} else {
    echo json_encode(['error' => 'Invalid key or missing data']);
}

// ✅ Key Decrypt Function
function decryptData($text) {
    $decoded = base64_decode($text);
    return openssl_decrypt($decoded, 'AES-128-ECB', '0175526800812345', OPENSSL_RAW_DATA);
}
?>
