<?php

$main_class = 'AdminEdit';

class AdminEdit extends Window
{
    protected $tableName = 'admins';

    public function handleUpdate()
    {
        if (getVal('Submit')) {
            $data = $this->getData();
            global $adminID;
            $admPassOld = $data['admPassOld'];
            $admPass1 = $data['admPass1'];
            $admPass2 = $data['admPass2'];
            $error = 0;
            // nova hesla se musi rovnat
            if ($admPass1 != $admPass2) {
                $error = 1;
                // Zadané heslo a kontrolní heslo se neshodují
                $ErrStr = translate('errorPasswNotEqual');
            }

            if (strlen($admPass1) < 6) {
                $error = 15;
                $ErrStr = translate('errorPasswLength');
            }

            // kontrola puvodniho hesla
            $qb = sqlQueryBuilder()->select('id', 'login', 'password', 'OLD_PASSWORD(:admPassOld) AS passwGet')
                ->from('admins')
                ->where(\Query\Operator::equals(['id' => $adminID]))
                ->setParameter('admPassOld', $admPassOld)
                ->setMaxResults(1)
                ->execute();

            if ($qb->rowCount() == 1) {
                $log = $qb->fetch();
                $admName = $log['login'];
                if (($log['passwGet'] != $log['password']) && (password_verify($admPassOld, $log['password']) == false)) {
                    $error = 1;
                    // Zadané současné heslo není správné
                    $ErrStr = translate('errorBadPassw');
                }
            }

            if ($error == 0) {
                $new_hash = password_hash($admPass1, PASSWORD_BCRYPT);

                if ($this->updateSQL('admins', ['password' => $new_hash], ['id' => $adminID])) {
                    $ErrStr = urlencode(sprintf(translate('activityPasswEdited'), $admName));
                    writeDownActivity(sprintf(translate('activityPasswEdited'), $admName));
                } else {
                    $ErrStr = translate('scripterror', 'status');
                }
                redirect('launch.php?s=adminEdit.php&acn=passw&ErrStr='.$ErrStr);
            } else {
                redirect('launch.php?s=adminEdit.php&acn=passw&ErrStr='.urlencode($ErrStr));
            }
        }

        return parent::handleUpdate();
    }

    public function getData()
    {
        $data = parent::getData();

        $data['email'] = getAdminUser()['email'];

        return $data;
    }

    protected function getID()
    {
        return getAdminUser()['id'];
    }

    protected function getAction()
    {
        return 'edit';
    }
}
