<?php

class Am_Grid_Filter_License extends Am_Grid_Filter_Abstract
{
    protected $varList = array('filter', 'dat1', 'dat2');
    protected $filterMap = array(
        'u' => array('login', 'name_f', 'name_l', 'email'),
        'i' => array('public_id'),
        't' => array('key'),
        'a' => array('request')
    );

    public function __construct()
    {
        $this->attributes = array(
            'placeholder' => ___('Invoice/User/License/Bindings')
        );
        return parent::__construct();
    }

    protected function applyFilter()
    {
        class_exists('Am_Form', true);

        if ($filter = $this->getParam('filter')) {
            foreach ($this->filterMap as $alias => $fields) {
                foreach ($fields as $field) {
                    $c = new Am_Query_Condition_Field($field, 'LIKE', '%' . $filter . '%', $alias);
                    if (!isset($condition)) {
                        $condition = $c;
                    } else {
                        $condition->_or($c);
                    }
                }
            }
            $this->grid->getDataSource()->getDataSourceQuery()
                ->add($condition);
        }
        if ($dat1 = $this->getParam('dat1')) {
            $this->grid->getDataSource()->getDataSourceQuery()
                ->addWhere("t.expires >= ?", Am_Form_Element_Date::convertReadableToSQL($dat1) . ' 00:00:00');
        }
        if ($dat2 = $this->getParam('dat2')) {
            $this->grid->getDataSource()->getDataSourceQuery()
                ->addWhere("t.expires <= ?", Am_Form_Element_Date::convertReadableToSQL($dat2) . ' 23:59:59');
        }
    }

    function renderInputs()
    {
        $prefix = $this->grid->getId();

        $dat1 = Am_Html::escape($this->getParam('dat1'));
        $dat2 = Am_Html::escape($this->getParam('dat2'));

        $start = ___('Start Date');
        $end = ___('End Date');

        return $this->renderInputText('filter') .
            " " . ___('Expires') . <<<CUT
            <input type="text" placeholder="$start" name="{$prefix}_dat1" class="datepicker" style="width:80px" value="{$dat1}" />
            <input type="text" placeholder="$end" name="{$prefix}_dat2" class="datepicker" style="width:80px" value="{$dat2}" />
CUT;
    }

    function getTitle()
    {
        return '';
    }
}

class Softsale_AdminLicenseController extends Am_Mvc_Controller_Grid
{
    public function checkAdminPermissions(Admin $admin)
    {
        return $admin->hasPermission(Bootstrap_Softsale::ADMIN_PERM_ID);
    }

    public function cardAction()
    {
        $licenses = $this->getDi()->licenseTable->findByInvoiceId($this->getParam('id'));
        $out = '';
        foreach ($licenses as $l)
        {
            $out .= "<strong>{$l->key}</strong> {$l->getScheme()->title}<br />";
        }
        echo $out;
    }

    public function userAction()
    {
        $user_id = $this->getInt('user_id');
        $grid = $this->createGrid();
        $grid->getDataSource()->addWhere('t.user_id=?', $user_id);
        $grid->removeField('login');
        $grid->runWithLayout('admin/user-layout.phtml');
    }

    public function createGrid()
    {
        $ds = new Am_Query($this->getDi()->licenseTable);
        $ds->leftJoin('?_user', 'u', 'u.user_id=t.user_id');
        $ds->leftJoin('?_softsale_license_scheme', 's', 's.scheme_id=t.scheme_id');
        $ds->leftJoin('?_invoice', 'i', 'i.invoice_id=t.invoice_id');
        $ds->leftJoin('?_softsale_license_activation', 'a', 'a.license_id=t.license_id');
        $ds->addField('u.login', 'login');
        $ds->addField('s.title', 'scheme');
        $ds->addField('i.invoice_id', 'invoice_invoice_id');
        $ds->addField("CONCAT(t.invoice_id, '/', IFNULL(i.public_id, ''))", 'invoice_num');
        $ds->addField('COUNT(a.license_activation_id)', 'activations_count');
        $grid = new Am_Grid_Editable('_license', 'Licenses', $ds, $this->_request, $this->view);
        $grid->setForm(array($this, 'createForm'));

        $grid->addField('login', ___('Username'))->addDecorator(
            new Am_Grid_Field_Decorator_Link('admin-users?_u_a=edit&_u_b={THIS_URL}&_u_id={user_id}'));
        $grid->addField('invoice_num', ___('Invoice'))
            ->setRenderFunction(function($r, $f, $g) {
                if (!$r->invoice_invoice_id) {
                    return $g->renderTd('&mdash;', false);
                } else {
                    $url = $this->getDi()->url("admin-user-payments/index/user_id/{$r->user_id}#invoice-{$r->invoice_id}");
                    return $g->renderTd(sprintf('<a href="%s" target="_top">%s</a>',
                        $url, $g->escape($r->invoice_num)), false);
                }

            });
        $grid->addField('scheme', 'Scheme')->addDecorator(
            new Am_Grid_Field_Decorator_Link('softsale/admin-scheme?_schemes_a=edit&_schemes_b={THIS_URL}&_schemes_id={scheme_id}'));
        $grid->addField('key', ___('License Key'));
        $grid->addField(new Am_Grid_Field_Date('expires', ___('Expires')))
            ->setFormatDate();
        $grid->addField('activations_count', ___('Activations'))
            ->setRenderFunction(function($r, $f, $g) {
                return $g->renderTd(sprintf('<span id="softsalelicense-%d-cnt">%d</span>',
                    $r->pk(), $r->$f), false);
            })->addDecorator(
            new Am_Grid_Field_Decorator_DetailGrid('softsale/admin-license/activations/license_id/{license_id}', 'Activations')
            );

        $grid->actionDelete('insert');
        $grid->actionDelete('delete');

        $grid->setFilter(new Am_Grid_Filter_License);

        $grid->addCallback(Am_Grid_ReadOnly::CB_TR_ATTRIBS,
                array($this, 'getTrAttribs'));
        $grid->addCallback(Am_Grid_Editable::CB_RENDER_STATIC,
                array($this, 'renderStatic'));
        $grid->setPermissionId(Bootstrap_Softsale::ADMIN_PERM_ID);

        $grid->actionAdd(new Am_Grid_Action_Export);
        return $grid;
    }

