<?php

include_once __DIR__ . '/../secrets.php';
include '../db_connect.php';

$user_id     = $_POST['user_id'] ?? '';
$sender_id   = $_POST['sender_id'] ?? '';
$post_id     = $_POST['post_id'] ?? '';
$type        = $_POST['type'] ?? '';
$time        = $_POST['time'] ?? '';
$text        = $_POST['text'] ?? '';
$key        = $_POST['key'] ?? '';

$security_key = decrypData($key);

header('Content-Type: application/json'); // JSON রেসপন্স

if ($security_key === false) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid encryption data']);
    exit;
}

if ($security_key == SECURITY_KEY_PLAIN) {

    $con = dbConnect();

    $stmt = $con->prepare("SELECT id FROM media_notice WHERE post_id = ?");
    $stmt->bind_param("s", $post_id);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows === 0) {

        $stmt = $con->prepare("INSERT INTO media_notice (user_id, sender_id, post_id, type, time, text) 
                               VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssss", $user_id, $sender_id, $post_id, $type, $time, $text);

        if ($stmt->execute()) {
            echo json_encode(['status' => 'success',  'message' => 'Successful']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Database Error: ' . $stmt->error]);
        }

    } else {
        
      $sql = "UPDATE media_notice SET sender_id = '$sender_id', type = '$type', time = '$time', text = '$text' WHERE post_id = '$post_id'";

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

      if ($result) {
        echo json_encode(['status'=>'success','message'=>'Successfully']);
      } else {
        echo json_encode(['status'=>'error','message'=>'Query Error: ' . mysqli_error($con)]);
      }

    }

    $stmt->close();
    $con->close();
}
?>
