<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\UserAuthorizationPolicy;
use MintyPHP\Service\User\UserAccessTemplateService;
use MintyPHP\Session;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();

if (!Session::checkCsrfToken()) {
    Router::json(['ok' => false, 'error' => 'csrf_expired']);
    return;
}

$action = strtolower(trim((string) ($action ?? '')));
$allowedActions = ['activate', 'deactivate', 'delete', 'send-access'];
if (!in_array($action, $allowedActions, true)) {
    Router::json(['ok' => false, 'error' => 'invalid_action']);
}

$raw = requestInput()->bodyAll()['uuids'] ?? '';
$uuids = [];
if (is_array($raw)) {
    $uuids = $raw;
} elseif (is_string($raw)) {
    $uuids = array_filter(array_map('trim', explode(',', $raw)));
}
$uuids = array_values(array_unique(array_filter($uuids)));
if (!$uuids) {
    Router::json(['ok' => false, 'error' => 'no_selection']);
}

$currentUserId = (int) ($session['user']['id'] ?? 0);
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$decision = $authorizationService->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_BULK, [
    'actor_user_id' => $currentUserId,
    'bulk_action' => $action,
]);
if (!$decision->isAllowed()) {
    http_response_code($decision->status());
    Router::json(['ok' => false, 'error' => $decision->error()]);
}

$userAccountService = app(\MintyPHP\Service\User\UserAccountService::class);
$mailService = app(\MintyPHP\Service\Mail\MailService::class);
$userAccessTemplateService = app(UserAccessTemplateService::class);

if ($action === 'activate') {
    $result = $userAccountService->setActiveByUuids($uuids, true, $currentUserId);
    if (!($result['ok'] ?? false)) {
        Router::json(['ok' => false, 'error' => 'update_failed']);
    }
    Router::json(['ok' => true, 'count' => (int) ($result['count'] ?? 0)]);
}

if ($action === 'deactivate') {
    if ($currentUserId > 0) {
        $currentUser = $userAccountService->findById($currentUserId);
        $currentUuid = $currentUser['uuid'] ?? '';
        if ($currentUuid !== '') {
            $uuids = array_values(array_filter($uuids, static fn ($uuid) => $uuid !== $currentUuid));
        }
        if (!$uuids) {
            Router::json(['ok' => false, 'error' => 'self_deactivate']);
        }
    }

    $result = $userAccountService->setActiveByUuids($uuids, false, $currentUserId);
    if (!($result['ok'] ?? false)) {
        Router::json(['ok' => false, 'error' => 'update_failed']);
    }
    Router::json(['ok' => true, 'count' => (int) ($result['count'] ?? 0)]);
}

if ($action === 'delete') {
    $result = $userAccountService->deleteByUuids($uuids, $currentUserId);
    if (!($result['ok'] ?? false)) {
        Router::json(['ok' => false, 'error' => $result['error'] ?? 'delete_failed']);
    }
    Router::json(['ok' => true, 'count' => (int) ($result['count'] ?? 0)]);
}

$successCount = 0;
$failedCount = 0;

foreach ($uuids as $uuid) {
    $user = $userAccountService->findByUuid($uuid);
    if (!$user || empty($user['email'])) {
        $failedCount++;
        continue;
    }

    $context = $userAccessTemplateService->buildContext($user);
    $locale = (string) ($context['locale'] ?? '');
    $subject = (string) ($context['subject'] ?? t('Your access details'));
    $vars = is_array($context['vars'] ?? null) ? $context['vars'] : [];

    $result = $mailService->sendTemplate('access_info', $vars, (string) $user['email'], $subject, $locale);
    if ($result['ok'] ?? false) {
        $successCount++;
    } else {
        $failedCount++;
    }
}

Router::json([
    'ok' => $successCount > 0,
    'count' => $successCount,
    'failed' => $failedCount,
]);
