<?php
require __DIR__ . '/bootstrap.php';

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\Database;
use App\Core\Response;
use App\Core\Security;

$user = Auth::requireUser();
$pdo = Database::connection();
$input = request_input();
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$action = strtolower(trim((string)($input['action'] ?? ($method === 'GET' ? 'status' : 'register'))));

function pyrk_mobile_tokens_table_exists(PDO $pdo): bool
{
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'mobile_device_tokens'");
        $stmt->execute();
        return (int)$stmt->fetchColumn() > 0;
    } catch (Throwable) {
        return false;
    }
}

function pyrk_mobile_clean(string $value, int $max): string
{
    $value = trim(preg_replace('/[\x00-\x1F\x7F]/u', '', $value) ?? '');
    return function_exists('mb_substr') ? mb_substr($value, 0, $max, 'UTF-8') : substr($value, 0, $max);
}

if (!pyrk_mobile_tokens_table_exists($pdo)) {
    Response::error('Native mobile token table is not installed. Run database/migrations/040_native_mobile_features.sql.', 503);
}

if ($method === 'GET' && $action === 'status') {
    $stmt = $pdo->prepare('SELECT platform, COUNT(*) AS device_count, MAX(last_seen_at) AS last_seen_at FROM mobile_device_tokens WHERE user_id = ? AND is_active = 1 GROUP BY platform ORDER BY platform');
    $stmt->execute([(int)$user['id']]);
    $devices = $stmt->fetchAll(PDO::FETCH_ASSOC);
    Response::ok([
        'registered' => count($devices) > 0,
        'devices' => $devices,
    ]);
}

if ($method !== 'POST') {
    Response::error('Method not allowed.', 405);
}
Csrf::validateFromRequest();

$token = pyrk_mobile_clean((string)($input['token'] ?? ''), 512);
if ($token === '' || strlen($token) < 20) {
    Response::error('A valid phone push token is required.');
}

if ($action === 'register') {
    $platform = strtolower(pyrk_mobile_clean((string)($input['platform'] ?? 'unknown'), 20));
    if (!in_array($platform, ['android', 'ios', 'web', 'unknown'], true)) $platform = 'unknown';

    $deviceId = pyrk_mobile_clean((string)($input['device_id'] ?? ''), 191);
    $appVersion = pyrk_mobile_clean((string)($input['app_version'] ?? ''), 50);
    $model = pyrk_mobile_clean((string)($input['model'] ?? ''), 120);
    $osVersion = pyrk_mobile_clean((string)($input['os_version'] ?? ''), 80);

    $stmt = $pdo->prepare('INSERT INTO mobile_device_tokens
        (user_id, push_token, platform, device_id, app_version, model, os_version, is_active, last_seen_at, created_at, updated_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, 1, NOW(), NOW(), NOW())
        ON DUPLICATE KEY UPDATE
            user_id = VALUES(user_id), platform = VALUES(platform), device_id = VALUES(device_id),
            app_version = VALUES(app_version), model = VALUES(model), os_version = VALUES(os_version),
            is_active = 1, last_seen_at = NOW(), updated_at = NOW()');
    $stmt->execute([(int)$user['id'], $token, $platform, $deviceId ?: null, $appVersion ?: null, $model ?: null, $osVersion ?: null]);

    try {
        Security::audit((int)$user['id'], 'native_device_registered', 'mobile_device_tokens', null, [
            'platform' => $platform,
            'device_id' => $deviceId ?: null,
            'app_version' => $appVersion ?: null,
        ]);
    } catch (Throwable) {
        // Audit must not interrupt device registration.
    }

    Response::ok(['platform' => $platform], 'This phone is registered for Pyrk push notifications.');
}

if ($action === 'unregister') {
    $stmt = $pdo->prepare('UPDATE mobile_device_tokens SET is_active = 0, updated_at = NOW() WHERE user_id = ? AND push_token = ?');
    $stmt->execute([(int)$user['id'], $token]);
    Response::ok([], 'This phone was unregistered from Pyrk push notifications.');
}

Response::error('Unsupported mobile device action.', 404);
