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

    class pjAdminClients extends pjAdmin
    {
        public function beforeFilter()
        {
            parent::beforeFilter();

            $this->checkLogin();

            if (!$this->isAdmin() && !$this->isTutor()) {
                $this->set('status', 2);
            }
        }

        public function beforeRender()
        {
            parent::beforeRender();
                        
            $this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
            $this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
            $this->appendJs('pjAdminClients.js');
        }

        public function pjActionIndex()
        {
            $this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
        }

        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 (!$this->get('status')) {
                if (!empty($_POST)) {
                    $data = array();
                    if($this->isTutor())
                    {
                        $data['tutor_id'] = $this->getUserId();
                    }
                    $id = pjClientModel::factory()
                    ->setAttributes(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 = pjUserModel::factory()->where('role_id', 3)->orderBy("name ASC")->findAll()->getData();
                $this->set('tutor_arr', $tutor_arr);
            }
        }

        public function pjActionUpdate()
        {
            if (!$this->get('status')) {
                if (!empty($_POST)) {
                    pjClientModel::factory()->set('id', $_GET['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('pjUser', 't2.id=t1.tutor_id', 'left outer')
                ->find($_GET['id'])->getData();
                $this->set('client', $client);
                
                $tutor_arr = pjUserModel::factory()->where('role_id', 3)->orderBy("name ASC")->findAll()->getData();
                $this->set('tutor_arr', $tutor_arr);
            }
        }

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

            if (!empty($_GET['id'])) {
                $pjClientModel = pjClientModel::factory();
                $client = $pjClientModel->find($_GET['id'])->getData();
                if (!empty($client) && $pjClientModel->set('id', $client['id'])->erase()->getAffectedRows() == 1) {
                    pjClientUrlModel::factory()->reset()->where('client_id', $client['id'])->eraseAll();
                    pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Client have been deleted.'));
                }
            }
            else {
                pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing, empty or invalid parameters.'));
            }

            exit;
        }

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

            if (!empty($_POST['record'])) {
                $clients = pjClientModel::factory()->whereIn('id', $_POST['record'])->findAll()->getData();
                if (!empty($clients)) {
                    pjClientModel::factory()->reset()->whereIn('id', $_POST['record'])->eraseAll();
                    pjClientUrlModel::factory()->reset()->whereIn('client_id', $_POST['record'])->eraseAll();
                    pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Client(s) have been deleted.'));
                }
            }
            else {
                pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing, empty or invalid parameters.'));
            }

            exit;
        }

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

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

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

            if ($this->isXHR()) {
                $pjClientModel = pjClientModel::factory()
                ->join('pjUser', 't1.tutor_id = t2.id', 'left outer');
                if($this->isTutor())
                {
                    $pjClientModel->where('tutor_id', $this->getUserId());
                }
                if (!empty($_GET['q'])) {
                    $q = $pjClientModel->escapeString($_GET['q']);
                    $pjClientModel->where("(t1.email LIKE '%$q%' OR t1.username LIKE '%$q%')");
                }

                $column = 'email';
                $direction = 'ASC';
                if (isset($_GET['direction']) && isset($_GET['column']) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC'))) {
                    $column = $_GET['column'];
                    $direction = strtoupper($_GET['direction']);
                }

                $total = $pjClientModel->findCount()->getData();
                $rowCount = isset($_GET['rowCount']) && (int) $_GET['rowCount'] > 0 ? (int) $_GET['rowCount'] : 10;
                $pages = ceil($total / $rowCount);
                $page = isset($_GET['page']) && (int) $_GET['page'] > 0 ? intval($_GET['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()
        {
            if (!$this->get('status')) {
                $this->appendJs('tinymce.min.js', PJ_THIRD_PARTY_PATH . 'tinymce/');

                $client = pjClientModel::factory()->find($_GET['id'])->getData();
                $this->set('client', $client);

                if (!empty($_POST)) {
                    $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, $_POST['subject']);
                    $message = str_replace($search, $replace, $_POST['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);
            }
        }
    }