<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type, Accept, X-MAINPP-Push-Secret');

function respond(int $status, array $payload): void
{
    http_response_code($status);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') respond(405, ['success' => false]);
$server_secret = trim((string) getenv('MAINPP_PUSH_SECRET'));
$push_config_path = __DIR__ . '/../config/push_config.php';
if ($server_secret === '' && is_file($push_config_path)) {
    $push_config = require $push_config_path;
    if (is_array($push_config)) {
        $server_secret = trim((string) ($push_config['push_secret'] ?? ''));
    }
}
$request_secret = trim((string) ($_SERVER['HTTP_X_MAINPP_PUSH_SECRET'] ?? ''));
if ($server_secret === '' || !hash_equals($server_secret, $request_secret)) {
    respond(403, ['success' => false, 'message' => 'Akses penghantaran push ditolak.']);
}

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/push_service.php';
$payload = json_decode(file_get_contents('php://input') ?: '', true);
if (!is_array($payload)) $payload = [];
$user_id = (int) ($payload['user_id'] ?? 0);
$title = trim((string) ($payload['title'] ?? ''));
$body = trim((string) ($payload['body'] ?? ''));
$data = is_array($payload['data'] ?? null) ? $payload['data'] : [];
if ($user_id <= 0 || $title === '' || $body === '') {
    respond(422, ['success' => false, 'message' => 'Maklumat notifikasi tidak lengkap.']);
}
respond(200, sendMainppPush($conn, $user_id, $title, $body, $data));