    public function getTrAttribs(& $ret, $record)
    {
        if ($record->is_disabled) {
            $ret['class'] = isset($ret['class']) ? $ret['class'] . ' disabled' : 'disabled';
        }
    }

    public function activationsAction()
    {
        $id = (int)$this->getParam('license_id');
        if (!$id) throw new Am_Exception_InputError('Empty id passed to ' . __METHOD__);

        $license = $this->getDi()->licenseTable->load($id);
        $this->view->license = $license;
        $this->view->activations = $license->getActivations();
        $this->view->display('admin/softsale/_activations.phtml');
    }

    public function addActivationAction()
    {
        $id = (int)$this->getParam('license_id');
        if (!$id) throw new Am_Exception_InputError('Empty id passed to ' . __METHOD__);
        $license = $this->getDi()->licenseTable->load($id);
        /* @var $license License */
        $response = $license->activate((array)$this->getParam('request'));
        if ($response->isValid())
        {
            return $this->activationsAction();
        } else {
            $ret = array('ok' => false, 'message' => $response->getMessage());
            $this->_response->ajaxResponse($ret);
        }
    }

    public function disableActivationAction()
    {
        $id = (int)$this->getParam('license_id');
        if (!$id) throw new Am_Exception_InputError('Empty id passed to ' . __METHOD__);
        $license = $this->getDi()->licenseTable->load($id);
        /* @var $license License */
        $aid = (int)$this->getParam('license_activation_id');
        if (!$aid) throw new Am_Exception_InputError('Empty aid passed to ' . __METHOD__);
        $licenseActivation = $this->getDi()->licenseActivationTable->load($aid);
        $licenseActivation->disable();
        return $this->activationsAction();
    }

    public function createForm()
    {
        $form = new Am_Form_Admin;

        $form->addText('key', array('class' => 'am-el-wide'))
            ->setLabel(___('License Key'));
        $form->addDateTime('expires')
            ->setLabel(___('Expires'));
        $form->addText('info', array('class' => 'am-el-wide'))
            ->setLabel(___('License Info'));
        $form->addAdvCheckbox('is_disabled')
            ->setLabel(___('Is Disabled?'));

        return $form;
    }

    public function renderStatic(& $out, $grid)
    {
        $out .= <<<CUT
<script type="text/javascript">
jQuery(function($){
    jQuery(document).on('click',".add-activation-button", function(event){
       var input = jQuery(this).closest("tr").find(":input").serializeArray();
       jQuery("#activation-message").hide();
       var url = amUrl('/softsale/admin-license/add-activation', 1);
       jQuery.post(
           url[0],
           jQuery.merge(input, url[1]),
           function(data, textStatus){
                if (data.message)
                    jQuery("#activation-message").text("Activation error: " + data.message).slideDown();
                else {
                    jQuery(".grid-detail-dialog").html(data);
                }
           }
       );
       return false;
    });
    jQuery(document).on('click',".activation-disable", function(event){
       jQuery.get(this.href,
           function(data, textStatus){
                if (data.message)
                    jQuery("#activation-message").text("Cannot disable: " + data.message).slideDown();
                else {
                    jQuery(".grid-detail-dialog").html(data);
                }
           }
       );
       return false;
    });
});
</script>
<style type="text/css">
.div-flash-message  {
  width: 350px;
  margin-left: auto; margin-right: auto;
  padding: 1em;
  font-size: 12px;
  color: #454430;
  background: #ffffcf;
  border: solid 3px #545454;
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
  border-radius: 3px;
  margin-bottom: 0.2em;
}
</style>
CUT;
    }
}