<?php

include_once __DIR__ . '/secrets.php';
include 'db_connect.php';

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

$key = $data['key'];
$userid = $data['userid'];              // Me
$friend_userid = $data['friend_userid']; // Other user

$security_key = decrypData($key);

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

if ($security_key == SECURITY_KEY_PLAIN && strlen($userid) > 0) {

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

    // ================= USER DATA =================
    $sql = "SELECT * FROM page_table WHERE userid = '$userid'";
    $output = mysqli_query($con, $sql);

    if ($output && mysqli_num_rows($output) > 0) {

        $row = mysqli_fetch_assoc($output);

        /* ===============================
           FRIEND REQUEST COUNTS
        =================================*/
        $pending_in = mysqli_fetch_assoc(
            mysqli_query($con,
                "SELECT COUNT(*) AS total FROM friends_request 
                 WHERE receiver_id = '$userid' AND status = 'pending'")
        )['total'];

        $accepted_out = mysqli_fetch_assoc(
            mysqli_query($con,
                "SELECT COUNT(*) AS total FROM friends_request 
                 WHERE sender_id = '$userid' AND status = 'accepted'")
        )['total'];

        $accepted_in = mysqli_fetch_assoc(
            mysqli_query($con,
                "SELECT COUNT(*) AS total FROM friends_request 
                 WHERE receiver_id = '$userid' AND status = 'accepted'")
        )['total'];

        /* ===============================
           TWO-WAY FRIEND STATUS CHECK
        =================================*/
        $relationship_status = 'none';

        $sql_relation = "
            SELECT sender_id, receiver_id, status 
            FROM friends_request
            WHERE 
                (sender_id = '$userid' AND receiver_id = '$friend_userid')
             OR (sender_id = '$friend_userid' AND receiver_id = '$userid')
            LIMIT 1
        ";

        $res_relation = mysqli_query($con, $sql_relation);

        if ($res_relation && mysqli_num_rows($res_relation) > 0) {
            $rel = mysqli_fetch_assoc($res_relation);

            if ($rel['status'] === 'accepted') {
                $relationship_status = 'friends';
            } elseif ($rel['status'] === 'pending') {
                if ($rel['sender_id'] == $userid) {
                    $relationship_status = 'sent';      // আমি পাঠিয়েছি
                } else {
                    $relationship_status = 'received';  // সে পাঠিয়েছে
                }
            } elseif ($rel['status'] === 'rejected') {
                $relationship_status = 'rejected';
            }
        }
        
        
        $sql1 = "
    SELECT id 
    FROM conversations 
    WHERE 
        (user_one = '$userid' AND user_two = '$friend_userid')
     OR (user_one = '$friend_userid' AND user_two = '$userid')
    LIMIT 1
";

$output1 = mysqli_query($con, $sql1);

$conversation_id = null;

if ($output1 && mysqli_num_rows($output1) > 0) {
    $row1 = mysqli_fetch_assoc($output1);
    $conversation_id = (int)$row1['id'];
}

        /* ===============================
           FINAL RESPONSE
        =================================*/
        $temp = [
            'id' => $row['id'],
            'userid' => $row['userid'],
            'name' => $row['name'],
            'image' => $url . $row['image'],
            'time' => $row['time'],
            'status' => $row['status'],
            'cover' => $url . $row['cover'],
            'bpay' => $row['bpay'],
            'address' => $row['address'],

            // Friend counts
            'pending_request_in' => (int)$pending_in,
            'accepted_out'       => (int)$accepted_out,
            'accepted_in'        => (int)$accepted_in,

            // ⭐ Relationship info
            'relationship_status' => $relationship_status,
            'conversation_id' => $conversation_id
        ];

        echo json_encode($temp, JSON_UNESCAPED_SLASHES);

    } else {
        echo json_encode(['error' => 'No data found']);
    }

    mysqli_close($con);

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

?>
