<?php

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

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

$userid = $data['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();
    $profileUrl = "https://app.bpluspro.xyz/social/";

    /* ===========================
       1️⃣ Pending Request List
       =========================== */
    $sql1 = "SELECT fr.id AS request_id, fr.time,
                   fr.sender_id,
                   s.name,
                   s.image, s.bpay, s.token
            FROM friends_request fr
            LEFT JOIN signup s ON fr.sender_id = s.userid
            WHERE fr.receiver_id = '$userid'
            AND fr.status = 'pending'";

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

    $requests = array();

    while($row = mysqli_fetch_assoc($result1)){
        $requests[] = array(
            'request_id' => $row['request_id'],
            'time' => $row['time'],
            'userid' => $row['sender_id'],
            'name' => $row['name'],
            'image' => $profileUrl . $row['image'],
            'bpay' => $row['bpay'],
            'token' => $row['token']
        );
    }

    mysqli_free_result($result1);


    /* ===========================
       2️⃣ Suggestion List (Not Sent)
       =========================== */
    $sql2 = "SELECT s.userid, s.name, s.image, s.bpay, s.token
             FROM signup s
             WHERE s.userid != '$userid'
             AND s.userid NOT IN (
                  SELECT fr.sender_id 
                  FROM friends_request fr 
                  WHERE fr.receiver_id = '$userid'
             )
             AND s.userid NOT IN (
                  SELECT fr.receiver_id 
                  FROM friends_request fr 
                  WHERE fr.sender_id = '$userid'
             )
             LIMIT 20";

    $result2 = mysqli_query($con, $sql2);

    $suggestions = array();

    while($row = mysqli_fetch_assoc($result2)){
        $suggestions[] = array(
            'userid' => $row['userid'],
            'name' => $row['name'],
            'image' => $profileUrl . $row['image'],
            'bpay' => $row['bpay'],
            'token' => $row['token']
        );
    }

    mysqli_free_result($result2);
    mysqli_close($con);


    /* ===========================
       Final JSON Format (Expected by Java)
       =========================== */
    $response = array(
        'requests'    => $requests,     // who sent request
        'suggestions' => $suggestions   // who did NOT send
    );

    echo json_encode($response, JSON_UNESCAPED_SLASHES);
}

?>
