<?php

namespace Ministra\Admin\Controller;

use Ministra\Admin\Adapter\DataTableAdapter;
use Ministra\Admin\Repository\LicenseKeysRepository;
use Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\K131970f0a776522b1a53ba419cd5e32c;
use Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\cff05f9ec87d13db426b6be495c35612\c289e887452121479958f4918dfbb7d5;
use Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\cff05f9ec87d13db426b6be495c35612\f43aac94c61399fab94959a50d7a8abb5\n103be8efb8d7445a2a867195bbb22596;
use Ministra\Lib\SMACCode;
use Ministra\Lib\SMACCodeException;
use Ministra\Lib\SMACLicenseInvalidFormatException;
use Psr\Container\ContainerInterface;
use Silex\Application;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response as Response;
use Upload\File;
use Upload\Storage\FileSystem;
class LicenseKeysController extends \Ministra\Admin\Controller\BaseMinistraController
{
    protected $db;
    public function __construct(\Silex\Application $app)
    {
        parent::__construct($app, __CLASS__);
    }
    public function index()
    {
        if (empty($this->app['action_alias'])) {
            return $this->app->redirect($this->app['controller_alias'] . '/about-license-keys');
        }
        return $this->app['twig']->render($this->getTemplateName(__METHOD__));
    }
    public function about_license_keys()
    {
        return $this->app['twig']->render($this->getTemplateName(__METHOD__));
    }
    public function license_keys_list(\Ministra\Admin\Repository\LicenseKeysRepository $repository, \Psr\Container\ContainerInterface $container)
    {
        $attribute = $this->getDropdownAttribute();
        $this->checkDropdownAttribute($attribute);
        $this->app['dropdownAttribute'] = $attribute;
        $this->getCodeFilters();
        $container->set('allUserStatuses', [['id' => '1', 'title' => $this->setLocalization('Turned On')], ['id' => '2', 'title' => $this->setLocalization('Turned Off')]]);
        $container->set('allStatuses', [['id' => \Ministra\Lib\SMACCode::STATUS_NOT_ACTIVATED, 'title' => $this->setLocalization(\Ministra\Lib\SMACCode::STATUS_NOT_ACTIVATED)], ['id' => \Ministra\Lib\SMACCode::STATUS_ACTIVATED, 'title' => $this->setLocalization(\Ministra\Lib\SMACCode::STATUS_ACTIVATED)], ['id' => \Ministra\Lib\SMACCode::STATUS_MANUALLY_ENTERED, 'title' => $this->setLocalization(\Ministra\Lib\SMACCode::STATUS_MANUALLY_ENTERED)], ['id' => \Ministra\Lib\SMACCode::STATUS_BLOCKED, 'title' => $this->setLocalization('BlockedLicense')], ['id' => \Ministra\Lib\SMACCode::STATUS_RESERVED, 'title' => $this->setLocalization(\Ministra\Lib\SMACCode::STATUS_RESERVED)]]);
        $container->set('allKeyTypes', [['id' => '1,2', 'title' => $this->setLocalization('Standard')], ['id' => '3,4', 'title' => $this->setLocalization('Advanced')]]);
        $devices = $repository->findForFilters('device');
        $container->set('allDevices', \array_filter(\array_map(function ($row) {
            return !empty($row['device']) ? ['id' => $row['device'], 'title' => $row['device']] : false;
        }, !empty($devices) ? $devices : [])));
        return $this->app['twig']->render($this->getTemplateName(__METHOD__));
    }
    private function getDropdownAttribute()
    {
        $attribute = [['name' => 'key_id', 'title' => $this->setLocalization('ID'), 'checked' => false], ['name' => 'code', 'title' => $this->setLocalization('License key'), 'checked' => true], ['name' => 'key_type', 'title' => $this->setLocalization('Key type'), 'checked' => true], ['name' => 'count_clear_attempts', 'title' => $this->setLocalization('Remaining clearings'), 'searchable' => false, 'checked' => true], ['name' => 'expire_date', 'title' => $this->setLocalization('Key expiration date'), 'searchable' => false, 'checked' => true], ['name' => 'key_status', 'title' => $this->setLocalization('Status'), 'checked' => true], ['name' => 'user_id', 'title' => $this->setLocalization('User'), 'checked' => true], ['name' => 'device', 'title' => $this->setLocalization('Device type'), 'checked' => true], ['name' => 'last_active', 'title' => $this->setLocalization('User activity'), 'checked' => true], ['name' => 'action', 'title' => $this->setLocalization('Actions'), 'checked' => true, 'searchable' => false], ['name' => 'operations', 'title' => $this->setLocalization('Operations'), 'checked' => true, 'searchable' => true]];
        return $attribute;
    }
    private function getCodeFilters()
    {
        $filters = [];
        if (\array_key_exists('filters', $this->data)) {
            if (\array_key_exists('key_type', $this->data['filters']) && (string) $this->data['filters']['key_type'] !== '0') {
                $filters['SUBSTRING(`code`, 2, 1) IN' . ((string) $this->data['filters']['key_type'] == '1' ? '(1, 2)' : '(3, 4)') . ' AND 1 '] = '1';
            }
            if (\array_key_exists('request', $this->data['filters']) && (string) $this->data['filters']['request'] !== '0') {
                $filters['request'] = $this->data['filters']['request'];
            }
            if (\array_key_exists('status', $this->data['filters']) && (string) $this->data['filters']['status'] !== '0') {
                $const = \strtoupper($this->data['filters']['status']);
                $filters['status'] = \constant("SMACCode::STATUS_{$const}");
            }
            if (\array_key_exists('device', $this->data['filters']) && (string) $this->data['filters']['device'] !== '0') {
                $filters['device'] = \urlencode($this->data['filters']['device']);
            }
            $this->app['filters'] = $this->data['filters'];
        } else {
            $this->app['filters'] = [];
        }
        return $filters;
    }
    public function license_keys_list_json(\Symfony\Component\HttpFoundation\Request $request, \Ministra\Admin\Repository\LicenseKeysRepository $licenseRepository, \Ministra\Admin\Adapter\DataTableAdapter $dataTableAdapter, \Psr\Container\ContainerInterface $container, $local_use = false)
    {
        if (!$this->isAjax && $local_use === false) {
            $this->app->abort(404, $this->setLocalization('Page not found'));
        }
        $dataTableAdapter->setHavingColumns(['key_type'])->process();
        $data = $licenseRepository->getGridData(null, $dataTableAdapter);
        $response = ['data' => [], 'recordsTotal' => $data['total'], 'recordsFiltered' => $data['filter']];
        $response['data'] = \array_map(function ($row) {
            $row['status_flag'] = \strtolower(\str_replace(' ', '_', $row['key_status']));
            $row['added'] = \strtotime($row['added']) * ($this->isAjax ? 1000 : 1);
            $row['action'] = $row['key_status'] == \Ministra\Lib\SMACCode::STATUS_BLOCKED ? 'active' : 'block';
            if (\in_array($row['key_type'], [1, 2])) {
                $row['key_type'] = $this->setLocalization('Standard');
            } else {
                if (\in_array($row['key_type'], [3, 4])) {
                    $row['key_type'] = $this->setLocalization('Advanced');
                } else {
                    $row['key_type'] = $this->setLocalization('Invalid');
                }
            }
            $row['count_clear_attempts'] = $row['count_clear_attempts'] < 0 ? '-' : $row['count_clear_attempts'];
            $row['expire_date'] = $row['expire_date'] < 0 ? $this->setLocalization('Absent') : $row['expire_date'];
            $row['login'] = empty($row['login']) ? $row['user_id'] : $row['login'];
            $row['key_status'] = $row['key_status'] === \Ministra\Lib\SMACCode::STATUS_BLOCKED ? 'BlockedLicense' : $row['key_status'];
            $row['last_active'] = (int) $row['last_active'] > 0 ? $row['last_active'] : null;
            switch ($row['key_status']) {
                case \Ministra\Lib\SMACCode::STATUS_BLOCKED:
                    $row['action'] = 'active';
                    break;
                case \Ministra\Lib\SMACCode::STATUS_NOT_ACTIVATED:
                    $row['action'] = 'block';
                    break;
                case \Ministra\Lib\SMACCode::STATUS_RESERVED:
                    $row['action'] = 'reserved';
                    break;
                default:
                    $row['action'] = 'ignore';
            }
            $row['RowOrder'] = 'dTRow_' . $row['key_id'];
            return $row;
        }, $data['data']);
        $response['data'] = $this->setLocalization($response['data'], 'key_status');
        $error = '';
        if ($this->isAjax && !$local_use) {
            $response = $this->generateAjaxResponse($response);
            return new \Symfony\Component\HttpFoundation\JsonResponse($response, empty($error) ? 200 : 500);
        }
        return $response;
    }
    public function upload_key_file()
    {
        if (!$this->isAjax || $this->method != 'POST') {
            $this->app->abort(404, $this->setLocalization('Page not found'));
        }
        $data = [];
        $data['action'] = 'updateTableData';
        $data['data'] = [];
        $error = $this->setLocalization('Upload failed');
        $storage = new \Upload\Storage\FileSystem('/tmp', true);
        $file = new \Upload\File('files', $storage);
        try {
            $file->upload();
            $result = \Ministra\Lib\SMACCode::importFile($file->getNameWithExtension(), \file_get_contents($file->getPath() . '/' . $file->getNameWithExtension()));
            @\unlink($file->getPath() . '/' . $file->getNameWithExtension());
            if ($result !== false) {
                $data['msg'] = $this->setLocalization('License keys is imported ') . \Ministra\Lib\SMACCode::$countImported;
                $error = '';
            }
        } catch (\Ministra\Lib\SMACLicenseInvalidFormatException $e) {
            $data['msg'] = $this->setLocalization('Invalid format for next license keys') . ': ' . $e->getLicensesAsString();
        } catch (\Ministra\Lib\SMACCodeException $e) {
            $data['msg'] = $this->setLocalization($e->getMessage());
        } catch (\Exception $e) {
            $data['msg'] = $error = $e->getMessage();
        }
        $response = $this->generateAjaxResponse($data);
        return new \Symfony\Component\HttpFoundation\Response(\json_encode($response), empty($error) ? 200 : 500, ['Content-Type' => 'application/json; charset=UTF-8']);
    }
    public function toggle_key_status(\Symfony\Component\HttpFoundation\Request $request, \Ministra\Admin\Repository\LicenseKeysRepository $licenseKeysRepository)
    {
        $data = ['id' => [], 'action' => 'updateTableRow', 'data' => [], 'msg_list' => []];
        $ids = $request->get($request->get('group_key'), $request->get('id'));
        if ($idsData = \json_decode($ids)) {
            $ids = $idsData;
        }
        if (empty($ids)) {
            $this->app->abort(404, $this->setLocalization('Page not found'));
        }
        $action = $this->postData['action'] ?: $request->get('action');
        $licenses = $licenseKeysRepository->updateLicensesStatus($action, $ids);
        $retData = ['data' => $licenses, 'id' => [], 'additional' => []];
        foreach ($licenses as $license) {
            $result = false;
            if (isset($license['is_updated']) && $license['is_updated']) {
                $result = true;
                $retData['id'][$license['id']] = 1;
            } else {
                $retData['id'][$license['id']] = -1;
                $retData['additional']['action'] = 'JSErrorModalBox';
                if (empty($retData['additional']['msg'])) {
                    $retData['additional']['msg'] = $this->setLocalization('Not changed') . ' id:' . $license['id'];
                } else {
                    $retData['additional']['msg'] .= ', ' . $license['id'];
                }
            }
            $retData['msg_list'][$license['key_id']] = $this->groupMessageList($license['id'], $result, $this->updateMessageTemplate());
        }
        $result = \count($retData['id']);
        $data['id'] = \array_filter($retData['id']);
        $error = false;
        if (empty($retData['id'])) {
            $hasError = $result !== \count($retData['id']);
            if (!$hasError) {
                $error = $retData['msg'] = $error = $this->setLocalization('Nothing to do');
            } else {
                $error = $retData['msg'] = $this->setLocalization('Some errors found');
            }
        } else {
            $retData['data'] = $this->setLocalization($licenses['data'], 'status');
            $changed = \array_filter($data['id'], function ($val) {
                return $val !== -1;
            });
            $retData['id'] = \array_keys($retData['id']);
            if (!empty($changed)) {
                $msg_str = 'id: ' . \implode(', ', \array_keys($changed));
                $retData['msg'] = $this->setLocalization('Keys {updchid} has been updated', '', $msg_str, ['{updchid}' => $msg_str]);
            }
        }
        $response = $this->generateAjaxResponse($retData, $error);
        return new \Symfony\Component\HttpFoundation\Response(\json_encode($response), empty($error) ? 200 : 500, ['Content-Type' => 'application/json; charset=UTF-8']);
    }
    private function updateMessageTemplate()
    {
        return ['success' => ['status' => true, 'msg' => $this->setLocalization('Key id:{updid} updated')], 'failed' => ['status' => false, 'msg' => $this->setLocalization('Key id:{updid} not updated')], 'error' => ['status' => false, 'msg' => $this->setLocalization('Update key id:{updid} ended with an error')]];
    }
    public function check_license_keys(\Symfony\Component\HttpFoundation\Request $request, \Ministra\Admin\Repository\LicenseKeysRepository $licenseRepository, \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\cff05f9ec87d13db426b6be495c35612\c289e887452121479958f4918dfbb7d5 $clearKeyService)
    {
        return $this->clear_license_keys($request, $licenseRepository, $clearKeyService, true, 'Updated');
    }
    public function clear_license_keys(\Symfony\Component\HttpFoundation\Request $request, \Ministra\Admin\Repository\LicenseKeysRepository $licenseRepository, \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\cff05f9ec87d13db426b6be495c35612\c289e887452121479958f4918dfbb7d5 $clearKeyService, $onlyCheck = false, $clearMessage = 'Cleared')
    {
        if (!\Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\K131970f0a776522b1a53ba419cd5e32c::getSafe('util_operator_secret', null) || !\Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\K131970f0a776522b1a53ba419cd5e32c::getSafe('operator_key', null)) {
            $data = $this->generateAjaxResponse([], $this->setLocalization('Operator identifiers is empty. Set options util_operator_secret and operator_key in config.ini'));
            return new \Symfony\Component\HttpFoundation\JsonResponse($data, 400);
        }
        $licenses = \json_decode($request->get('ids'), true);
        if (!$licenses) {
            $data = $this->generateAjaxResponse([], $this->setLocalization('Empty list'));
            return new \Symfony\Component\HttpFoundation\JsonResponse($data, 400);
        }
        $invalidFormat = [];
        $denied = [];
        $licenses = $licenseRepository->getByPks($licenses);
        $licensesClearList = [];
        foreach ($licenses as $license) {
            if (!\preg_match("/[\\d][\\d]\\w{10}/", $license['code'])) {
                $invalidFormat[] = ['license' => $license['code'], 'id' => $license['id'], 'message' => $this->setLocalization('Error. License key belongs to other service provider.')];
                continue;
            }
            if (!\is_numeric($license['code'][1]) || $license['code'][1] % 2 !== 0) {
                $denied[] = ['license' => $license['code'], 'id' => $license['id'], 'message' => $this->setLocalization('Error. License key belongs to other service provider.')];
                continue;
            }
            $licensesClearList[] = ['license' => $license['code'], 'id' => $license['id']];
        }
        if (\count($licenses) === \count($denied) + \count($invalidFormat)) {
            $data = $this->generateAjaxResponse(['data' => [\Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\cff05f9ec87d13db426b6be495c35612\c289e887452121479958f4918dfbb7d5::eeea772284d31736714bcc299be7fade => $denied, \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\cff05f9ec87d13db426b6be495c35612\c289e887452121479958f4918dfbb7d5::U4f3e9a964de3e82443d485e81e85b169 => $invalidFormat]], $this->setLocalization('Error. License key belongs to other service provider.'));
            return new \Symfony\Component\HttpFoundation\JsonResponse($data, 200);
        }
        $clearKeyService->f80b9b66fd877d92e10c1f041e618aef1($licensesClearList);
        if ($onlyCheck) {
            $clearKeyService->f23a6648beadc7ecb64fd5ab8e34f8a6();
        }
        $data = $clearKeyService->clear();
        if (null === $data || !\is_array($data)) {
            $message = 'Something went wrong. Check your internet connection and try again later.';
            switch ($data) {
                case \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\cff05f9ec87d13db426b6be495c35612\f43aac94c61399fab94959a50d7a8abb5\n103be8efb8d7445a2a867195bbb22596::ab3305790e14467f120913d114635e16:
                    $message = '';
                    break;
                case \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\cff05f9ec87d13db426b6be495c35612\f43aac94c61399fab94959a50d7a8abb5\n103be8efb8d7445a2a867195bbb22596::ad4752330ce629ff94072b26b1a0793d:
                    $message = 'Connection server error';
                    break;
                case \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\cff05f9ec87d13db426b6be495c35612\f43aac94c61399fab94959a50d7a8abb5\n103be8efb8d7445a2a867195bbb22596::M77e0e01233c921db777495f217a14945:
                    $message = 'Connection to database failed';
                    break;
                case \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\cff05f9ec87d13db426b6be495c35612\f43aac94c61399fab94959a50d7a8abb5\n103be8efb8d7445a2a867195bbb22596::ee301cb832f7a01dbcf4552fb8b6f546:
                    $message = 'Incorrect operator key or secret phrase';
                    break;
                case \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\cff05f9ec87d13db426b6be495c35612\f43aac94c61399fab94959a50d7a8abb5\n103be8efb8d7445a2a867195bbb22596::m8de2b879ea3019ab8d0de6f6c8c5c87d:
                    $message = 'Empty';
                    break;
                case \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\cff05f9ec87d13db426b6be495c35612\f43aac94c61399fab94959a50d7a8abb5\n103be8efb8d7445a2a867195bbb22596::m360d022de88289575c306a3b4942f380:
                    $message = 'Server error. Try again later.';
                    break;
            }
            return new \Symfony\Component\HttpFoundation\JsonResponse($this->generateAjaxResponse([], $this->setLocalization($message)), 500);
        }
        $clearKeyService->H97fe1e34a192e63070f28183ab4f1138();
        return new \Symfony\Component\HttpFoundation\JsonResponse(['data' => [\Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\cff05f9ec87d13db426b6be495c35612\c289e887452121479958f4918dfbb7d5::eeea772284d31736714bcc299be7fade => \array_merge($denied, $this->addMessageForGroupLicenses($clearKeyService->f2e3f1d9e6a5c63666ebe3b1507c3747(), 'Error. License key belongs to other service provider.')), \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\cff05f9ec87d13db426b6be495c35612\c289e887452121479958f4918dfbb7d5::U4f3e9a964de3e82443d485e81e85b169 => $invalidFormat, \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\cff05f9ec87d13db426b6be495c35612\c289e887452121479958f4918dfbb7d5::aae01495f3a0e320ca37c0c612105237 => $this->addMessageForGroupLicenses($clearKeyService->s90f88a59e59c154fc0ed57296c8dfcd2(), $clearMessage), \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\cff05f9ec87d13db426b6be495c35612\c289e887452121479958f4918dfbb7d5::H81ca26346f382a6ba60e751aa93d1f14 => $this->addMessageForGroupLicenses($clearKeyService->m07ffdd8abe94ba0891cd8d9af652fdd0(), $onlyCheck ? $clearMessage : "Skipped. License key don't have assigned user."), \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\cff05f9ec87d13db426b6be495c35612\c289e887452121479958f4918dfbb7d5::v3f08595f6fb2f8f04f01f46da21fae79 => $this->addMessageForGroupLicenses($clearKeyService->m1a3e96f845f2dbdf5d8ca591ae1bb65b(), 'Error. Limit of clearings is exceeded.'), \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\cff05f9ec87d13db426b6be495c35612\c289e887452121479958f4918dfbb7d5::c28e496e76fd3ef2d45ab676c6484c5a => $this->addMessageForGroupLicenses($clearKeyService->n566a687084aa607527301e9c27521ee7(), 'Error. License key is expired.'), \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\cff05f9ec87d13db426b6be495c35612\c289e887452121479958f4918dfbb7d5::bed2b8eedf06a426abc60593d3247955 => $this->addMessageForGroupLicenses($clearKeyService->t5b991084081fe62c94dab3ffb947afde(), 'Error. License key is blocked.')]], 200);
    }
    private function addMessageForGroupLicenses($list, $message)
    {
        $newList = [];
        foreach ($list as $item) {
            $newList[] = ['message' => $this->setLocalization($message), 'id' => $item['id'], 'license' => $item['license']];
        }
        return $newList;
    }
    private function getCodesFields()
    {
        return ['id' => 'S_C.`id` as `id`', 'code' => 'S_C.`code` as `code`', 'key_type' => 'IF(SUBSTRING(S_C.`code`, 2, 1) IN (1, 2), 1, 2) as `key_type`', 'request' => 'S_C.`request` as `request`', 'added' => 'S_C.`added` as `added`', 'status' => 'S_C.`status` as `status`', 'user_id' => 'S_C.`user_id` as `user_id`', 'device' => 'S_C.`device` as `device`'];
    }
}
