<?php
declare(strict_types=1);

require_once __DIR__ . '/../system/bootstrap.php';
require_once __DIR__ . '/../system/auth.php';
require_once __DIR__ . '/../system/response.php';
require_once __DIR__ . '/../system/audit.php';

$user = require_auth($pdo);

if (!in_array($user['role_key'], ['super_admin','platform_admin','rsp_admin'], true)) {
    error_forbidden('Forbidden');
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $userId = (int)($_GET['user_id'] ?? 0);
    if ($userId <= 0) error_bad_request('Invalid user_id');

    $stmt = $pdo->prepare("
        SELECT platform, enabled
        FROM user_platform_access
        WHERE user_id = ?
    ");
    $stmt->execute([$userId]);

    $result = ['web' => true, 'mobile' => true];

    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $result[$row['platform']] = (bool)$row['enabled'];
    }

    success('Platform access loaded', $result);
}

if ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    if (!is_array($input)) error_bad_request('Invalid JSON');

    $userId = (int)($input['user_id'] ?? 0);
    if ($userId <= 0) error_bad_request('Invalid user_id');

    foreach (['web','mobile'] as $platform) {
        if (!array_key_exists($platform, $input)) continue;

        $enabled = $input[$platform] ? 1 : 0;

        $pdo->prepare("
            INSERT INTO user_platform_access (user_id, platform, enabled)
            VALUES (?, ?, ?)
            ON DUPLICATE KEY UPDATE enabled = VALUES(enabled)
        ")->execute([$userId, $platform, $enabled]);

        audit_log(
            $pdo,
            $user,
            'update',
            'user_platform_access',
            $userId,
            ['platform' => $platform, 'enabled' => $enabled]
        );
    }

    success('Platform access updated');
}

error_bad_request('Method not allowed');
