<?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'];

$security_key = decrypData($key);
$response = array();

if ($security_key == 'Jobayer121415') {

    $con = dbConnect();

    $notFollowingArray = array();

    $sql = "SELECT 
                s.id, 
                s.name, 
                s.image,
                (SELECT COUNT(*) FROM post_table p WHERE p.userid = s.id) AS post_count,
                (SELECT COUNT(*) FROM followers f WHERE f.following_id = s.id) AS followers_count
            FROM singup_table s
            WHERE s.id != ? 
            AND s.id NOT IN (
                SELECT following_id FROM followers WHERE follower_id = ?
            )";

    $stmt = $con->prepare($sql);
    $stmt->bind_param("ss", $userid, $userid);
    $stmt->execute();
    $result = $stmt->get_result();

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

        // ✅ ইউজারের স্ট্যাটাস খুঁজে বের করা
        $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'];
        }
        

        $notFollowingArray[] = array(
            'id' => $item['id'],
            'name' => $item['name'],
            'image' => $item['image'],
            'post_count' => $item['post_count'],
            'followers_count' => $item['followers_count'],
            'status' => $status // ✅ নতুন ফিল্ড
        );
    }

    // Shuffle the array so that results come in random order
    shuffle($notFollowingArray);

    $response[] = array(
        'not_following' => $notFollowingArray
    );

    echo json_encode($response); 

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

// Key decrypt function
function decrypData($text) {
    $decoded = base64_decode($text);
    $decrypted = openssl_decrypt($decoded, 'AES-128-ECB', '0175526800812345', OPENSSL_RAW_DATA);
    return $decrypted;
}
?>
