<?php

use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

defined('VALID_INCLUDE') or exit('Restricted area');

function POHODA_getDataItemDetails($contactId = 0, $type, $status, $values = '')
{
    if ($contactId == 0) {
        $structItemDetails['dataItemId'] = '';
    } else {
        $structItemDetails['dataItemId'] = $contactId;
    }
    $structItemDetails['dataItemDetails'][0]['type'] = $type;
    $structItemDetails['dataItemDetails'][0]['status'] = $status;
    $structItemDetails['dataItemDetails'][0]['statusMessage'] = getTextString('errors', $status);

    if (!empty($values)) {
        $structItemDetails['dataItemDetails'][0]['valueRequested']['name'] = $values['requestedValueName'];
        $structItemDetails['dataItemDetails'][0]['valueRequested']['value'] = $values['requestedValue'];
        $structItemDetails['dataItemDetails'][0]['valueAssigned']['name'] = $values['assignedValueName'];
        $structItemDetails['dataItemDetails'][0]['valueAssigned']['value'] = $values['assignedValue'];
    }

    return $structItemDetails;
}

function POHODA_setDataItemValues($requestedValueName, $requestedValue, $assignedValueName, $assignedValue)
{
    $values['requestedValueName'] = $requestedValueName;
    $values['requestedValue'] = $requestedValue;
    $values['assignedValueName'] = $assignedValueName;
    $values['assignedValue'] = $assignedValue;

    return $values;
}

function updatePass($password, $id)
{
    $new_hash = password_hash($password, PASSWORD_BCRYPT);
    sqlQuery('UPDATE '.getTableName('admins')." SET password='{$new_hash}' WHERE id={$id}");

    return $new_hash;
}

function POHODA_login($params)
{
    global $cfg;

    $requestParams = $params['requestParams'];

    $session = ServiceContainer::getService('session');

    if (!empty($requestParams['userName']) && !empty($requestParams['userPassw'])) {
        // expirovane loginy znepristupnit
        sqlQuery('UPDATE '.getTableName('admins')." SET active='N' WHERE date_valid<>'' AND date_valid<=NOW()");

        $SQL = sqlQuery('SELECT id, password, OLD_PASSWORD(:password) AS passwGet
							FROM '.getTableName('admins')."
							WHERE login=:login AND active='Y'
							LIMIT 1", ['login' => $requestParams['userName'], 'password' => $requestParams['userPassw']]);
        if (sqlNumRows($SQL) == 1) {
            $log = sqlFetchArray($SQL);

            // --------------------------------------------------
            // data pro informaci o prihlaeni administratora

            // IP ADRESA
            $log['ip'] = '';
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $explode_ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $log['ip'] = $explode_ip[0];
            } else {
                $log['ip'] = $_SERVER['REMOTE_ADDR'];
            }

            // DOMENOVA ADRESA
            $log['ip_name'] = '';
            if (isset($_SERVER['REMOTE_HOST']) && $_SERVER['REMOTE_HOST'] != '') {
                $log['ip_name'] = $_SERVER['REMOTE_HOST'];
            } else {
                $log['ip_name'] = gethostbyaddr($log['ip']);
            }
            $log['ip_name'] = strtolower($log['ip_name']);
            // --------------------------------------------------

            $password = $requestParams['userPassw'];

            if ($log['passwGet'] == $log['password']) {
                $password = updatePass($password, $log['id']);
            }

            // porovnani zadaneho hesla
            if (password_verify($password, $log['password'])) {
                if (password_needs_rehash($log['password'], PASSWORD_BCRYPT)) {
                    updatePass($password, $log['id']);
                }

                $session->set('_logged', true);
                $session->set('_ctrlString', md5(getShopUniqueName().':'.getIP()));
                $session->set('_expiry', ceil(time() + 120));
                $session->set('_adminID', $log['id']);
                $session->set('_eshopID', $cfg['Program']['licence']['ID']);

                // --------------------------------------------------
                // ulozeni pristupu administratora
                sqlQuery('INSERT INTO '.getTableName('admins_accesses')." SET
							id_admin='".$log['id']."', date_access=NOW(), ip='".$log['ip']."', 
							ip_name='".$log['ip_name']."', login_status='OK' ");
                // --------------------------------------------------

                $response = [
                    'status' => 200,
                    'statusMessage' => getTextString('errors', 200),
                    'responseData' => [],
                ];

                $response['responseData']['sessionId'] = session_id();
            } // neplatne zadane heslo
            else {
                $error = 3;
                $session->set('_logged', false);
                $password = '';

                // --------------------------------------------------
                // ulozeni pristupu administratora
                sqlQuery('INSERT INTO '.getTableName('admins_accesses')." SET
							id_admin='".$log['id']."', date_access=NOW(), ip='".$log['ip']."', 
							ip_name='".$log['ip_name']."', login_status='PASSW' ");
                // --------------------------------------------------

                $response = [
                    'status' => 403,
                    'statusMessage' => getTextString('errors', 403).' - spatne heslo',
                ];
            }
        } // uzivatel nebyl vubec nalezen
        else {
            $error = 2;
            $session->set('_logged', false);
            $login = '';
            $password = '';

            $response = [
                'status' => 403,
                'statusMessage' => getTextString('errors', 403).' - uzivatel nebyl nalezen',
            ];
        }
    } else {
        $response = [
            'status' => 403,
            'statusMessage' => getTextString('errors', 403).' - prazdne prihlasovaci udaje',
        ];
    }

    $session->save();

    return new xmlrpcresp(php_xmlrpc_encode($response));
}

function POHODA_logout($params)
{
    $requestParams = $params['requestParams'];

    $session = ServiceContainer::getService('session');

    if (isset($requestParams['sessionId'])) {
        $session->set('_logged', false);
        $session->remove('_adminID');
        $session->remove('_ip');

        $response = [
            'status' => 200,
            'statusMessage' => getTextString('errors', 200),
        ];
    } else {
        $response = [
            'status' => 200,
            'statusMessage' => getTextString('errors', 200),
        ];
    }

    return new xmlrpcresp(php_xmlrpc_encode($response));
}

function POHODA_checkSession($sessionId)
{
    // tmp hotfix
    //    return true;

    if (!$sessionId) {
        return false;
    }

    $session = ServiceContainer::getService('session');

    if ($session->isStarted()) {
        $session->save();
    }

    $session->setId($sessionId);

    $ret = $session->start();

    // logError(__FILE__, __LINE__, session_id(), true);

    if ($session->get('_logged', false)) {
        return true;
    } else {
        return false;
    }
}

function POHODA_unauthorized($params = null)
{
    $response = [
        'status' => 403,
        'statusMessage' => getTextString('errors', 403),
        'requestedParams' => [],
        'responseData' => [],
    ];

    return new xmlrpcresp(php_xmlrpc_encode($response));
}
