<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Accept');

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'] ?? '') === 'OPTIONS') respond(204, []);
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    respond(405, ['success' => false, 'message' => 'Method tidak dibenarkan.']);
}

require_once __DIR__ . '/../db.php';
$payload = json_decode(file_get_contents('php://input') ?: '', true);
if (!is_array($payload)) $payload = $_POST;

$action = strtolower(trim((string) ($payload['action'] ?? 'register')));
$user_id = (int) ($payload['user_id'] ?? 0);
$token = trim((string) ($payload['token'] ?? ''));
$platform = substr(strtolower(trim((string) ($payload['platform'] ?? 'unknown'))), 0, 20);
$device_name = substr(trim((string) ($payload['device_name'] ?? '')), 0, 120);

if ($user_id <= 0) {
    respond(422, ['success' => false, 'message' => 'User ID tidak sah.']);
}

$user_stmt = mysqli_prepare($conn, "SELECT id FROM users WHERE id = ? AND status = 'approved' LIMIT 1");
mysqli_stmt_bind_param($user_stmt, 'i', $user_id);
mysqli_stmt_execute($user_stmt);
if (!mysqli_fetch_assoc(mysqli_stmt_get_result($user_stmt))) {
    respond(403, ['success' => false, 'message' => 'Akaun tidak dibenarkan.']);
}

if ($action === 'send' || $action === 'notify') {
    $title = trim((string) ($payload['title'] ?? 'Notifikasi'));
    $body = trim((string) ($payload['body'] ?? $payload['message'] ?? ''));
    $data = is_array($payload['data'] ?? null) ? $payload['data'] : [];
    $sender_id = (int) ($payload['sender_user_id'] ?? $payload['user_id'] ?? 0);
    $target_ids_raw = $payload['target_user_ids'] ?? $payload['recipient_ids'] ?? $payload['user_ids'] ?? [];
    if (!is_array($target_ids_raw)) {
        $target_ids_raw = [$payload['target_user_id'] ?? $payload['user_id'] ?? 0];
    }

    $target_ids = [];
    foreach ($target_ids_raw as $tid) {
        $id = (int) $tid;
        if ($id > 0 && $id !== $sender_id) {
            $target_ids[$id] = true;
        }
    }

    if (!empty($payload['notify_all_department']) && $sender_id > 0) {
        $dept_stmt = mysqli_prepare($conn, "SELECT id FROM users WHERE LOWER(TRIM(department)) = LOWER(TRIM((SELECT department FROM users WHERE id = ?))) AND id <> ? AND status = 'approved'");
        if ($dept_stmt) {
            mysqli_stmt_bind_param($dept_stmt, 'ii', $sender_id, $sender_id);
            mysqli_stmt_execute($dept_stmt);
            $res = mysqli_stmt_get_result($dept_stmt);
            if ($res) {
                while ($r = mysqli_fetch_assoc($res)) {
                    $target_ids[(int) $r['id']] = true;
                }
            }
        }
    }

    require_once __DIR__ . '/../includes/push_service.php';
    $sent = 0;
    $failed = 0;
    foreach (array_keys($target_ids) as $target_id) {
        $res = sendMainppPush($conn, (int) $target_id, $title, $body, $data);
        $sent += (int) ($res['sent'] ?? 0);
        $failed += (int) ($res['failed'] ?? 0);
    }

    respond(200, [
        'success' => true,
        'message' => "Notifikasi dihantar kepada $sent peranti.",
        'sent' => $sent,
        'failed' => $failed,
    ]);
}

if ($token === '' || strlen($token) > 512) {
    respond(422, ['success' => false, 'message' => 'Maklumat peranti tidak lengkap.']);
}

if ($action === 'unregister') {
    $stmt = mysqli_prepare($conn, 'UPDATE push_devices SET enabled = 0, updated_at = NOW() WHERE user_id = ? AND token = ?');
    mysqli_stmt_bind_param($stmt, 'is', $user_id, $token);
    mysqli_stmt_execute($stmt);
    respond(200, ['success' => true, 'message' => 'Peranti dinyahdaftar.']);
}

$stmt = mysqli_prepare(
    $conn,
    'INSERT INTO push_devices (user_id, token, platform, device_name, enabled, last_seen_at)
     VALUES (?, ?, ?, ?, 1, NOW())
     ON DUPLICATE KEY UPDATE user_id = VALUES(user_id), platform = VALUES(platform),
       device_name = VALUES(device_name), enabled = 1, last_seen_at = NOW(), updated_at = NOW()'
);
mysqli_stmt_bind_param($stmt, 'isss', $user_id, $token, $platform, $device_name);
if (!mysqli_stmt_execute($stmt)) {
    respond(500, ['success' => false, 'message' => 'Token notifikasi gagal disimpan.']);
}

respond(200, ['success' => true, 'message' => 'Peranti sedia menerima notifikasi.']);
