<?php

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

    class pjAdminExtras extends pjAdmin
    {
        public function pjActionIndex()
        {
            if (!$this->isAdmin()) {
                $this->set('status', 2);
            }
            else {
                $this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
                $this->appendJs('pjAdminExtras.js');
            }
        }

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

            if ($this->isXHR() && $this->isAdmin())
            {
                $pjExtraModel = pjExtraModel::factory();
                if (!empty($_GET['q'])) {
                    $q = pjObject::escapeString($_GET['q']);
                    $pjExtraModel->where('t1.name LIKE', "%$q%");;
                }

                if (!empty($_GET['status'])) {
                    $pjExtraModel->where('t1.status LIKE', pjObject::escapeString($_GET['status']));
                }

                $column = 'name';
                $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 = $pjExtraModel->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 = $pjExtraModel
                    ->select("t1.id, t1.name, t1.status")
                    ->orderBy("$column $direction")
                    ->limit($rowCount, $offset)
                    ->findAll()
                    ->getData();

                if (!empty($data)) {
                    foreach ($data as $key => $extra) {
                        $extra['price'] = pjUtil::formatCurrencySign($extra['price'], $this->option_arr['o_currency']);
                        $data[$key] = $extra;
                    }
                }

                pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
            }
            exit;
        }

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

            if ($this->isXHR() && $this->isAdmin()) {
                $pjExtraModel = pjExtraModel::factory();
                $pjExtraModel->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
            }
            exit;
        }

        public function pjActionCreate()
        {
            if (!$this->isAdmin()) {
                $this->set('status', 2);
            }
            else {
                if (!empty($_POST)) {
                    $pjExtraModel = pjExtraModel::factory();
                    $extraId = $pjExtraModel->setAttributes($_POST)->insert()->getInsertId();
                    if ($extraId > 0) {
                        if (!empty($_POST['options'])) {
                            foreach ($_POST['options'] as $extraOption) {
                                pjExtraOptionModel::factory()
                                    ->setAttributes(array(
                                        'extra_id' => $extraId,
                                        'name' => $extraOption['name'],
                                        'price' => $extraOption['price']
                                    ))
                                    ->insert();
                            }
                        }

                        $err = 'AEX03';
                    } else {
                        $err = 'AEX04';
                    }
                    pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminExtras&action=pjActionIndex&err=$err");
                }

                $this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
                $this->appendJs('pjAdminExtras.js');
            }
        }
        
        public function pjActionUpdate()
        {
            if (!$this->isAdmin()) {
                $this->set('status', 2);
            }
            else {
                if (!empty($_POST)) {
                    pjExtraModel::factory()
                        ->where('id', $_GET['id'])
                        ->modifyAll($_POST);

                    pjExtraOptionModel::factory()->reset()->where('extra_id', $_GET['id'])->eraseAll();
                    if (!empty($_POST['options'])) {
                        foreach ($_POST['options'] as $extraOption) {
                            pjExtraOptionModel::factory()
                                ->reset()
                                ->setAttributes(array(
                                    'extra_id' => $_GET['id'],
                                    'name' => $extraOption['name'],
                                    'price' => $extraOption['price']
                                ))
                                ->insert();
                        }
                    }

                    $err = 'AEX01';

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

                $extra = pjExtraModel::factory()->find($_GET['id'])->getData();
                $this->set('extra', $extra);
                
                $extraOptions = pjExtraOptionModel::factory()
                    ->where('extra_id', $extra['id'])
                    ->findAll()
                    ->getData();
                $this->set('extraOptions', $extraOptions);
                
                $this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
                $this->appendJs('pjAdminExtras.js');
            }
        }

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

            if ($this->isXHR() && $this->isAdmin())
            {
                if (isset($_GET['id']) && !in_array($_GET['id'], array(1, $this->getUserId())))
                {
                    if (pjExtraModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
                    {
                        pjExtraOptionModel::factory()->where('extra_id', $_GET['id'])->eraseAll();
                        pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Extra has been deleted.'));
                    } else {
                        pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Extra has not been deleted.'));
                    }
                } else {
                    pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Missing or invalid data.'));
                }
            }
            exit;
        }

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

            if ($this->isXHR() && $this->isAdmin())
            {
                if (isset($_POST['record']) && !empty($_POST['record']))
                {
                    pjExtraModel::factory()
                        ->whereIn('id', $_POST['record'])
                        ->eraseAll();

                    pjExtraOptionModel::factory()
                        ->whereIn('foreign_id', $_POST['record'])
                        ->eraseAll();
                    
                    pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Extra(s) has been deleted.'));
                }
                pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing or empty parameters.'));
            }
            exit;
        }

    }