<?php

class SelfService_IndexController extends Am_Mvc_Controller
{
    /** User */
    protected $user = null;

    function  preDispatch()
    {
        $this->getDi()->auth->requireLogin();
        $this->user = $this->getDi()->auth->getUser();

        $this->view->headLink()->appendStylesheet($this->view->_scriptCss('self-service.css'));
    }

    function indexAction()
    {
        $type = $this->getDi()->selfserviceTypeTable->load($this->getParam('type_id'));
        $balance = $this->getDi()->selfserviceBalanceTable->balance($this->user, $type->pk());

        if ($this->getRequest()->isPost() &&
                $product = $this->getModule()->getProduct($this->getParam('product_id'), $type->pk())) {

            if ($balance < $product->credits) {
                throw new Am_Exception_InputError('User have not enough credits');
            }
            $balance = $this->getDi()->selfserviceHistoryTable->debit(
                    $this->user, $product->credits, $type->pk(), $product->title,
                    'product', $product->pk());

            $invoice = $this->getDi()->invoiceRecord;
            $invoice->setUser($this->user);
            $invoice->add($product);

            $begin_date = $product->calculateStartDate($this->getDi()->sqlDate, $invoice);
            $p = new Am_Period($product->getBillingPlan()->first_period);
            $expire_date = $p->addTo($begin_date);

            $access = $this->getDi()->accessRecord;
            $access->setForInsert([
                'user_id' => $this->user->pk(),
                'product_id' => $product->pk(),
                'qty' => 1,
                'begin_date' => $begin_date,
                'expire_date' => $expire_date,
                'comment' => sprintf('%s Self-Service Store (%d)', amDatetime($this->getDi()->sqlDateTime), $product->credits)
            ])->save();

            $this->getDi()->emailTemplateTable->sendZeroAutoresponders($this->user, $access);

            if ($this->getModule()->getConfig('product_added_admin')) {
                $et = Am_Mail_Template::load('self-service.product_added_admin');

                $et->setUser($this->user);
                $et->setProduct($product);

                $et->sendAdmin();
            }

            $url = $this->getDi()->hook->filter(
                $this->url('self-service/thanks', ['id' => $this->getDi()->security->obfuscate($access->pk())], false),
                Bootstrap_SelfService::EVENT_SELF_SERVICE_THANKS_REDIRECT,
                [
                    'access' => $access,
                    'product' => $product,
                    'user' => $this->user,
                ]
            );

            if ($url) {
                Am_Mvc_Response::redirectLocation($url);
            }
        }

        $this->view->type = $type;
        $this->view->balance = $balance;

        $products = $this->getModule()->getAvailableProducts($this->user, $type->pk(), $this->getParam('c'));
        $products = $this->getDi()->productTable->filterProducts(
                    $products,
                    $this->user->getActiveProductIds(),
                    $this->user->getExpiredProductIds(),
                    false);

        $perpage = $this->getModule()->getConfig('records_per_page', 10);

        $paginator = new Am_Paginator(ceil(count($products)/$perpage),
            $this->getRequest()->getParam('ssp', 0), null, 'ssp', $this->getRequest());

        $this->view->paginator = $paginator;
        $this->view->products = array_slice($products, $this->getRequest()->getParam('ssp', 0) * $perpage, $perpage);

        $this->view->display('self-service/index.phtml');
    }

    function thanksAction()
    {
        if (!$id = $this->getDi()->security->reveal($this->getRequest()->getParam('id'))) {
            throw new Am_Exception_InputError();
        }

        $access = $this->getDi()->accessTable->load($id);
        if ($access->user_id != $this->user->pk()) {
            throw new Am_Exception_InputError();
        }

        $this->view->product = $this->getDi()->productTable->load($access->product_id);
        $this->view->display('self-service/thanks.phtml');
    }

