<?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);

if (!isset($jsonArray['userid']) || !isset($jsonArray['key'])) {
    echo json_encode(['error' => 'Invalid input']);
    exit;
}

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

$response = array();

$security_key = decrypData($key);

if ($security_key === false) {
    echo 'Invalid encryption data';
    exit;
}

if ($security_key == SECURITY_KEY_PLAIN) {
    
    $con = dbConnect();
    
    if (!$con) {
        echo json_encode(['error' => 'Database connection failed']);
        exit;
    }

    $noticeArray = array();
    $stmt = $con->prepare("SELECT * FROM notification_table WHERE userid = ? ORDER BY id DESC");
    $stmt->bind_param("s", $userid);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($item = $result->fetch_assoc()) {
        $noticeArray[] = array(
            'id' => $item['id'],
            'userid' => $item['userid'],
            'sender' => $item['sender'],
            'name' => $item['name'],
            'profile' => $item['profile'],
            'time' => $item['time'],
            'notice' => $item['notice'],
            'type' => $item['type'],
            'title' => $item['title'],
            'post_id' => $item['post_id']
        );
    }

    $response = array(
        'notice' => $noticeArray
    );

    echo json_encode($response, JSON_UNESCAPED_UNICODE);
}


?>
