<?php

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

    if (!defined("ROOT_PATH")) {
        header("HTTP/1.1 403 Forbidden");
        exit;
    }

    class pjAdminClients extends pjAdmin
    {


        public function pjActionIndex()
        {

            $this->checkLogin();
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminClients.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
        }

        public function pjActionCreate()
        {
            $registrationEmail = pjMultiLangModel::factory()
                ->whereIn('field', array('client_subject_registration', 'client_tokens_registration'))
                ->where('model', 'pjCalendar')
                ->where('foreign_id', $this->getForeignId())
                ->where('locale', $this->getLocaleId())
                ->findAll()
                ->getDataPair('field', 'content');

                if (self::isPost() && $this->_post->toInt('client_create')){
                	$_POST = $this->_post->raw();
            
                    $data = array();
                    if($this->isTutor())
                    {
                        $data['tutor_id'] = $this->getUserId();
                    }

                    $id = pjClientModel::factory(array_merge($_POST, $data))->insert()->getInsertId();
                    
                    $Email = new pjEmail();
                    $Email->setContentType('text/html');
                    if ($this->option_arr['o_send_email'] == 'smtp') {
                        $Email
                            ->setTransport('smtp')
                            ->setSmtpHost($this->option_arr['o_smtp_host'])
                            ->setSmtpPort($this->option_arr['o_smtp_port'])
                            ->setSmtpUser($this->option_arr['o_smtp_user'])
                            ->setSmtpPass($this->option_arr['o_smtp_pass']);
                    }

                    $code = base64_encode(time() . '-' . $id);
                    pjClientUrlModel::factory()
                        ->setAttributes(array(
                            'client_id' => $id,
                            'code' => $code
                        ))
                        ->insert();

                    $url = $this->option_arr['o_install_url'] . '#!/Login/' . $code;
                    $search = array(
                        '{Username}',
                        '{Password}',
                        '{Email}',
                        '{Link}'
                    );

                    $replace = array(
                        pjSanitize::clean($_POST['username']),
                        pjSanitize::clean($_POST['password']),
                        pjSanitize::clean($_POST['email']),
                        sprintf('<a href="%1$s">%1$s</a>', $url)
                    );

                    $subject = str_replace($search, $replace, $registrationEmail['client_subject_registration']);
                    $message = str_replace($search, $replace, $registrationEmail['client_tokens_registration']);
                    if (!empty($subject) && !empty($message)) {
                        $message = pjUtil::textToHtml($message);
                        $Email
                            ->setTo($_POST['email'])
                            ->setFrom(pjAppController::getFromEmail())
                            ->setSubject($subject)
                            ->send($message);
                    }

                    pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminClients&action=pjActionIndex&err=AC03");
                }

                $tutor_arr = pjAuthUserModel::factory()->where('role_id', 5)->orderBy("name ASC")->findAll()->getData();
                $this->set('tutor_arr', $tutor_arr);

                $this->appendCss('awesome-bootstrap-checkbox.css', PJ_THIRD_PARTY_PATH . 'awesome_bootstrap_checkbox/');
            
                $this->appendCss('jasny-bootstrap.min.css', PJ_THIRD_PARTY_PATH . 'jasny/');
                $this->appendJs('jasny-bootstrap.min.js', PJ_THIRD_PARTY_PATH . 'jasny/');
                
                $this->appendCss('css/select2.min.css', PJ_THIRD_PARTY_PATH . 'select2/');
                $this->appendJs('js/select2.full.min.js', PJ_THIRD_PARTY_PATH . 'select2/');
                
                $this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
                $this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
                $this->appendJs('additional-methods.js', PJ_THIRD_PARTY_PATH . 'validate/');
                $this->appendJs('pjAdminClients.js');
            
        }

        public function pjActionUpdate()
        {
            
                if (self::isPost() && $this->_post->toInt('id')) {
                    $_POST = $this->_post->raw();

                    pjClientModel::factory()->set('id', $this->_post->toInt('id'))->modify($_POST);

                    pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminClients&action=pjActionIndex&id=".$_GET['id']."&err=AC01");
                }

                $client = pjClientModel::factory()
                ->select(sprintf("t1.*, AES_DECRYPT(t1.password, '%1\$s') AS `password`, t2.name AS tutor", PJ_SALT))
                ->join('pjAuthUser', 't2.id=t1.tutor_id', 'left outer')
                ->find($this->_get->toInt('id'))->getData();

                $this->set('client', $client);
                
                $tutor_arr = pjAuthUserModel::factory()->where('role_id', 5)->orderBy("name ASC")->findAll()->getData();
                $this->set('tutor_arr', $tutor_arr);

                $this->appendCss('awesome-bootstrap-checkbox.css', PJ_THIRD_PARTY_PATH . 'awesome_bootstrap_checkbox/');
            
                $this->appendCss('jasny-bootstrap.min.css', PJ_THIRD_PARTY_PATH . 'jasny/');
                $this->appendJs('jasny-bootstrap.min.js', PJ_THIRD_PARTY_PATH . 'jasny/');
                
                $this->appendCss('css/select2.min.css', PJ_THIRD_PARTY_PATH . 'select2/');
                $this->appendJs('js/select2.full.min.js', PJ_THIRD_PARTY_PATH . 'select2/');
                
                $this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
                $this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
                $this->appendJs('additional-methods.js', PJ_THIRD_PARTY_PATH . 'validate/');
                $this->appendJs('pjAdminClients.js');
            
        }


        public function pjActionDelete()
        {
            $this->setAjax(true);
        
            if (!$this->isXHR())
            {
                self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
            }
            
            if (!self::isPost())
            {
                self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'HTTP method not allowed.'));
            }

            if ($this->_get->check('id') && $this->_get->toInt('id') > 0)
            {
                $pjClientModel = pjClientModel::factory();
                $arr = $pjClientModel->find($this->_get->toInt('id'))->getData();
                if (!empty($arr) && $pjClientModel->setAttributes(array('id' => $arr['id']))->erase()->getAffectedRows() == 1)
                {
                    pjClientUrlModel::factory()->reset()->where('client_id', $this->_get->toInt('id'))->eraseAll();
                    
                    self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Client have been deleted.'));
                } else {
                    self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Client has not been deleted.'));
                }
            }
            
            self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing, empty or invalid parameters.'));
        }


        public function pjActionDeleteBulk()
        {
            $this->setAjax(true);
        
            if (!$this->isXHR())
            {
                self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
            }
            
            if (!self::isPost())
            {
                self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'HTTP method not allowed.'));
            }
            
            $record = $this->_post->toArray('record');
            if (count($record))
            {
                $pjClientModel = pjClientModel::factory();
                $arr = $pjClientModel->whereIn('id', $record)->findAll()->getData();
                
                $pjClientModel->reset()->whereIn('id', $record)->eraseAll();
                pjClientUrlModel::factory()->reset()->whereIn('client_id', $record)->eraseAll();
                
                self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Client(s) have been deleted.'));
            }
            exit;
        }


        public function pjActionCheckEmail()
        {
            $this->setAjax(true);
            if ($this->isXHR()) {
                $pjClientModel = pjClientModel::factory()->where('t1.email', $this->_get->toString('email'));
                if (!empty($this->_get->toInt('id'))) {
                    $pjClientModel->where('t1.id !=', $this->_get->toInt('id'));
                }

                echo $pjClientModel->findCount()->getData() == 0 ? 'true' : 'false';
            }
            exit;
        }

        public function pjActionGetJson()
        {
            $this->setAjax(true);

            if ($this->isXHR()) {
                $pjClientModel = pjClientModel::factory()
                ->join('pjAuthUser', 't1.tutor_id = t2.id', 'left outer');
                if($this->isTutor())
                {
                    $pjClientModel->where('tutor_id', $this->getUserId());
                }

                $get = $this->_get->raw();
                // if (!empty($_GET['q'])) {
                if($this->_get->check('q') && $get['q'] != ''){
                    $q = $pjClientModel->escapeString($this->_get->toString('q'));
                    $pjClientModel->where("(t1.email LIKE '%$q%' OR t1.username LIKE '%$q%')");
                }

                $column = 'email';
                $direction = 'ASC';
               
                if ($this->_get->check('column') && in_array(strtoupper($this->_get->toString('direction')), array('ASC', 'DESC'))){
                    $column = $this->_get->toString('column');
					$direction = strtoupper($this->_get->toString('direction'));
                }

                $total = $pjClientModel->findCount()->getData();
                $rowCount = $this->_get->toInt('rowCount') ? $this->_get->toInt('rowCount') : 10;
                $pages = ceil($total / $rowCount);
                $page = $this->_get->toInt('page') ? $this->_get->toInt('page') : 1;
                $offset = ((int) $page - 1) * $rowCount;
                if ($page > $pages) {
                    $page = $pages;
                }

                $data = $pjClientModel
                    ->select(sprintf("t1.*, AES_DECRYPT(t1.password, '%1\$s') AS `password`, t2.name AS tutor", PJ_SALT))
                    ->orderBy("$column $direction")
                    ->limit($rowCount, $offset)
                    ->findAll()
                    ->getData();
                foreach($data as $k => $v)
                {
                    $data[$k]['tutor'] = !empty($v['tutor']) ? $v['tutor'] : __('lblNA', true);
                }
                pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
            }
            exit;
        }

        public function pjActionSaveJson()
        {
            $this->setAjax(true);

            if ($this->isXHR()) {
                pjClientModel::factory()->set('id', $_GET['id'])->modify(array($_POST['column'] => $_POST['value']));
            }
            exit;
        }

        public function pjActionResend()
        {
                $this->appendCss('awesome-bootstrap-checkbox.css', PJ_THIRD_PARTY_PATH . 'awesome_bootstrap_checkbox/');
            
                $this->appendCss('jasny-bootstrap.min.css', PJ_THIRD_PARTY_PATH . 'jasny/');
                $this->appendJs('jasny-bootstrap.min.js', PJ_THIRD_PARTY_PATH . 'jasny/');
                
                $this->appendCss('css/select2.min.css', PJ_THIRD_PARTY_PATH . 'select2/');
                $this->appendJs('js/select2.full.min.js', PJ_THIRD_PARTY_PATH . 'select2/');
                
                $this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
                $this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
                $this->appendJs('additional-methods.js', PJ_THIRD_PARTY_PATH . 'validate/');
                $this->appendJs('pjAdminClients.js');
            
                $this->appendJs('tinymce.min.js', PJ_THIRD_PARTY_PATH . 'tinymce/');

                $client = pjClientModel::factory()->find($this->_get->toInt('id'))->getData();
                $this->set('client', $client);

                if (self::isPost()) {
                    $Email = new pjEmail();
                    $Email->setContentType('text/html');
                    if ($this->option_arr['o_send_email'] == 'smtp') {
                        $Email
                            ->setTransport('smtp')
                            ->setSmtpHost($this->option_arr['o_smtp_host'])
                            ->setSmtpPort($this->option_arr['o_smtp_port'])
                            ->setSmtpUser($this->option_arr['o_smtp_user'])
                            ->setSmtpPass($this->option_arr['o_smtp_pass']);
                    }

                    pjClientUrlModel::factory()
                        ->where('client_id', $client['id'])
                        ->modifyAll(array(
                            'expired' => 'T'
                        ));

                    $code = base64_encode(time() . '-' . $client['id']);
                    pjClientUrlModel::factory()
                        ->setAttributes(array(
                            'client_id' => $client['id'],
                            'code' => $code
                        ))
                        ->insert();

                    $url = $this->option_arr['o_install_url'] . '#!/Login/' . $code;
                    $search = array(
                        '{Username}',
                        '{Password}',
                        '{Email}',
                        '{Link}'
                    );
                    $replace = array(
                        pjSanitize::clean($client['username']),
                        pjSanitize::clean($client['password']),
                        pjSanitize::clean($client['email']),
                        sprintf('<a href="%1$s">%1$s</a>', $url)
                    );

                    $subject = str_replace($search, $replace, $this->_post->toString('subject');
                    $message = str_replace($search, $replace, $this->_post->toString('message');
                    if (!empty($subject) && !empty($message)) {
                        $message = pjUtil::textToHtml($message);
                        $Email
                            ->setTo($client['email'])
                            ->setFrom(pjAppController::getFromEmail())
                            ->setSubject($subject)
                            ->send($message);
                    }

                    pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminClients&action=pjActionIndex&err=AC05");
                }

                $registrationEmail = pjMultiLangModel::factory()
                    ->whereIn('field', array('client_subject_registration', 'client_tokens_registration'))
                    ->where('model', 'pjCalendar')
                    ->where('foreign_id', $this->getForeignId())
                    ->where('locale', $this->getLocaleId())
                    ->findAll()
                    ->getDataPair('field', 'content');
                $this->set('registrationEmail', $registrationEmail);
            
        }
    }