<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\User\UserServicesFactory;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

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

Guard::requireLogin();
Guard::requireAbilityOrForbidden(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_ADDRESS_BOOK_VIEW);

$buildAddressBookRedirect = static function (array $query): string {
    $params = [];
    $search = trim((string) ($query['search'] ?? ''));
    $tenants = trim((string) ($query['tenants'] ?? ''));
    $departments = trim((string) ($query['departments'] ?? ''));
    $roles = trim((string) ($query['roles'] ?? ''));
    $collectCustom = static function (array $source): array {
        $custom = [];
        foreach ($source as $rawKey => $rawValue) {
            $key = strtolower(trim((string) $rawKey));
            if ($key === '') {
                continue;
            }
            if (preg_match('/^cf_[a-f0-9-]{36}$/', $key)) {
                $value = trim((string) $rawValue);
                if ($value !== '') {
                    $custom[$key] = $value;
                }
                continue;
            }
            if (preg_match('/^cfm_[a-f0-9-]{36}$/', $key)) {
                $ids = array_values(array_filter(array_map(
                    'intval',
                    array_map('trim', explode(',', (string) $rawValue))
                ), static fn (int $id): bool => $id > 0));
                $ids = array_values(array_unique($ids));
                if ($ids) {
                    $custom[$key] = implode(',', $ids);
                }
                continue;
            }
            if (preg_match('/^cfd_[a-f0-9-]{36}_(from|to)$/', $key)) {
                $value = trim((string) $rawValue);
                if ($value !== '') {
                    $custom[$key] = $value;
                }
            }
        }
        ksort($custom, SORT_STRING);
        return $custom;
    };

    if ($search !== '') {
        $params['search'] = $search;
    }
    if ($tenants !== '') {
        $params['tenants'] = $tenants;
    }
    if ($departments !== '') {
        $params['departments'] = $departments;
    }
    if ($roles !== '') {
        $params['roles'] = $roles;
    }
    foreach ($collectCustom($query) as $customKey => $customValue) {
        $params[$customKey] = $customValue;
    }

    if (!$params) {
        return 'address-book';
    }
    return 'address-book?' . http_build_query($params);
};

$redirect = $buildAddressBookRedirect(requestInput()->bodyAll());
$errorBag = formErrors();
if ((requestInput()->method()) !== 'POST') {
    Router::redirect($redirect);
    return;
}

if (!Session::checkCsrfToken()) {
    $errorBag->addGlobal(t('Form expired, please try again'));
    flashFormErrors($errorBag, 'address-book', 'address_book_saved_filters');
    Router::redirect($redirect);
    return;
}

$userId = (int) ($session['user']['id'] ?? 0);
if ($userId <= 0) {
    Router::redirect('login');
    return;
}
$userSavedFilterService = (app(UserServicesFactory::class))->createUserSavedFilterService();

$name = trim((string) (requestInput()->bodyAll()['name'] ?? ''));
$result = $userSavedFilterService->saveAddressBookFilter($userId, $name, requestInput()->bodyAll());

if (!($result['ok'] ?? false)) {
    $error = (string) ($result['error'] ?? '');
    if ($error === 'name_required') {
        $errorBag->addGlobal(t('Filter name is required'));
    } elseif ($error === 'max_reached') {
        $errorBag->addGlobal(t('Maximum number of saved filters reached'));
    } else {
        $errorBag->addGlobal(t('Filter save failed'));
    }
    flashFormErrors($errorBag, 'address-book', 'address_book_saved_filter_save');
    Router::redirect($redirect);
    return;
}

$sessionStore->set('address_book_saved_filters', $userSavedFilterService->listForAddressBook($userId));
Flash::success(t('Filter saved'), 'address-book', 'address_book_saved_filter_saved');
Router::redirect($redirect);