    function getLifetimeBalance(User $user, $type_id)
    {
        return  $this->getDi()->db->selectCell("
                SELECT SUM(value)
                FROM ?_selfservice_history WHERE user_id = ?d AND type_id=?d AND (expire IS NULL OR expire=?)
                GROUP BY user_id, type_id
        ", $user->pk(), $type_id, Am_Period::MAX_SQL_DATE);
    }

    function createTransferForm()
    {
        $type_id = $this->getParam('type_id');
        $user = $this->getDi()->auth->getUser();
        $balance = $this->getLifetimeBalance($user, $type_id);

        if ($balance == 0) {
            $form = new Am_Form();
            $form->addHtml()->setHtml(___('You have no credits to transfer'));
            return $form;
        }

        $form = new Am_Form();
        $text = ___('You have %s credits that could be transferred  to another user',
            "<strong>".$balance."</strong>");
        $form->addHTML()->setHTML(<<<CUT
$text
CUT
        );
        $gr = $form->addGroup();
        $gr->addButton('minus', ['id' => 'form-minus'])->setContent('-');
        $el = $gr->addText("amount", ['size'=>2, 'id'=> 'form-amount', 'placeholder' => 0]);

        $gr->addRule('callback2', null, function($v) use ($balance){
            if((intval($v['amount'])<=0) || (intval($v['amount'])>$balance))
                {
                    return ___('Amount is incorrect');
                }
            });

        $gr->addButton("plus", ['id' => 'form-plus'])->setContent('+');
        $gr->setLabel(___('Amount of Credits to Transfer'));
        $form->addText('username', ['class' => 'am-el-wide', 'id' => 'form-username'])->setLabel(___('Transfer Credits to'))
            ->addRule('required')
            ->addRule('callback2', null, function($value) use ($user)
            {
                $u = $this->getDi()->userTable->findFirstByLogin($value);
                if(empty($u)){
                    return ___('There is no user with such username');
                }
                if($u->pk() == $user->pk())
                {
                    return ___("You can't send credits to yourself");
                }

            });
        $form->addScript()->setScript(<<<JS
    jQuery(document).ready(function(){
        const balance = parseInt('{$balance}');
        jQuery("#form-minus").on('click', function(e){
            e.preventDefault();
            let val = jQuery("#form-amount").val();
            val = val ? parseInt(val) : 0;
            jQuery("#form-amount").val(val-1<0?0:val-1);
        });
        jQuery("#form-plus").on('click', function(e){
            e.preventDefault();
            let val = jQuery("#form-amount").val();
            val = val ? parseInt(val) : 0;
            jQuery("#form-amount").val(val+1>balance?balance:val+1);
        });
    });
JS
        );
        $btnGroup = $form->addGroup();
        $btnGroup->addSubmit('send', ['value' => ___('Send Credits')]);
        $cancelUrl = $this->getDi()->surl("self-service/index/index/type_id/{$type_id}");
        $btnGroup->addHTML()->setHTML("&nbsp;&nbsp;<a href='{$cancelUrl}'>cancel</a>");
        return $form;
    }

    function transferAction()
    {
        $form = $this->createTransferForm();
        if ($form->isSubmitted() && $form->validate())
        {
            $value = $form->getValue();
            $user = $this->getDi()->userTable->findFirstByLogin($value['username']);
            $amount = $value['amount'];
            /**
             * @var SelfserviceHistoryTable $historyTable
             */
            $historyTable = $this->getDi()->selfserviceHistoryTable;
            $historyTable->debit($this->getDi()->auth->getUser(), $amount, $this->getParam('type_id'), $_msg  = ___('%s credits were transferred  to user %s', $amount, $user->login));
            $historyTable->credit($user,  $amount, $this->getParam('type_id'), ___('%s credits were received  from user %s', $amount, $this->getDi()->auth->getUser()->login));
            $this->view->assign('msg', $_msg);
            if ($this->getModule()->getConfig('credits_received') && $et = Am_Mail_Template::load('self-service.credits_received'))
            {
                $et->setUser($user);
                $et->setSender($this->getDi()->auth->getUser()->login);
                $et->setAmount($amount);
                $et->send($user);
            }
        }
        $this->view->assign('form', $form);
        $this->view->display('self-service/transfer.phtml');
    }
}