<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo 'Access Denied';
    exit();
}

include 'config.php';

$checkTable = $conn->query("SHOW TABLES LIKE 'push'");
if ($checkTable->num_rows == 0) {
    $create = "CREATE TABLE push (id INT AUTO_INCREMENT PRIMARY KEY, title TEXT, message TEXT)";
    $conn->query($create);
} else {
    $existingCols = [];
    $res = $conn->query("SHOW COLUMNS FROM push");
    while ($r = $res->fetch_assoc()) { $existingCols[] = $r['Field']; }
    foreach (array('title', 'message') as $col) {
        if (!in_array($col, $existingCols)) {
            $conn->query("ALTER TABLE push ADD `$col` TEXT");
        }
    }
}

foreach(array('title', 'message') as $field) {
    if(!isset($_POST[$field]) || trim($_POST[$field]) == '') {
        echo $field . ' is required';
        exit();
    }
}

$sql = "INSERT INTO push (title, message) VALUES (?, ?)";

$stmt = $conn->prepare($sql);
if ($stmt) {
    $stmt->bind_param("ss", $_POST['title'], $_POST['message']);
    if ($stmt->execute()) {
        echo "Auto Push Notification Send Successful";
    } else {
        echo "Auto Push Notification Send Failed";
    }
    $stmt->close();
} else {
    echo "Auto Push Notification Send Failed";
}
$conn->close();
?>