<?php

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

/* ===============================
   READ INPUT
================================ */
$json = file_get_contents('php://input');
$jsonArray = json_decode($json, true);

if (!isset($jsonArray[0]['userid'], $jsonArray[0]['key'])) {
    echo json_encode([['status' => false, 'message' => 'Invalid request']]);
    exit;
}

$userid = $jsonArray[0]['userid'];
$key    = $jsonArray[0]['key'];

/* ===============================
   SECURITY CHECK
================================ */
$security_key = decrypData($key);

if ($security_key === false || $security_key != SECURITY_KEY_PLAIN) {
    echo json_encode([['status' => false, 'message' => 'Invalid security key']]);
    exit;
}

/* ===============================
   DB CONNECT
================================ */
$con = dbConnect();
$profileurl = 'https://app.bpluspro.xyz/social/';

/* ===============================
   CONVERSATION LIST
================================ */
$postArray = [];

$sql = "
SELECT 
    c.id AS conversation_id,
    CASE 
        WHEN c.user_one = '$userid' THEN c.user_two
        ELSE c.user_one
    END AS other_user,

    CASE 
        WHEN LENGTH(
            CASE 
                WHEN c.user_one = '$userid' THEN c.user_two
                ELSE c.user_one
            END
        ) = 8 THEN s.name
        ELSE p.name
    END AS name,

    CASE 
        WHEN LENGTH(
            CASE 
                WHEN c.user_one = '$userid' THEN c.user_two
                ELSE c.user_one
            END
        ) = 8 THEN s.image
        ELSE p.image
    END AS image,

    CASE 
        WHEN LENGTH(
            CASE 
                WHEN c.user_one = '$userid' THEN c.user_two
                ELSE c.user_one
            END
        ) = 8 THEN s.bpay
        ELSE p.bpay
    END AS bpay,

    CASE 
        WHEN LENGTH(
            CASE 
                WHEN c.user_one = '$userid' THEN c.user_two
                ELSE c.user_one
            END
        ) = 8 THEN 'Profile'
        ELSE 'Page'
    END AS account_type

FROM conversations c
LEFT JOIN signup s ON s.userid = (
    CASE WHEN c.user_one = '$userid' THEN c.user_two ELSE c.user_one END
)
LEFT JOIN page_table p ON p.userid = (
    CASE WHEN c.user_one = '$userid' THEN c.user_two ELSE c.user_one END
)
WHERE c.user_one = '$userid' OR c.user_two = '$userid'
ORDER BY c.id DESC
";

$result = mysqli_query($con, $sql);

while ($row = mysqli_fetch_assoc($result)) {
    $postArray[] = [
        'conversation_id' => (int)$row['conversation_id'],
        'userid'          => $row['other_user'],
        'name'            => $row['name'],
        'profile'         => $profileurl . $row['image'],
        'bpay'            => $row['bpay'],
        'account_type'    => $row['account_type']
    ];
}

/* ===============================
   ACCEPTED FRIEND LIST
================================ */
$requests = [];

$sql1 = "
SELECT fr.id AS request_id, fr.sender_id,
       s.name, s.image, s.bpay
FROM friends_request fr
LEFT JOIN signup s ON fr.sender_id = s.userid
WHERE fr.receiver_id = '$userid'
AND fr.status = 'accepted'
";

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

while ($row = mysqli_fetch_assoc($result1)) {

    $sender_id = $row['sender_id'];
    $conversation_id = null;

    $check = mysqli_query($con, "
        SELECT id FROM conversations
        WHERE (user_one='$userid' AND user_two='$sender_id')
           OR (user_one='$sender_id' AND user_two='$userid')
        LIMIT 1
    ");

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

    $requests[] = [
        'request_id'      => (int)$row['request_id'],
        'userid'          => $sender_id,
        'name'            => $row['name'],
        'image'           => $profileurl . $row['image'],
        'bpay'            => $row['bpay'],
        'conversation_id' => $conversation_id
    ];
}

/* ===============================
   FINAL RESPONSE
================================ */
echo json_encode([[
    'status' => true,
    'data'   => $postArray,
    'friend' => $requests
]], JSON_UNESCAPED_SLASHES);

?>
