<?php

include_once __DIR__ . '/../secrets.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];
$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/';
    $postArray = array();

    // Modified SQL query to handle both Profile and Page types
   $noticeSql = "
SELECT 
    mn.*,
    CASE 
        WHEN LENGTH(mn.sender_id) = 8 THEN s.name
        WHEN LENGTH(mn.sender_id) = 9 THEN pg.name
    END AS sender_name,
    CASE 
        WHEN LENGTH(mn.sender_id) = 8 THEN s.image
        WHEN LENGTH(mn.sender_id) = 9 THEN pg.image
    END AS sender_image,
    CASE 
        WHEN LENGTH(mn.sender_id) = 8 THEN s.bpay
        WHEN LENGTH(mn.sender_id) = 9 THEN pg.bpay
    END AS sender_bpay
FROM media_notice mn
LEFT JOIN signup s 
    ON LENGTH(mn.sender_id) = 8 AND mn.sender_id = s.userid
LEFT JOIN page_table pg 
    ON LENGTH(mn.sender_id) = 9 AND mn.sender_id = pg.userid
WHERE mn.user_id = ?
ORDER BY mn.time DESC
";

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

$noticeArray = [];

while ($row = $result->fetch_assoc()) {
    $noticeArray[] = [
        'id'          => $row['id'],
        'post_id'     => $row['post_id'],
        'sender_id'   => $row['sender_id'],
        'sender_name' => $row['sender_name'],
        'sender_image'=> $profileurl . $row['sender_image'],
        'sender_bpay' => $row['sender_bpay'],
        'type'        => $row['type'],
        'text'        => $row['text'],
        'time'        => $row['time']
    ];
}

$response[] = [
    'notice' => $noticeArray
];

echo json_encode($response, JSON_UNESCAPED_SLASHES);

}

?>