<?php
include '../db_connect.php';

$userid = $_POST['userid'];
$name = $_POST['name'];
$profile = $_POST['profile'];
$time = $_POST['time'];
$title = $_POST['title'];
$sender = $_POST['sender'];
$notice = 'true';
$type = $_POST['type'];
$post_id = $_POST['post_id'];
$key = $_POST['key'];

$security_key = decrypData($key);

if ($security_key === 'Jobayer121415' && strlen($userid) > 0) {
    $con = dbConnect();

    // স্যানিটাইজ
    $userid  = mysqli_real_escape_string($con, $userid);
    $time    = mysqli_real_escape_string($con, $time);

    // ইউজারের টোকেন বের করা
    $tokenQuery = "SELECT token FROM singup_table WHERE id = '$userid'";
    $tokenResult = mysqli_query($con, $tokenQuery);

    if (mysqli_num_rows($tokenResult) > 0) {
        $tokenRow = mysqli_fetch_assoc($tokenResult);
        $token = $tokenRow['token'];
    } else {
        $token = '';
    }

    // আগে একই টাইমে নোটিফিকেশন দেওয়া হয়েছে কিনা চেক করা
    $checkQuery = "SELECT * FROM notification_table WHERE time = '$time' AND userid = '$userid'";
    $result = mysqli_query($con, $checkQuery);

    if (mysqli_num_rows($result) <= 0) {
        $sql = "INSERT INTO notification_table(userid, sender, name, profile, time, notice, type, title, post_id)
                VALUES ('$userid', '$sender', '$name', '$profile', '$time', '$notice', '$type', '$title', '$post_id')";
        if (mysqli_query($con, $sql)) {
            echo json_encode([
                "status" => "Successfully",
                "token" => $token
            ]);
        } else {
            echo json_encode([
                "status" => "Query Error: " . mysqli_error($con)
            ]);
        }
    } else {
        echo json_encode([
            "status" => "Notice already available!",
            "token" => $token
        ]);
    }

    mysqli_close($con);
}

function decrypData($text) {
    $decoded = base64_decode($text);
    return openssl_decrypt($decoded, 'AES-128-ECB', '0175526800812345', OPENSSL_RAW_DATA);
}
?>
