<?php
include '../db_connect.php';

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

$key = $data['key'] ?? '';
$userid = $data['userid'] ?? '';       // লগইন করা ইউজার
$friendid = $data['friendid'] ?? '';   // যার প্রোফাইল দেখা হচ্ছে

$security_key = decryptData($key);

if ($security_key === 'Jobayer121415' && !empty($friendid)) {
    $con = dbConnect();

    // ইউজারের প্রোফাইল ইনফো
    $sql = "SELECT * FROM singup_table WHERE id = ?";
    $stmt = $con->prepare($sql);
    $stmt->bind_param("i", $friendid);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($user = $result->fetch_assoc()) {
        // Followers count
        $followers_sql = "SELECT COUNT(*) AS followers_count FROM followers WHERE following_id = ?";
        $stmt1 = $con->prepare($followers_sql);
        $stmt1->bind_param("i", $friendid);
        $stmt1->execute();
        $followers_result = $stmt1->get_result();
        $followers_count = $followers_result->fetch_assoc()["followers_count"];

        // Following count
        $following_sql = "SELECT COUNT(*) AS following_count FROM followers WHERE follower_id = ?";
        $stmt2 = $con->prepare($following_sql);
        $stmt2->bind_param("i", $friendid);
        $stmt2->execute();
        $following_result = $stmt2->get_result();
        $following_count = $following_result->fetch_assoc()["following_count"];

        // Follow status check (friendid কে userid ফলো করে কিনা)
        $check_follow_sql = "SELECT id FROM followers WHERE follower_id = ? AND following_id = ?";
        $stmt3 = $con->prepare($check_follow_sql);
        $stmt3->bind_param("ii", $userid, $friendid);
        $stmt3->execute();
        $check_follow_result = $stmt3->get_result();
        $is_followed = ($check_follow_result->num_rows > 0);

        // সব ডেটা একসাথে
        $response = [
            'id' => $user['id'],
            'name' => $user['name'],
            'email' => $user['email'],
            'phone' => $user['phone'],
            'password' => $user['password'],
            'image' => $user['image'],
            'time' => $user['time'],
            'cover' => $user['cover'],
            'gender' => $user['gender'],
            'birthdate' => $user['birthdate'],
            'country' => $user['country'],
            'bio' => $user['bio'],
            'token' => $user['token'],
            'status' => $user['status'],
            'online' => $user['online'],
            'followers' => $followers_count,
            'following' => $following_count,
            'is_followed' => $is_followed
        ];

        echo json_encode($response);
    } else {
        echo json_encode(['error' => 'User not found']);
    }
} else {
    echo json_encode(['error' => 'Invalid key or missing data']);
}

// ডাটা ডিক্রিপশন ফাংশন
function decryptData($text) {
    $decoded = base64_decode($text);
    return openssl_decrypt($decoded, 'AES-128-ECB', '0175526800812345', OPENSSL_RAW_DATA);
}
?>
