<file_sep><?php

namespace Mebel\Model;

class Transaction
{
    public $id;
    public $type;
    public $description;
    public $material;
    public $quantity;
    public $sum;
    public $tarif;
    public $isWholesale;
    public $isIncome;

    public function exchangeArray($data)
    {
        $this->id = (!is_null($data['id'])) ? $data['id'] : null;
        $this->type = (!is_null($data['type'])) ? $data['type'] : null;
        $this->description = (!is_null($data['description'])) ? $data['description'] : null;
        $this->material = (!is_null($data['material'])) ? $data['material'] : null;
        $this->quantity = (!is_null($data['quantity'])) ? $data['quantity'] : null;
        $this->sum = (!empty($data['sum'])) ? $data['sum'] : 0;
        $this->tarif = (!empty($data['tarif'])) ? $data['tarif'] : 0;
        $this->isWholesale = (!is_null($data['isWholesale'])) ? $data['isWholesale'] : null;
        $this->isIncome = (!is_null($data['isIncome'])) ? $data['isIncome'] : null;
    }

    public function getArrayCopy()
    {
        return get_object_vars($this);
    }


}<file_sep><?php

namespace Mebel\Model;

class Worker
{
    public $id;
    public $fio;
    public $description;
    public $phone;
    public $address;

    public function exchangeArray($data)
    {
        $this->id = (!is_null($data['id'])) ? $data['id'] : null;
        $this->fio = (!is_null($data['fio'])) ? $data['fio'] : null;
        $this->description = (!is_null($data['description'])) ? $data['description'] : null;
        $this->phone = (!is_null($data['phone'])) ? $data['phone'] : null;
        $this->address = (!is_null($data['address'])) ? $data['address'] : null;
    }

    public function getArrayCopy()
    {
        return get_object_vars($this);
    }


}<file_sep>CREATE TABLE `material` (
  `id`          INT(10) UNSIGNED NOT NULL         AUTO_INCREMENT,
  `type`        VARCHAR(50)      NOT NULL,
  `name`        VARCHAR(255)                      DEFAULT NULL,
  `description` TEXT,
  `wholesale`   FLOAT            NOT NULL         DEFAULT 0,
  `retail`      FLOAT            NOT NULL         DEFAULT 0,
  `count`       INT(11)          NOT NULL         DEFAULT 0,
  `image`       VARCHAR(255)                      DEFAULT NULL,
  `date`        TIMESTAMP         NOT NULL         DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
)
  ENGINE = InnoDB
  DEFAULT CHARSET = utf8<file_sep><?php

namespace Mebel\Model;

class Rate
{
    public $id;
    public $description;
    public $payment;
    public $amount;
    public $metrik;

    public function exchangeArray($data)
    {
        $this->id = (!is_null($data['id'])) ? $data['id'] : null;
        $this->description = (!is_null($data['description'])) ? $data['description'] : null;
        $this->payment = (!is_null($data['payment'])) ? $data['payment'] : 0;
        $this->amount = (!is_null($data['amount'])) ? $data['amount'] : 0;
        $this->metrik = (!is_null($data['metrik'])) ? $data['metrik'] : null;
    }

    public function getArrayCopy()
    {
        return get_object_vars($this);
    }


}<file_sep><?php

namespace Mebel\Controller;

use Mebel\Form\WorkerForm;
use Mebel\Model\Worker;
use Mebel\Model\WorkerTable;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;

class WorkerController extends AbstractActionController
{
    protected $workerTable;

    public function indexAction()
    {
        if (!$this->getServiceLocator()->get('AuthService')->hasIdentity()) {
            return $this->redirect()->toRoute('login');
        }

        $view = new ViewModel(array(
            'info' => $this->getServiceLocator()->get('AuthService')->getStorage(),
        ));

        return $view;
    }


    public function ajaxAction(){

        $request = $this->getRequest();
        $current = $request->getPost('current', 1); ;
        $rowCount = $request->getPost('rowCount', 10);
        $sort = $request->getPost('sort');
        $sortField = key($sort);
        $sortType = $sort[$sortField];
        $searchPhrase = $request->getPost('searchPhrase');

        $offset = intval($rowCount) * (intval($current)-1);
        $workers= $this->getWorkerTable()->fetchPage(intval($rowCount), $offset, $sortField.' '.$sortType, $searchPhrase);
        $count= $this->getWorkerTable()->getCount();

        return new JsonModel(array(
            'current' => intval($current),
            'rowCount' => intval($rowCount),
            'rows' => $workers->toArray(),
            "total"=> $count,
        ));
    }

    public function deleteAction()
    {
        $id = (int)$this->params()->fromRoute('id');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $del = $request->getPost('del', 'No');

            if ($del == 'Удалить') {
                $id = (int)$request->getPost('id');
                $this->getWorkerTable()->deleteWorker($id);
            }

            return $this->redirect()->toRoute('worker');
        }

        $worker = $this->getWorkerTable()->getWorker($id);


        $view = new ViewModel([
                'id' => $worker->id,
                'title' => 'Өшіру '.$worker->fio,
                'description' => $worker->fio,
                'url' => $this->url()->fromRoute('worker',['action' => 'delete', 'id' => $worker->id])
            ]
        );
        $view->setTemplate('mebel/admin/delete.phtml');
        return $view;
    }



    public function editAction()
    {
        $id = (int) $this->params()->fromRoute('id', 0);

        if($id){
            $worker = $this->getWorkerTable()->getWorker($id);
        }
        else
            $worker = new Worker();


        $form  = new WorkerForm();
        $form->bind($worker);


        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $this->getWorkerTable()->saveWorker($worker);
                $this->flashMessenger()->addSuccessMessage('Сәтті сақталды');

                if(empty($id))
                    $id = $this->getWorkerTable()->insertedWorker();

                $this->redirect()->toRoute('worker', ['action' => 'edit', 'id' => $id]);
            }else {
                $this->flashMessenger()->addErrorMessage('Енгізуде қате бар');
                $form->highlightErrorElements();
            }
        }


        $view = new ViewModel([
            'form' => $form,
            'id' => $id,
        ]);
        return $view;
    }

    /**
     * @return WorkerTable
     */
    public function getWorkerTable()
    {
        if (!$this->workerTable) {
            $sm = $this->getServiceLocator();
            $this->workerTable = $sm->get('WorkerTable');
        }
        return $this->workerTable;
    }




}<file_sep>function load_prices() {
    clear();
    if ($('select[name=material]').val() > 0) {
        $.ajax({
            url: '/material/' + $('input[name=type]').val() + '/one/' + $('select[name=material]').val(),
            type: 'POST',
            dataType: 'json',
            async: true,
            data: {},
            success: function (data) {
                if (data) {

                    if ($('input[name=isIncome]').val() == 0) {
                        if ($('input[name=quantity]').val() > parseInt(data.count)) {
                            alert('Количество не может быть больше остатка материала!');
                            $('input[name=quantity]').val(data.count);
                            $('input[name=quantity]').attr('style', 'border-color:#a94442; box-shadow:inset 0 1px 1px rgba(0,0,0,.075);')
                        }


                        if ($('input[name=isWholesale]').is(":checked")) {
                            $('input[name=tarif]').val(data.wholesale);
                        } else {
                            $('input[name=tarif]').val(data.retail);
                        }
                    }

                    if ($('input[name=quantity]').val() > 0) {
                        $('input[name=sum]').val($('input[name=tarif]').val() * $('input[name=quantity]').val());
                    } else {
                        $('input[name=sum]').val(0);
                    }
                }
            },
            error: function (data) {
                clear();
                console.log(data);
            }
        });
    } else {
        clear();
    }
}

function clear() {
    if ($('input[name=isIncome]').val() == 0) {
        $('input[name=tarif]').val(0);
    }
    $('input[name=sum]').val(0);
}


$(document).ready(function() {
    $("select[name=material]").select2({
        placeholder: "Материал таңдаңыз",
        allowClear: true,
        language: "ru"
    });
});

<file_sep>$(function () {
    handleaction();

    var timestamp = Date.parse($('input[name=workdate]').val())

    if (isNaN(timestamp) == true) {
        var date = new Date();

        var day = date.getDate();
        var month = date.getMonth() + 1;
        var year = date.getFullYear();

        if (month < 10) month = "0" + month;
        if (day < 10) day = "0" + day;

        var today = year + "-" + month + "-" + day;
        $('input[name=workdate]').attr("value", today);
    }


    $("select[name='rate[]']").multiselect({
        buttonWidth: '100%',
        onChange: add_workdones
    });
});

function load_rate(rateId) {
    if (rateId > 0) {
        $.ajax({
            url: '/rate/one/' + rateId,
            type: 'POST',
            dataType: 'json',
            async: true,
            data: {},
            success: function (data) {
                if (data) {
                    $("input[name='workdones["+rateId+"][rate]']").val(rateId);
                    $("input[name='workdones["+rateId+"][metrik]']").val(data.metrik);
                    $("input[name='workdones["+rateId+"][rateamount]']").val(parseFloat(data.amount));
                    $("input[name='workdones["+rateId+"][ratepayment]']").val(parseFloat(data.payment));

                    $amount = $("input[name='workdones["+rateId+"][amount]']").val();
                    $payment = data.payment * ($amount / data.amount);
                    $("input[name='[workdones"+rateId+"][payment]']").val($payment);
                }
            },
            error: function (data) {
                console.log(data);
            }
        });
    }
}

function recaluculate(){
    $('input[name=total]').val(0);
    $("input[name$='[payment]']").each(function() {
        var total = $('input[name=total]').val();
        $('input[name=total]').val(Number($( this ).val()) + Number(total));
    });
}
function add_workdones(option, checked, select) {
    /*alert('Changed option ' + $(option).text() + '.');
     var currentCount = $('#workdonesDiv> fieldset').length;*/

    recaluculate();

    $('#panel' + option.val()).remove();
    $('#panel0').remove();

    if (checked === true) {
        var template = $('#workdonesDiv> span').data('template');
        template = template.replace(/__workdones_count__/g, option.val());

        $('#workdonesDiv').append(template);
        $('.title' + option.val()).html('<b>' + $(option).text() + '</b>');
        $("input[name='workdones["+$(option).val()+"][name]']").val($(option).text());

        handleaction();

        load_rate( option.val());
    }

    return false;
}

function handleaction(){
    $("input[name$='[amount]']").tooltip({ placement: "left",trigger: "hover"});
    $("input[name$='[payment]']").tooltip({ placement: "left",trigger: "hover"});

    $("input[name$='[amount]']").change(function(){
        $amount = $(this).val();
        $rateamount = $(this).siblings("input[name$='[rateamount]']").val();
        $ratepayment = $(this).siblings("input[name$='[ratepayment]']").val();
        $payment = $ratepayment * ($amount / $rateamount);
        $(this).siblings("input[name$='[payment]']").val($payment);

        recaluculate();
    });
}
<file_sep><?php
namespace Mebel\Form;

use Zend\Db\Adapter\AdapterInterface;
use Zend\Form\Form;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory;

class MaterialForm extends Form
{
    protected $adapter;

    public function __construct($type, $transactionCount)
    {
        parent::__construct('material');

        $inputFilter = new InputFilter();
        $factory = new Factory();


        $this->add([
            'name' => 'id',
            'type' => 'Hidden',
        ]);

        $this->add([
            'name' => 'type',
            'type' => 'Hidden',
            'attributes' => [
                'value' => $type,
            ],
            'haystack' => ['ldsp','dvp','pvh','stol', 'mdf'],
        ]);


        $inputFilter->add($factory->createInput([
            'name' => 'type',
            'required' => true,
            'filters' => [
                ['name' => 'StripTags'],
                ['name' => 'StringTrim'],
            ],
            'validators' => [
                new \Zend\Validator\InArray(
                    ['haystack' => ['ldsp', 'dvp', 'pvh', 'stol', 'mdf']]
                ),
            ],
        ]));

        $this->add([
            'name' => 'image',
            'required' => false,
            'type' => 'File',
            'attributes' => [],
            'options' => [
                'label' => 'Фото',
                'label_attributes' => ['class' => 'control-label col-md-2']
            ],
        ]);
        $this->add([
            'name' => 'name',
            'required' => true,
            'type' => 'Text',
            'attributes' => [
                'class' => 'form-control',
                'placeholder' => 'Наименование',
                'required' => 'true'
            ],
            'options' => [
                'label' => 'Наименование',
                'label_attributes' => ['class' => 'control-label col-md-2']
            ],
        ]);

        $inputFilter->add($factory->createInput([
            'name'     => 'name',
            'required' => false,
            'filters'  => [
                ['name' => 'StripTags'],
                ['name' => 'StringTrim'],
            ],
        ]));

        $this->add([
            'name' => 'description',
            'required' => true,
            'type' => 'Textarea',
            'attributes' => [
                'class' => 'form-control',
                'style' => 'width:100%',
                'rows' => '3',
                'placeholder' => 'Описание',
            ],
            'options' => [
                'label' => 'Описание',
                'label_attributes' => ['class' => 'control-label col-md-2']
            ],
        ]);

        $inputFilter->add($factory->createInput([
            'name'     => 'description',
            'required' => false,
            'filters'  => [
                ['name' => 'StripTags'],
                ['name' => 'StringTrim'],
            ],
        ]));

        if($type!='pvh') {
            $this->add([
                'name' => 'wholesale',
                'required' => true,
                'type' => 'Number',
                'attributes' => [
                    'class' => 'form-control',
                    'placeholder' => 'Оптовая цена',
                    'required' => 'true',
                    'min' => '0',
                    'step' => '1'
                ],
                'options' => [
                    'label' => 'Оптовая цена',
                    'label_attributes' => ['class' => 'control-label col-md-2']
                ],
            ]);
        }

        $this->add([
            'name' => 'retail',
            'required' => true,
            'type' => 'Number',
            'attributes' => [
                'class' => 'form-control',
                'placeholder' => 'Рознечная цена',
                'min' => '0',
                'step' => '1'
            ],
            'options' => [
                'label' => 'Рознечная цена',
                'label_attributes' => ['class' => 'control-label col-md-2']
            ],
        ]);


        $countParams = [
            'name' => 'count',
            'type' => 'Number',
            'attributes' => [
                'class' => 'form-control',
                'placeholder' => $type!='pvh'?'Количество(Остаток на складе)':'Метр(на складе)',
                'min' => '0',
                'step' => '1'
            ],
            'options' => [
                'label' => $type!='pvh'?'Количество':'Метр',
                'label_attributes' => ['class' => 'control-label col-md-2']
            ],
        ];

        if($transactionCount==0) {
            $countParams['required']   = true;
        }

        $this->add($countParams);

        $inputFilter->add($factory->createInput([
            'name'     => 'count',
            'required' => $transactionCount==0?true:false,
        ]));


/*        $this->add([
            'type' => 'Zend\Form\Element\Csrf',
            'name' => 'csrf'
        ));*/


        $this->add([
            'name' => 'submit',
            'type' => 'Submit',
            'attributes' => [
                'value' => 'Сақтау',
                'id' => 'submitbutton',
                'class' => 'btn btn-success pull-right'
            ],
        ]);

        $this->setInputFilter($inputFilter);
    }

    public function highlightErrorElements()
    {
        foreach ($this->getElements() as $element) {
            if ($element->getMessages()) {
                $element->setAttribute('style', 'border-color:#a94442; box-shadow:inset 0 1px 1px rgba(0,0,0,.075);');
                $element->setLabelAttributes([
                    'class' => 'control-label col-md-2',
                    'style' => 'color:#a94442']);
            }
        }
    }
}<file_sep>CREATE TABLE `account` (
  `id`       INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `password` VARCHAR(255)     NOT NULL,
  `fio`      VARCHAR(255)     NOT NULL,
  `phone`    VARCHAR(255)     NOT NULL,
  `email`    VARCHAR(255)     NOT NULL,
  `address`  TEXT,
  `role`     VARCHAR(255)     NOT NULL DEFAULT 'user',
  PRIMARY KEY (`id`)
)
  ENGINE = InnoDB
  AUTO_INCREMENT = 2
  DEFAULT CHARSET = utf8;

INSERT INTO account (ID, PASSWORD, FIO, PHONE, EMAIL, ROLE)
VALUES (1, 'admin', 'Admin', '<PASSWORD>', 'admin', 'admin');
<file_sep><?php

namespace Mebel\Model;

class Work
{
    public $id;
    public $worker;
    public $total;
    public $workdate;

    public $workdones;

    public function exchangeArray($data)
    {
        $this->id = (!is_null($data['id'])) ? $data['id'] : null;
        $this->worker = (!is_null($data['worker'])) ? $data['worker'] : null;
        $this->total = (!is_null($data['total'])) ? $data['total'] : 0;
        $this->workdate = (!is_null($data['workdate'])) ? $data['workdate'] : null;

        $this->workdones = (isset($data['workdones'])) ? $data['workdones'] : null;
    }

    public function getArrayCopy()
    {
        return get_object_vars($this);
    }

    /**
     * @return mixed
     */
    public function getWorkdones()
    {
        return $this->workdones;
    }

    /**
     * @param mixed $workdones
     */
    public function setWorkdones($workdones)
    {
        $this->workdones = $workdones;
    }
}<file_sep><?php
namespace Mebel\Model;

use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Expression;
use Zend\Db\Sql\Sql;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;

class WorkerTable
{
    protected $tableGateway;

    public static $tableName = 'worker';

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    public function fetchAll()
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }

    public function fetchPage($rowCount, $offset, $orderby, $searchPhrase)
    {

        $sql = new Sql($this->tableGateway->adapter);
        $select = $sql->select();
        $select->from($this->tableGateway->table);

        $select->columns(['*']);

        if ($rowCount < 0)
            $select->offset(0);
        else
            $select->limit($rowCount)->offset($offset);
        $select->order($orderby);
        $select->order('date desc');


        if ($searchPhrase) {
            $select->where->NEST->like('fio', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->OR->like('description', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->OR->like('phone', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->OR->like('address', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->OR->like('date', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->UNNEST;
        }

        $statement = $sql->prepareStatementForSqlObject($select);
        $result = $statement->execute();

        $resultSet = new ResultSet();
        $resultSet->initialize($result);

        return $resultSet;
    }


    public function getCount()
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet->count();
    }

    public function getWorker($id)
    {
        $id = (int)$id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }

    public function saveWorker(Worker $worker)
    {
        $data = array(
            'fio' => $worker->fio,
            'description' => $worker->description,
            'phone' => $worker->phone,
            'address' => $worker->address,
        );

        $id = (int)$worker->id;
        if ($id == 0) {
            $this->tableGateway->insert($data);
        } else {
            if ($this->getWorker($id)) {
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('Worker_id does not exist');
            }
        }
    }

    public function deleteWorker($id)
    {
        $this->tableGateway->delete(array('id' => (int)$id));
    }


    public function insertedWorker()
    {
        return $this->tableGateway->lastInsertValue;
    }
}<file_sep><?php
namespace Mebel\Model;

use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Sql;
use Zend\Db\TableGateway\TableGateway;

class WorkdoneTable
{
    protected $tableGateway;

    public static $tableName = 'workdone';

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    public function getWorkdoneByWorkId($workId)
    {
        $workId  = (int) $workId;
        $rowset = $this->tableGateway->select(['work' => $workId]);
        return $rowset;
    }



    public function getCount()
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet->count();
    }

    public function getWorkdone($id)
    {
        $id = (int)$id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }

    public function saveWorkdone(Workdone $workdone)
    {
        $data = array(
            'work' => $workdone->work,
            'payment' => $workdone->payment,
            'rateamount' => $workdone->rateamount,
            'ratepayment' => $workdone->ratepayment,
            'amount' => $workdone->amount,
            'name' => $workdone->name,
            'metrik' => $workdone->metrik,
        );

        $id = (int)$workdone->id;
        if ($id == 0) {
            $this->tableGateway->insert($data);
        } else {
            if ($this->getWorkdone($id)) {
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('Workdone_id does not exist');
            }
        }
    }

    public function deleteWorkdone($id)
    {
        $this->tableGateway->delete(array('id' => (int)$id));
    }


    public function insertedWorkdone()
    {
        return $this->tableGateway->lastInsertValue;
    }
}<file_sep><?php
namespace Mebel\Form;

use Mebel\Model\Workdone;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\Stdlib\Hydrator\ClassMethods as ClassMethodsHydrator;

class WorkdoneFieldset extends Fieldset implements InputFilterProviderInterface
{

    public static $span = "<span data-template='
<div class=\"panel panel-default\" id=\"panel__workdones_count__\">
    <div class=\"panel-heading\">
        <h4 class=\"panel-title\">
            <a data-toggle=\"collapse\" data-target=\"#rate__workdones_count__\"
               href=\"#rate__workdones_count__\" class=\"collapsed title__workdones_count__\">
            </a>
        </h4>
    </div>
    <div id=\"rate__workdones_count__\" class=\"panel-collapse collapse in\">
        <div class=\"panel-body\">
            <fieldset>
                <input type=\"hidden\" name=\"workdones[__workdones_count__][id]\" value=\"\">
                <input type=\"hidden\" name=\"workdones[__workdones_count__][work]\" value=\"\">
                <input type=\"hidden\" name=\"workdones[__workdones_count__][rate]\" value=\"\">
                <input type=\"hidden\" name=\"workdones[__workdones_count__][name]\" value=\"\">
                <input data-toggle=\"tooltip\" title=\"Жұмыс көлемі\"  type=\"number\" name=\"workdones[__workdones_count__][amount]\" class=\"form-control\"
                       placeholder=\"Жұмыс көлемі\" min=\"0\" step=\"1\"value=\"\">
                <input data-toggle=\"tooltip\" title=\"Жұмыс төлемі(тенге)\"  type=\"number\" name=\"workdones[__workdones_count__][payment]\" class=\"form-control\"
                       placeholder=\"Жұмыс төлемі(тенге)\" min=\"0\" step=\"1\" readonly=\"readonly\" value=\"\">
                <input type=\"hidden\" name=\"workdones[__workdones_count__][ratepayment]\" value=\"\">
                <input type=\"hidden\" name=\"workdones[__workdones_count__][rateamount]\" value=\"\">
                <input type=\"hidden\" name=\"workdones[__workdones_count__][metrik]\" value=\"\">
            </fieldset>
        </div>
    </div>
</div>
                            '></span>";


    public function __construct()
    {
        parent::__construct('workdones');


        $this
            ->setHydrator(new ClassMethodsHydrator(false))
            ->setObject(new Workdone());


        $this->add([
            'name' => 'id',
            'type' => 'Hidden',
        ]);

        $this->add([
            'name' => 'work',
            'type' => 'Hidden',
        ]);

        $this->add([
            'name' => 'rate',
            'type' => 'Hidden',
        ]);

        $this->add([
            'name' => 'name',
            'type' => 'Hidden',
        ]);

        $this->add([
            'name' => 'payment',
            'required' => true,
            'type' => 'Number',
            'attributes' => [
                'class' => 'form-control',
                'placeholder' => 'Жұмыс төлемі(тенге)',
                'min' => '0',
                'step' => '0.01',
                'readonly' => 'readonly'
            ],
            'options' => [
                'label' => 'Жұмыс төлемі(тенге)',
                'label_attributes' => ['class' => 'control-label col-md-2']
            ],
        ]);

        $this->add([
            'name' => 'amount',
            'required' => true,
            'type' => 'Number',
            'attributes' => [
                'class' => 'form-control',
                'placeholder' => 'Жұмыс көлемі',
                'min' => '0',
                'step' => '0.01',
            ],
            'options' => [
                'label' => 'Жұмыс көлемі',
                'label_attributes' => ['class' => 'control-label col-md-2']
            ],
        ]);


        $this->add([
            'name' => 'ratepayment',
            'type' => 'Hidden',
        ]);


        $this->add([
            'name' => 'rateamount',
            'type' => 'Hidden',
        ]);


        $this->add([
            'name' => 'metrik',
            'type' => 'Hidden',
        ]);


/*        $this->add([
            'name' => 'ratepayment',
            'required' => true,
            'type' => 'Number',
            'attributes' => [
                'class' => 'form-control',
                'placeholder' => 'тарифтік толем',
                'min' => '0',
                'step' => '0.01',
                'readonly' => 'readonly'
            ],
            'options' => [
                'label' => 'Тарифтік жұмыс төлемі(тенге)',
                'label_attributes' => ['class' => 'control-label col-md-2']
            ],
        ]);


         $this->add([
            'name' => 'rateamount',
            'required' => true,
            'type' => 'Number',
            'attributes' => [
                'class' => 'form-control',
                'placeholder' => 'тарифтік көлемі',
                'min' => '0',
                'step' => '0.01',
                'readonly' => 'readonly'
            ],
            'options' => [
                'label' => 'Тарифтік жұмыс көлемі',
                'label_attributes' => ['class' => 'control-label col-md-2']
            ],
        ]);




        $this->add([
            'name' => 'metrik',
            'required' => true,
            'type' => 'Text',
            'attributes' => [
                'class' => 'form-control',
                'placeholder' => 'Измерение(метр/штук)',
                'required' => 'true',
                'readonly' => 'readonly'
            ],
            'options' => [
                'label' => 'Измерение(метр/штук)',
                'label_attributes' => ['class' => 'control-label col-md-2']
            ],
        ]);*/

    }


    /**
     * @return array
     */
    public function getInputFilterSpecification()
    {
        return [
            [
                'name' => 'name',
                'required' => true,
            ],
            [
                'name' => 'rateamount',
                'required' => true,
            ],
            [
                'name' => 'ratepayment',
                'required' => true,
            ],
            [
                'name' => 'amount',
                'required' => true,
            ],
            [
                'name' => 'payment',
                'required' => true,
            ],
            [
                'name' => 'metrik',
                'required' => true,
                'filters' => [
                    ['name' => 'StripTags'],
                    ['name' => 'StringTrim'],
                ],
            ]

        ];
    }

}<file_sep>CREATE TABLE `worker` (
  `id`          INT(10) UNSIGNED NOT NULL         AUTO_INCREMENT,
  `fio`         VARCHAR(255)     NOT NULL,
  `description` TEXT,
  `phone`       VARCHAR(255)     NULL,
  `address`     TEXT,
  `date`        TIMESTAMP         NOT NULL         DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
)
  ENGINE = InnoDB;
<file_sep><?php
namespace Mebel\Form;

use Zend\Db\Adapter\AdapterInterface;
use Zend\Form\Form;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory;

class TransactionForm extends Form
{
    protected $adapter;

    public function __construct(AdapterInterface $dbAdapter, $type, $config)
    {
        $this->adapter =$dbAdapter;

        parent::__construct('transaction');

        $inputFilter = new InputFilter();
        $factory = new Factory();


        $this->add([
            'name' => 'id',
            'type' => 'Hidden',
        ]);

        $this->add([
            'name' => 'type',
            'type' => 'Hidden',
            'attributes' => [
                'value' => $type,
            ],
            'haystack' => ['ldsp','dvp','pvh','stol'],
        ]);


        $inputFilter->add($factory->createInput([
            'name' => 'type',
            'required' => true,
            'filters' => [
                ['name' => 'StripTags'],
                ['name' => 'StringTrim'],
            ],
            'validators' => [
                new \Zend\Validator\InArray(
                    ['haystack' => ['ldsp', 'dvp', 'pvh', 'stol', 'mdf']]
                ),
            ],
        ]));

        $this->add([
            'name' => 'isIncome',
            'type' => 'Hidden',
        ]);


        $inputFilter->add($factory->createInput([
            'name' => 'isIncome',
            'required' => true,
        ]));

        $this->add([
            'name' => 'description',
            'required' => true,
            'type' => 'Textarea',
            'attributes' => [
                'class' => 'form-control',
                'style' => 'width:100%',
                'rows' => '3',
                'placeholder' => 'Описание',
            ],
            'options' => [
                'label' => 'Описание',
                'label_attributes' => ['class' => 'control-label col-md-2']
            ],
        ]);

        $inputFilter->add($factory->createInput([
            'name'     => 'description',
            'required' => false,
            'filters'  => [
                ['name' => 'StripTags'],
                ['name' => 'StringTrim'],
            ],
        ]));


        $this->add(array(
            'name' => 'material',
            'type' => 'Select',
            'attributes' => array(
                'class' => 'form-control',
                'required' => 'required',
                'onchange' => 'load_prices();'
            ),
            'options' => array(
                'label' => 'Материал ('.$config['menu'][$type].')',
                'label_attributes' => ['class' => 'control-label col-md-2'],
                'empty_option' => 'Материал таңдаңыз',
                'value_options' => $this->getMaterial($type),
            ),
        ));

        $inputFilter->add($factory->createInput([
            'name' => 'material',
            'required' => true,
            'filters' => [
                ['name' => 'StripTags'],
                ['name' => 'StringTrim'],
            ],
        ]));


        $this->add([
            'name' => 'quantity',
            'required' => true,
            'type' => 'Number',
            'attributes' => [
                'class' => 'form-control',
                'placeholder' => 'Саны',
                'required' => 'true',
                'min' => '0',
                'step' => '1',
                'onchange' => 'load_prices();'
            ],
            'options' => [
                'label' => 'Саны',
                'label_attributes' => ['class' => 'control-label col-md-2']
            ],
        ]);

        $inputFilter->add($factory->createInput([
            'name' => 'quantity',
            'required' => true,
            'filters' => [
                ['name' => 'StripTags'],
                ['name' => 'StringTrim'],
            ],
        ]));

        $this->add([
            'name' => 'sum',
            'required' => true,
            'type' => 'Number',
            'attributes' => [
                'readonly' => 'true',
                'class' => 'form-control',
                'placeholder' => 'Сумма',
                'min' => '0',
                'step' => '1'
            ],
            'options' => [
                'label' => 'Сумма',
                'label_attributes' => ['class' => 'control-label col-md-2']
            ],
        ]);

        $inputFilter->add($factory->createInput([
            'name' => 'sum',
            'required' => false,
        ]));

        $this->add([
            'name' => 'tarif',
            'required' => true,
            'type' => 'Number',
            'attributes' => [
                'class' => 'form-control',
                'placeholder' => 'Тариф',
                'min' => '0',
                'step' => '1',
                'onchange' => 'load_prices();'
            ],
            'options' => [
                'label' => 'Тариф',
                'label_attributes' => ['class' => 'control-label col-md-2']
            ],
        ]);


        $inputFilter->add($factory->createInput([
            'name' => 'tarif',
            'required' => false,
        ]));

        $this->add([
            'name' => 'isWholesale',
            'type' => 'Checkbox',
            'attributes' => [
                'value' => 0,
                'onchange' => 'load_prices();'
            ],
            'options' => [
                'label' => 'Оптовая продажа',
                'label_attributes' => ['class' => 'control-label col-md-2'],
                'use_hidden_element' => true,
                'checked_value' => 1,
                'unchecked_value' => 0
            ],
        ]);

/*        $this->add([
            'name' => 'isIncome',
            'type' => 'Checkbox',
            'attributes' => [
                'value' => 0
            ],
            'options' => [
                'label' => 'Кіріс',
                'label_attributes' => ['class' => 'control-label col-md-2'],
                'use_hidden_element' => true,
                'checked_value' => 1,
                'unchecked_value' => 0
            ],
        ]);*/


/*        $this->add([
            'type' => 'Zend\Form\Element\Csrf',
            'name' => 'csrf'
        ));*/


        $this->add([
            'name' => 'confirm',
            'type' => 'Submit',
            'attributes' => [
                'value' => 'Потвердить',
                'id' => 'submitbutton',
                'class' => 'btn btn-success pull-right'
            ],
        ]);

        $this->add([
            'name' => 'save',
            'type' => 'Submit',
            'attributes' => [
                'value' => 'Сохранить',
                'id' => 'submitbutton',
                'class' => 'btn btn-primary pull-right'
            ],
        ]);

        $this->add([
            'name' => 'edit',
            'type' => 'Submit',
            'attributes' => [
                'value' => 'Редактировать',
                'id' => 'submitbutton',
                'class' => 'btn  btn-warning  pull-right',
                'style' => 'margin-right:10px'
            ],
        ]);

        $this->setInputFilter($inputFilter);
    }

    public function getMaterial($type)
    {

        $dbAdapter = $this->adapter;
        $sql       = "SELECT id, name, count FROM material WHERE type='".$type."' ORDER BY id ASC";
        $statement = $dbAdapter->query($sql);
        $result    = $statement->execute();

        $selectData = [];

        foreach ($result as $res) {
            $selectData[$res['id']] = $res['name'].'(складта '.$res['count'].' қалды)';
        }
        return $selectData;
    }


    public function highlightErrorElements()
    {
        foreach ($this->getElements() as $element) {
            if ($element->getMessages()) {
                $element->setAttribute('style', 'border-color:#a94442; box-shadow:inset 0 1px 1px rgba(0,0,0,.075);');
                $element->setLabelAttributes([
                    'class' => 'control-label col-md-2',
                    'style' => 'color:#a94442']);
            }
        }
    }
}<file_sep>CREATE TABLE `workdone` (
  `id`          INT(10) UNSIGNED NOT NULL         AUTO_INCREMENT,
  `work`        INT(10) UNSIGNED NOT NULL,
  `name`        TEXT,
  `ratepayment` FLOAT            NOT NULL,
  `rateamount`  FLOAT            NOT NULL,
  `payment`     FLOAT            NOT NULL         DEFAULT 0,
  `amount`      FLOAT            NOT NULL         DEFAULT 0,
  `metrik`      VARCHAR(255)     NOT NULL,
  `date`        TIMESTAMP         NOT NULL         DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  INDEX `FK1_work` (`work`),
  CONSTRAINT `FK1_work` FOREIGN KEY (`work`) REFERENCES `work` (`id`)
    ON UPDATE CASCADE
    ON DELETE CASCADE
)
  ENGINE = InnoDB;
<file_sep><?php
return array(

    'menu' => [
        'all' => 'Все материалы',
        'ldsp' => 'ЛДСП',
        'mdf' => 'МДФ акрель',
        'dvp' => 'ДВП',
        'pvh' => 'ПВХ',
        'stol' => 'Столешница',
    ],

    'sale' => [
        0 => 'Рознечная продажа',
        1 => 'Оптовая продажа',
    ],

    'come' => [
        0 => 'Шығыс',
        1 => 'Кіріс',
    ],



    'controllers' => array(
        'invokables' => array(
            'Mebel\Controller\Admin'          =>  'Mebel\Controller\AdminController',
            'Mebel\Controller\Material'       =>  'Mebel\Controller\MaterialController',
            'Mebel\Controller\Transaction'    =>  'Mebel\Controller\TransactionController',
            'Mebel\Controller\Worker'         =>  'Mebel\Controller\WorkerController',
            'Mebel\Controller\Rate'           =>  'Mebel\Controller\RateController',
            'Mebel\Controller\Work'           =>  'Mebel\Controller\WorkController',
		)
    ),

    'router' => array(
        'routes' => array(

            'home' => array(
                'type' => 'segment',
                'options' => array(
                    'route' => '/[:action]',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    ),
                    'defaults' => array(
                        'controller' => 'Mebel\Controller\Admin',
                        'action' => 'index',
                    ),
                ),
            ),

            'material' => array(
                'type' => 'segment',
                'options' => array(
                    'route' => '/material[/:type][/:action][/:id]',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    ),
                    'defaults' => array(
                        'controller' => 'Mebel\Controller\Material',
                        'action' => 'index',
                    ),
                ),
            ),
            'transaction' => array(
                'type' => 'segment',
                'options' => array(
                    'route' => '/transaction[/:type][/:action][/:id][?direction=:direction]',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    ),
                    'defaults' => array(
                        'controller' => 'Mebel\Controller\Transaction',
                        'action' => 'index',
                    ),
                ),
            ),
            'worker' => array(
                'type' => 'segment',
                'options' => array(
                    'route' => '/worker[/:action][/:id]',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    ),
                    'defaults' => array(
                        'controller' => 'Mebel\Controller\Worker',
                        'action' => 'index',
                    ),
                ),
            ),
            'rate' => array(
                'type' => 'segment',
                'options' => array(
                    'route' => '/rate[/:action][/:id]',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    ),
                    'defaults' => array(
                        'controller' => 'Mebel\Controller\Rate',
                        'action' => 'index',
                    ),
                ),
            ),
            'work' => array(
                'type' => 'segment',
                'options' => array(
                    'route' => '/work[/:action][/:id]',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    ),
                    'defaults' => array(
                        'controller' => 'Mebel\Controller\Work',
                        'action' => 'index',
                    ),
                ),
            ),
            'report' => array(
                'type' => 'segment',
                'options' => array(
                    'route' => '/report[/:action]',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    ),
                    'defaults' => array(
                        'controller' => 'Mebel\Controller\Report',
                        'action' => 'index',
                    ),
                ),
            ),

            'login' => array(
                'type' => 'Literal',
                'options' => array(
                    'route' => '/login',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    ),
                    'defaults' => array(
                        'controller' => 'Mebel\Controller\Admin',
                        'action' => 'login',
                    ),
                ),
            ),

            'authenticate' => array(
                'type' => 'Literal',
                'options' => array(
                    'route' => '/authenticate',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    ),
                    'defaults' => array(
                        'controller' => 'Mebel\Controller\Admin',
                        'action' => 'authenticate',
                    ),
                ),
            ),

            'logout' => array(
                'type' => 'Literal',
                'options' => array(
                    'route' => '/logout',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    ),
                    'defaults' => array(
                        'controller' => 'Mebel\Controller\Admin',
                        'action' => 'logout',
                    ),
                ),
            ),

            'admin' => array(
                'type' => 'segment',
                'options' => array(
                    'route' => '/admin/setting/[:action][/:id][?[page=:page]]',
                    'defaults' => array(
                        'controller' => 'Mebel\Controller\Admin',
                        'action'     => 'admin',
                    ),
                ),
            ),

        ),
    ),

    'service_manager' => array(
        'abstract_factories' => array(
            'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
            'Zend\Log\LoggerAbstractServiceFactory',
        ),
        'aliases' => array(
            'translator' => 'MvcTranslator',
            'Zend\Authentication\AuthenticationService' => 'AuthService',
        ),
    ),

    'translator' => array(
        'locale' => 'ru_RU',
		'available'     => array(
			'kz_KZ' => 'Kazakh',
			'ru_RU' => 'Russian',
		),
        'translation_file_patterns' => array(
            array(
                'type'     => 'gettext',
                'base_dir' => __DIR__ . '/../language',
                'pattern'  => '%s.mo',
            ),
        ),
    ),

    'view_manager' => array(
        'display_not_found_reason' => true,
        'display_exceptions' => true,
        'doctype' => 'HTML5',
        'not_found_template'       => 'error/404',
        'exception_template'       => 'error/index',
        'template_map' => array(
            'layout/layout'           			=> __DIR__ . '/../view/layout/layout.phtml',
            'application/index/index' 			=> __DIR__ . '/../view/application/index/index.phtml',
            'error/404'               			=> __DIR__ . '/../view/error/404.phtml',
            'error/index'             			=> __DIR__ . '/../view/error/index.phtml',
        ),
        'template_path_stack' => array(
            __DIR__ . '/../view',
        ),
        'strategies' => array(
            'ViewJsonStrategy'
        ),
    ),

    // Placeholder for console routes
    'console' => array(
        'router' => array(
            'routes' => array(
				'sendmail'  => [
					'options' => [
						'route'    => 'sendmail',
						'defaults' => [
							'controller' => 'Mebel\Admin\Console',
							'action' => 'sendMail',
						],
					],
				],
            ),
        ),
    ),
);<file_sep>CREATE TABLE `work` (
  `id`       INT(10) UNSIGNED NOT NULL         AUTO_INCREMENT,
  `worker`   INT(10) UNSIGNED NOT NULL,
  `total`    FLOAT            NOT NULL         DEFAULT 0,
  `workdate` DATE             NULL,
  `date`     TIMESTAMP         NOT NULL         DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  INDEX `FK1_worker` (`worker`),
  CONSTRAINT `FK1_worker` FOREIGN KEY (`worker`) REFERENCES `worker` (`id`)
    ON UPDATE CASCADE
    ON DELETE CASCADE
)
  ENGINE = InnoDB;
<file_sep><?php
namespace Mebel\Model;

use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Expression;
use Zend\Db\Sql\Sql;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;

class TransactionTable
{
    protected $tableGateway;

    public static $tableName = 'transaction';

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    public function fetchAll()
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }

    public function countByMaterial($material)
    {
        return $this->tableGateway->select(['material' => $material])->count();
    }

    public function fetchPage($rowCount, $offset, $orderby, $searchPhrase, $type, $direction)
    {

        $sql = new Sql($this->tableGateway->adapter);
        $select = $sql->select();
        $select->from($this->tableGateway->table);

        $select->columns([
            '*',
            new Expression("CASE isWholesale WHEN 0 THEN 'рознечная' WHEN 1 THEN 'оптовая' END as saleStr"),
            new Expression("CASE isIncome WHEN 0 THEN 'шығыс' WHEN 1 THEN 'кіріс' END as comeStr"),
            new Expression('material.name as materialStr'),
            new Expression("DATE_FORMAT(transaction.date, '%Y-%m-%d')  as dateStr"),
            new Expression("DATE_FORMAT(transaction.date,'%H:%i:%s')  as timeStr"),
        ]);

        $select->join('material', 'material.id = transaction.material', ['name'], Select::JOIN_LEFT);

        if ($rowCount < 0)
            $select->offset(0);
        else
            $select->limit($rowCount)->offset($offset);
        $select->order($orderby);
        $select->order('date desc');


        if ($searchPhrase) {
            $select->where->NEST->like('description', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->OR->like('quantity', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->OR->like('sum', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->OR->like('tarif', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->OR->like('date', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->UNNEST;
        }

        if($type != 'all') {
            $select->where->equalTo('transaction.type', $type);
        }

        if($direction == 'income') {
            $select->where->equalTo('isIncome', 1);
        }
        if($direction == 'outcome') {
            $select->where->equalTo('isIncome', 0);
        }


        $statement = $sql->prepareStatementForSqlObject($select);
        $result = $statement->execute();

        $resultSet = new ResultSet();
        $resultSet->initialize($result);

        return $resultSet;
    }


    public function getCount($type)
    {
        if($type!='all') {
            $resultSet = $this->tableGateway->select(function (Select $select) use($type) {
                $select->where->like('type', $type);
            });
        } else {
            $resultSet = $this->tableGateway->select();
        }

        return $resultSet->count();
    }

    public function getTransaction($id)
    {
        $id = (int)$id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }

    public function saveTransaction(Transaction $transaction)
    {
        $data = array(
            'type' => $transaction->type,
            'description' => $transaction->description,
            'material' => $transaction->material,
            'quantity' => $transaction->quantity,
            'sum' => $transaction->sum,
            'tarif' => $transaction->tarif,
            'isWholesale' => $transaction->isWholesale === null?0:$transaction->isWholesale,
            'isIncome' => $transaction->isIncome === null?0:$transaction->isIncome,
        );

        $id = (int)$transaction->id;
        if ($id == 0) {
            $this->tableGateway->insert($data);
        } else {
            if ($this->getTransaction($id)) {
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('Transaction_id does not exist');
            }
        }
    }

    public function deleteTransaction($id)
    {
        $this->tableGateway->delete(array('id' => (int)$id));
    }


    public function insertedTransaction()
    {
        return $this->tableGateway->lastInsertValue;
    }
}<file_sep><?php

namespace Mebel\Model;

class Workdone
{
    public $id;
    public $work;
    public $rate;
    public $payment;
    public $amount;
    public $ratepayment;
    public $rateamount;
    public $name;
    public $metrik;

    public function exchangeArray($data)
    {
        $this->id = (!is_null($data['id'])) ? $data['id'] : null;
        $this->work = (!is_null($data['work'])) ? $data['work'] : null;
        $this->rate = (!empty($data['rate'])) ? $data['rate'] : 0;
        $this->payment = (!is_null($data['payment'])) ? $data['payment'] : 0;
        $this->amount = (!is_null($data['amount'])) ? $data['amount'] : 0;
        $this->ratepayment = (!is_null($data['payment'])) ? $data['payment'] : null;
        $this->rateamount = (!is_null($data['amount'])) ? $data['amount'] : null;
        $this->name = (!is_null($data['name'])) ? $data['name'] : null;
        $this->metrik = (!is_null($data['metrik'])) ? $data['metrik'] : null;
    }

    public function getArrayCopy()
    {
        return get_object_vars($this);
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return mixed
     */
    public function getWork()
    {
        return $this->work;
    }

    /**
     * @param mixed $work
     */
    public function setWork($work)
    {
        $this->work = $work;
    }

    /**
     * @return mixed
     */
    public function getRate()
    {
        return $this->rate;
    }

    /**
     * @param mixed $rate
     */
    public function setRate($rate)
    {
        $this->rate = $rate;
    }


    /**
     * @return mixed
     */
    public function getPayment()
    {
        return $this->payment;
    }

    /**
     * @param mixed $payment
     */
    public function setPayment($payment)
    {
        $this->payment = $payment;
    }

    /**
     * @return mixed
     */
    public function getAmount()
    {
        return $this->amount;
    }

    /**
     * @param mixed $amount
     */
    public function setAmount($amount)
    {
        $this->amount = $amount;
    }

    /**
     * @return mixed
     */
    public function getRatepayment()
    {
        return $this->ratepayment;
    }

    /**
     * @param mixed $ratepayment
     */
    public function setRatepayment($ratepayment)
    {
        $this->ratepayment = $ratepayment;
    }

    /**
     * @return mixed
     */
    public function getRateamount()
    {
        return $this->rateamount;
    }

    /**
     * @param mixed $rateamount
     */
    public function setRateamount($rateamount)
    {
        $this->rateamount = $rateamount;
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param mixed $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }



    /**
     * @return mixed
     */
    public function getMetrik()
    {
        return $this->metrik;
    }

    /**
     * @param mixed $metrik
     */
    public function setMetrik($metrik)
    {
        $this->metrik = $metrik;
    }




}<file_sep><?php

namespace Mebel;

use Mebel\Model\Material;
use Mebel\Model\MaterialTable;
use Mebel\Model\Rate;
use Mebel\Model\RateTable;
use Mebel\Model\Transaction;
use Mebel\Model\TransactionTable;
use Mebel\Model\User;
use Mebel\Model\UserTable;

use Mebel\Model\AuthStorage;

use Mebel\Model\Work;
use Mebel\Model\Workdone;
use Mebel\Model\WorkdoneTable;
use Mebel\Model\Worker;
use Mebel\Model\WorkerTable;
use Mebel\Model\WorkTable;
use Mebel\View\Helper\Config;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;

use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter;
use Zend\Authentication\AuthenticationService;
use Zend\Permissions\Acl\Acl;
use Zend\Permissions\Acl\Role\GenericRole as Role;
use Zend\Permissions\Acl\Resource\GenericResource as Resource;

class Module implements AutoloaderProviderInterface, ConfigProviderInterface
{

    public function onBootstrap(MvcEvent $e)
    {
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);

        $this->initAcl($e);
		$eventManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'checkAcl'));

    }


    public function initAcl(MvcEvent $e)
    {

        $acl = new Acl();

        $acl->addRole(new Role('nobody'))
            ->addRole(new Role('admin'));

        $acl->addResource(new Resource('home'))
            ->addResource(new Resource('material'))
            ->addResource(new Resource('transaction'))
            ->addResource(new Resource('worker'))
            ->addResource(new Resource('rate'))
            ->addResource(new Resource('work'))
            ->addResource(new Resource('login'))
            ->addResource(new Resource('logout'))
            ->addResource(new Resource('authenticate'));

        $acl->allow('nobody', 'home')->allow('nobody', 'login')->allow('nobody', 'authenticate')
            ->allow('admin', 'home')->allow('admin', 'authenticate')->allow('admin', 'logout')->allow('admin', 'material')->allow('admin', 'transaction')->allow('admin', 'worker')->allow('admin', 'rate')->allow('admin', 'work');

        $e->getViewModel()->acl = $acl;
    }

    public function checkAcl(MvcEvent $e)
    {
        $route = $e->getRouteMatch()->getMatchedRouteName();

        $authStorage = new AuthStorage();
        $userRole = $authStorage->getRole();

        if (!$e->getViewModel()->acl->isAllowed($userRole, $route) ) {
            $response = $e->getResponse();

            //location to page or what ever
            $response->getHeaders()->addHeaderLine('Location', $e->getRequest()->getBaseUrl() . '/login');
            $response->setStatusCode(301);
        }
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    // Autoload all classes from namespace 'Blog' from '/module/Blog/src/Blog'
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                )
            )
        );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getViewHelperConfig(){
        return [
            'factories' => [
                'config' => function($sm){
                    $config =  $sm->getServiceLocator()->get('config');
                    return new Config($config);

                },
            ],
        ];
    }

    public function getServiceConfig()
    {
        return array(

            'factories'=> [

                'Mebel\Model\AuthStorage' => function ($sm) {
                    return new AuthStorage(UserTable::$tableName);
                },

                'AuthService' => function ($sm) {
                    $dbAdapter      = $sm->get('Zend\Db\Adapter\Adapter');
                    $dbTableAuthAdapter  = new DbTableAuthAdapter($dbAdapter, UserTable::$tableName,'email','<PASSWORD>');

                    $authService = new AuthenticationService();
                    $authService->setAdapter($dbTableAuthAdapter);
                    $authService->setStorage($sm->get('Mebel\Model\AuthStorage'));

                    return $authService;
                },
                'UserTable' =>  function($sm) {
                    $tableGateway = $sm->get('UserTableGateway');
                    $table = new UserTable($tableGateway);
                    return $table;
                },
                'UserTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new User());
                    return new TableGateway(UserTable::$tableName, $dbAdapter, null, $resultSetPrototype);
                },
                'MaterialTable' =>  function($sm) {
                    $tableGateway = $sm->get('MaterialTableGateway');
                    $table = new MaterialTable($tableGateway);
                    return $table;
                },
                'MaterialTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Material());
                    return new TableGateway(MaterialTable::$tableName, $dbAdapter, null, $resultSetPrototype);
                },
                'TransactionTable' =>  function($sm) {
                    $tableGateway = $sm->get('TransactionTableGateway');
                    $table = new TransactionTable($tableGateway);
                    return $table;
                },
                'TransactionTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Transaction());
                    return new TableGateway(TransactionTable::$tableName, $dbAdapter, null, $resultSetPrototype);
                },
                'WorkerTable' =>  function($sm) {
                    $tableGateway = $sm->get('WorkerTableGateway');
                    $table = new WorkerTable($tableGateway);
                    return $table;
                },
                'WorkerTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Worker());
                    return new TableGateway(WorkerTable::$tableName, $dbAdapter, null, $resultSetPrototype);
                },
                'RateTable' =>  function($sm) {
                    $tableGateway = $sm->get('RateTableGateway');
                    $table = new RateTable($tableGateway);
                    return $table;
                },
                'RateTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Rate());
                    return new TableGateway(RateTable::$tableName, $dbAdapter, null, $resultSetPrototype);
                },
                'WorkTable' =>  function($sm) {
                    $tableGateway = $sm->get('WorkTableGateway');
                    $table = new WorkTable($tableGateway);
                    return $table;
                },
                'WorkTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Work());
                    return new TableGateway(WorkTable::$tableName, $dbAdapter, null, $resultSetPrototype);
                },
                'WorkdoneTable' =>  function($sm) {
                    $tableGateway = $sm->get('WorkdoneTableGateway');
                    $table = new WorkdoneTable($tableGateway);
                    return $table;
                },
                'WorkdoneTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Workdone());
                    return new TableGateway(WorkdoneTable::$tableName, $dbAdapter, null, $resultSetPrototype);
                },
            ],
        );
    }

}<file_sep><?php

namespace Mebel\Controller;

use Mebel\Form\TransactionForm;
use Mebel\Model\MaterialTable;
use Mebel\Model\Transaction;
use Mebel\Model\TransactionTable;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;

class TransactionController extends AbstractActionController
{
    protected $transactionTable;
    protected $materialTable;

    public function indexAction()
    {
        if (!$this->getServiceLocator()->get('AuthService')->hasIdentity()) {
            return $this->redirect()->toRoute('login');
        }

        $type = $this->params()->fromRoute('type');

        if(empty($type))
            $this->redirect()->toRoute('transaction', ['type' => 'all']);

        $direction = $this->params()->fromQuery('direction');

        $config = $this->getServiceLocator()->get('config');

        $view = new ViewModel(array(
            'info' => $this->getServiceLocator()->get('AuthService')->getStorage(),
            'type' => $type,
            'direction' => $direction,
            'config' => $config,
        ));

        return $view;
    }


    public function ajaxAction(){
        $type = $this->params()->fromRoute('type');
        $direction = $this->params()->fromQuery('direction');

        $request = $this->getRequest();
        $current = $request->getPost('current', 1); ;
        $rowCount = $request->getPost('rowCount', 10);
        $sort = $request->getPost('sort');
        $sortField = key($sort);
        $sortType = $sort[$sortField];
        $searchPhrase = $request->getPost('searchPhrase');

        $offset = intval($rowCount) * (intval($current)-1);
        $transactions= $this->getTransactionTable()->fetchPage(intval($rowCount), $offset, $sortField.' '.$sortType, $searchPhrase, $type, $direction);
        $count= $this->getTransactionTable()->getCount($type);

        return new JsonModel(array(
            'current' => intval($current),
            'rowCount' => intval($rowCount),
            'rows' => $transactions->toArray(),
            "total"=> $count,
        ));
    }

/*
    public function deleteAction()
    {
        $id = (int)$this->params()->fromRoute('id');
        $type = $this->params()->fromRoute('type');
        $direction = $this->params()->fromQuery('direction');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $del = $request->getPost('del', 'No');

            if ($del == 'Удалить') {
                $id = (int)$request->getPost('id');
                $this->getTransactionTable()->deleteTransaction($id);
            }

            return $this->redirect()->toRoute('transaction', ['type' => $type]);
        }

        $transaction = $this->getTransactionTable()->getTransaction($id);


        $view = new ViewModel([
                'id' => $transaction->id,
                'title' => 'Өшіру '.$transaction->type,
                'description' => $transaction->description,
                'type' => $transaction->type,
                'url' => $this->url()->fromRoute('transaction',['action' => 'delete', 'type' => $transaction->type , 'direction' => $transaction->direction, 'id' => $transaction->id])
            ]
        );
        $view->setTemplate('mebel/admin/delete.phtml');
        return $view;
    }
*/


    public function editAction()
    {
        $id = (int) $this->params()->fromRoute('id', 0);
        $type = $this->params()->fromRoute('type');
        $direction = $this->params()->fromQuery('direction');

        if(empty($type))
            $this->redirect()->toRoute('transaction', ['type' => 'all']);

        if($id){
            $transaction = $this->getTransactionTable()->getTransaction($id);
        }
        else
            $transaction = new Transaction();

        $save = false;
        $message = '';
        $dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $config = $this->getServiceLocator()->get('config');

        $form  = new TransactionForm($dbAdapter, $type, $config);
        $form->bind($transaction);

        if(!empty($id)) {
            foreach ($form->getElements() as $element) {
                $element->setAttribute('readonly', 'readonly');
            }

        }

        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            if ($form->isValid()) {

                $material = null;
                if($transaction->material){
                    $material = $this->getMaterialTable()->getMaterial($transaction->material);
                    if ($transaction->quantity <= 0) {
                        $message = 'Количество не может быть ранво нулю!';
                    }
                    if ($transaction->quantity > $material->count && $transaction->isIncome == 0) {
                        $message = 'Количество не может быть больше остатка материала!';
                    }
                } else {
                    $message = 'Материал в базе отсутствует';
                }

                if($transaction->isIncome == 0) {
                    if ($transaction->isWholesale == 1) {
                        $transaction->tarif = $material->wholesale;;
                    }
                    if ($transaction->isWholesale == 0) {
                        $transaction->tarif = $material->retail;
                    }
                }

                $transaction->sum= $transaction->tarif * $transaction->quantity;


                $confirmBtn = $request->getPost('confirm');

                if(!empty($confirmBtn)) {
                    $save = true;
                    foreach ($form->getElements() as $element) {
                        $element->setAttribute('readonly', 'readonly');
                    }
                }

                $saveBtn = $request->getPost('save');
                if (empty($message) && !empty($saveBtn) && empty($id)) {
                    $result = false;
                    if($transaction->isIncome == 1) {
                        $result = $this->getMaterialTable()->incomeMaterial($material, $transaction->quantity);
                    }
                    if($transaction->isIncome == 0) {
                        $result = $this->getMaterialTable()->outcomeMaterial($material, $transaction->quantity);
                    }

                    if($result){
                        $this->getTransactionTable()->saveTransaction($transaction);
                        $this->flashMessenger()->addSuccessMessage('Сәтті сақталды');
                        $this->redirect()->toRoute('transaction', ['action' => 'edit', 'type' => $type, 'direction' => $direction, 'id' => $this->getTransactionTable()->insertedTransaction()]);
                    }
                }
            }else {
                $this->flashMessenger()->addErrorMessage('Енгізуде қате бар');
                $form->highlightErrorElements();
            }
        }




        $view = new ViewModel([
            'save' => $save,
            'form' => $form,
            'id' => $id,
            'type' => $type,
            'direction' => $direction,
            'config' => $config,
            'message' => $message,
        ]);
        return $view;
    }

    /**
     * @return TransactionTable
     */
    public function getTransactionTable()
    {
        if (!$this->transactionTable) {
            $sm = $this->getServiceLocator();
            $this->transactionTable = $sm->get('TransactionTable');
        }
        return $this->transactionTable;
    }

    /**
     * @return MaterialTable
     */
    public function getMaterialTable()
    {
        if (!$this->materialTable) {
            $sm = $this->getServiceLocator();
            $this->materialTable = $sm->get('MaterialTable');
        }
        return $this->materialTable;
    }

}<file_sep><?php

namespace Mebel\Controller;

use Mebel\Form\MaterialForm;
use Mebel\Model\Material;
use Mebel\Model\MaterialTable;
use Mebel\Model\TransactionTable;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;

class MaterialController extends AbstractActionController
{
    protected $materialTable;
    protected $transactionTable;

    public function indexAction()
    {
        if (!$this->getServiceLocator()->get('AuthService')->hasIdentity()) {
            return $this->redirect()->toRoute('login');
        }

        $type = $this->params()->fromRoute('type');

        if(empty($type))
            $this->redirect()->toRoute('material', ['type' => 'all']);

        $config = $this->getServiceLocator()->get('config');

        $view = new ViewModel(array(
            'info' => $this->getServiceLocator()->get('AuthService')->getStorage(),
            'type' => $type,
            'config' => $config,
        ));

        return $view;
    }


    public function ajaxAction(){
        $type = $this->params()->fromRoute('type');

        $request = $this->getRequest();
        $current = $request->getPost('current', 1); ;
        $rowCount = $request->getPost('rowCount', 10);
        $sort = $request->getPost('sort');
        $sortField = key($sort);
        $sortType = $sort[$sortField];
        $searchPhrase = $request->getPost('searchPhrase');

        $offset = intval($rowCount) * (intval($current)-1);
        $materials= $this->getMaterialTable()->fetchPage(intval($rowCount), $offset, $sortField.' '.$sortType, $searchPhrase, $type);
        $count= $this->getMaterialTable()->getCount($type);

        return new JsonModel(array(
            'current' => intval($current),
            'rowCount' => intval($rowCount),
            'rows' => $materials->toArray(),
            "total"=> $count,
        ));
    }

    public function oneAction(){
        $id = (int)$this->params()->fromRoute('id');

        $material= $this->getMaterialTable()->getMaterial($id);

        return new JsonModel($material->getArrayCopy());
    }

    public function deleteAction()
    {
        $id = (int)$this->params()->fromRoute('id');
        $type = $this->params()->fromRoute('type');

        $transactionCount = $this->getTransactionTable()->countByMaterial($id);

        $request = $this->getRequest();
        if ($request->isPost()) {
            if($transactionCount<=0) {
                $del = $request->getPost('del', 'No');
                if ($del == 'Удалить') {
                    $id = (int)$request->getPost('id');
                    $this->getMaterialTable()->deleteMaterial($id);
                }
            }
            return $this->redirect()->toRoute('material', ['type' => $type]);
        }

        $material = $this->getMaterialTable()->getMaterial($id);


        $view = new ViewModel([
                'id' => $material->id,
                'title' => 'Өшіру '.$material->type.($transactionCount>0?'<span style="color: red"> &nbsp; Бүл материалда кіріс шығыстар бар, егер өшіргіңіз келсе алдымен кіріс шығысты өшіріңіз</span>':''),
                'description' => $material->name,
                'type' => $material->type,
                'delete' => $transactionCount,
                'url' => $this->url()->fromRoute('material',['action' => 'delete', 'type' => $material->type, 'id' => $material->id])
            ]
        );
        $view->setTemplate('mebel/admin/delete.phtml');
        return $view;
    }



    public function editAction()
    {
        $id = (int) $this->params()->fromRoute('id', 0);
        $type = $this->params()->fromRoute('type');

        if(empty($type))
            $this->redirect()->toRoute('material', ['type' => 'all']);

        $transactionCount = 0;
        $message = '';

        if($id){
            $material = $this->getMaterialTable()->getMaterial($id);
            $transactionCount = $this->getTransactionTable()->countByMaterial($material->id);
        }
        else
            $material = new Material();


        $form  = new MaterialForm($type, $transactionCount);
        $form->bind($material);

        if($transactionCount > 0){
            $form->get('count')->setAttribute('disabled', 'disabled');
            $form->get('name')->setAttribute('disabled', 'disabled');
        }

        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());

            if ($form->isValid()) {

                $materialCount = $this->getMaterialTable()->countByMaterialName($material->name);
                if($materialCount > 0) {
                    $message = 'Материал с таким именем уже существеут!!!';
                } else {
                    $this->getMaterialTable()->saveMaterial($material, $transactionCount);
                    $this->flashMessenger()->addSuccessMessage('Сәтті сақталды');

                    if(empty($id))
                        $id = $this->getMaterialTable()->insertedMaterial();

                    $this->redirect()->toRoute('material', ['type' => $type, 'action' => 'edit', 'id' => $id]);
                }

            }else {
                $this->flashMessenger()->addErrorMessage('Енгізуде қате бар');
                $form->highlightErrorElements();
            }
        }

        $config = $this->getServiceLocator()->get('config');

        $view = new ViewModel([
            'form' => $form,
            'id' => $id,
            'type' => $type,
            'config' => $config,
            'message' => $message,
            'photo' => empty($material->image)?'empty.png':$material->image,
        ]);
        return $view;
    }


    public function photoAction()
    {
        $id = (int)$this->params()->fromRoute('id', 0);
        $type = $this->params()->fromRoute('type');

        if(empty($type))
            $this->redirect()->toRoute('material', ['type' => 'all']);


        if($id== 0) {
            return $this->redirect()->toRoute('material', [
                'action' => 'index',
                'type' => $type
            ]);
        }


        $request = $this->getRequest();
        if ($request->isPost()) {
            $adapter = new \Zend\File\Transfer\Adapter\Http();
            $fullpath = getcwd() . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'photo' . DIRECTORY_SEPARATOR;
            $filename = $fullpath.$id . '.jpg';
            $adapter->addFilter('Rename', array('target' =>  $filename, 'overwrite' => true));
            $adapter->receive();

            $this->getMaterialTable()->saveImage($id, $id . '.jpg');

            $this->createThumbs($filename,  $fullpath.$id . '-400.jpg', 400);
            $this->createThumbs($filename,  $fullpath.$id . '-150.jpg', 150);



            return new JsonModel([]);
        }



        $material = $this->getMaterialTable()->getMaterial($id);
        $config = $this->getServiceLocator()->get('config');

        $view = new ViewModel([
            'material' => $material,
            'config'   => $config,
        ]);
        return $view;
    }


    function createThumbs($pathToImage, $pathToThumbImage, $thumbWidth)
    {

        $info = pathinfo($pathToImage);
        // continue only if this is a JPEG image
        if (strtolower($info['extension']) == 'jpg') {
            //echo "Creating thumbnail for {$pathToThumbImage} <br />";

            // load image and get image size
            $img = imagecreatefromjpeg($pathToImage);
            $width = imagesx($img);
            $height = imagesy($img);

            // calculate thumbnail size
            $new_width = $thumbWidth;
            $new_height = floor($height * ($thumbWidth / $width));

            // create a new temporary image
            $tmp_img = imagecreatetruecolor($new_width, $new_height);

            // copy and resize old image into new image
            imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

            // save thumbnail into a file
            imagejpeg($tmp_img, $pathToThumbImage);
        }

    }


    /**
     * @return MaterialTable
     */
    public function getMaterialTable()
    {
        if (!$this->materialTable) {
            $sm = $this->getServiceLocator();
            $this->materialTable = $sm->get('MaterialTable');
        }
        return $this->materialTable;
    }



    /**
     * @return TransactionTable
     */
    public function getTransactionTable()
    {
        if (!$this->transactionTable) {
            $sm = $this->getServiceLocator();
            $this->transactionTable = $sm->get('TransactionTable');
        }
        return $this->transactionTable;
    }


}<file_sep><?php
namespace Mebel\Model;

use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Predicate\Expression;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;

class MaterialTable
{
    protected $tableGateway;

    public static $tableName = 'material';

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    public function fetchAll()
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }

    public function fetchPage($rowCount, $offset, $orderby, $searchPhrase, $type)
    {

        $sql = new Sql($this->tableGateway->adapter);
        $select = $sql->select();
        $select->from($this->tableGateway->table);

        $select->columns(['*']);

        if ($rowCount < 0)
            $select->offset(0);
        else
            $select->limit($rowCount)->offset($offset);
        $select->order('name asc');


        if ($searchPhrase) {
            $select->where->NEST->like('name', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->OR->like('description', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->OR->like('wholesale', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->OR->like('retail', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->OR->like('count', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->OR->like('date', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->UNNEST;
        }

        if($type!='all') {
            $select->where->equalTo('type', $type);
        }

        $statement = $sql->prepareStatementForSqlObject($select);
        $result = $statement->execute();

        $resultSet = new ResultSet();
        $resultSet->initialize($result);

        return $resultSet;
    }


    public function getCount($type)
    {
        if($type!='all') {
            $resultSet = $this->tableGateway->select(function (Select $select) use($type) {
                $select->where->like('type', $type);
            });
        } else {
            $resultSet = $this->tableGateway->select();
        }

        return $resultSet->count();
    }

    /**
     * @param $id
     * @return Material
     * @throws \Exception
     */
    public function getMaterial($id)
    {
        $id = (int)$id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }

    public function countByMaterialName($materialName)
    {
        return $this->tableGateway->select( function (Select $select) use ($materialName) {
            $where = new Where();
            $where->addPredicate(new Expression("TRIM(LOWER(name)) = TRIM(LOWER(?)) ",  $materialName));
            $select->where($where);
            $select->columns(['id']);

        })->count();
    }

    public function saveMaterial(Material $material, $transactionCount)
    {
        $data = array(
            'type' => $material->type,
            'description' => $material->description,
            'wholesale' => $material->wholesale,
            'retail' => $material->retail,
            'image' => $material->image,
        );

        if ($transactionCount ==0) {
            $data['count'] =$material->count;
            $data['name'] =$material->name;
        }

        $id = (int)$material->id;
        if ($id == 0) {
            $this->tableGateway->insert($data);
        } else {
            if ($this->getMaterial($id)) {
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('Material_id does not exist');
            }
        }
    }

    public function incomeMaterial($material, $income)
    {
        $count = $material->count + $income;

        if($count<0)
            return false;

        $data = array(
            'count' =>$count,
        );

        $id = (int)$material->id;
        $this->tableGateway->update($data, array('id' => $id));

        return true;
    }

    public function outcomeMaterial($material, $outcome)
    {
        $count = $material->count - $outcome;

        if($count<0)
            return false;

        $data = array(
            'count' =>$count,
        );

        $id = (int)$material->id;
        $this->tableGateway->update($data, array('id' => $id));

        return true;
    }


    public function saveImage($id, $image)
    {
        $data = array(
            'image' => $image,
        );

        $this->tableGateway->update($data, array('id' => intval($id)));
    }

    public function deleteMaterial($id)
    {
        $this->tableGateway->delete(array('id' => (int)$id));
    }


    public function insertedMaterial()
    {
        return $this->tableGateway->lastInsertValue;
    }
}<file_sep><?php

namespace Mebel\Controller;

use Mebel\Form\LoginForm;
use Mebel\Model\SettingTable;
use Mebel\Model\UserTable;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class AdminController extends AbstractActionController
{

    protected $form;
    protected $storage;
    protected $authservice;
    protected $settingTable;
    protected $userTable;

    public function getAuthService()
    {
        if (!$this->authservice) {
            $this->authservice = $this->getServiceLocator()->get('AuthService');
        }
        return $this->authservice;
    }

    public function getSessionStorage()
    {
        if (!$this->storage) {
            $this->storage = $this->getServiceLocator()->get('Mebel\Model\AuthStorage');
        }
        return $this->storage;
    }

    public function getForm()
    {
        if (!$this->form) {
            $this->form = new LoginForm();
        }

        return $this->form;
    }

    public function loginAction()
    {
        //if already login, redirect to success page
        if ($this->getAuthService()->hasIdentity()) {
            $this->redirect()->toRoute('food', ['type' => 'pizza']);
        }

        $form = $this->getForm();

        $view = new ViewModel([
            'form' => $form,
            'messages' => $this->flashmessenger()->getMessages()
        ]);
        $view->setTerminal(true);

        return $view;
    }


    public function authenticateAction()
    {

        $form = $this->getForm();

        $request = $this->getRequest();
        if ($request->isPost()) {

//            fwrite(STDOUT, "test stop");

            $form->setData($request->getPost());
            if ($form->isValid()) {
                //check authentication...
                $this->getAuthService()->getAdapter()
                    ->setIdentity($request->getPost('email'))
                    ->setCredential($request->getPost('password'))
                    ->setCredentialTreatment('MD5(?)');

                $result = $this->getAuthService()->authenticate();
                foreach ($result->getMessages() as $message) {
                    //save message temporary into flashmessenger
                    $this->flashmessenger()->addMessage($message);
                }

                if ($result->isValid()) {

                    $resultRow = $this->getAuthService()->getAdapter()->getResultRowObject();

                    {
                        $this->getAuthService()->setStorage($this->getSessionStorage());
                        $this->getAuthService()->getStorage()->write([
                            'id' => $resultRow->id,
                            'fio' => $resultRow->fio,
                            'email' => $resultRow->email,
                            'phone' => $resultRow->phone,
                            'role' => $resultRow->role,
                            'address' => $resultRow->address,
                        ]);

                        return $this->redirect()->toRoute('transaction', ['type' => 'all']);
                    }
                }
            }
        }

        return $this->redirect()->toRoute('login');

    }

    public function menuAction()
    {
        if (!$this->getServiceLocator()->get('AuthService')->hasIdentity()) {
            return $this->redirect()->toRoute('login');
        }

        $config = $this->getServiceLocator()->get('config');
        $menuArray =  $config['menu'];

        $setting= $this->getSettingTable()->getSettingByName('menu');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $menus = $request->getPost('menu', []);
            $setting->value = implode(';', $menus);
            $this->getSettingTable()->saveSetting($setting);
        }

        $view = new ViewModel([
            'menu' => $menuArray,
            'menustr' => $setting->value,
        ]);

        return $view;

    }


    public function passwordAction()
    {
        /*var_dump(md5('admin'));  21232f297a57a5a743894a0e4a801fc3 */
        $id = (int)$this->getAuthService()->getStorage()->read()['id'];

        $user = $this->getUserTable()->getUser($id);

        $error = '';
        $success = '';
        $request = $this->getRequest();
        if ($request->isPost()) {
            $password = $request->getPost('password');
            $newpassword = $request->getPost('newpassword');
            $repassword = $request->getPost('repassword');

            if(md5($password)!= $user->password) {
                $error = 'Не правельно ввели текущий пароль!!!';
                goto metka;
            }

            if($newpassword!= $repassword) {
                $error = 'Пароль который ввели не совпадают!!!';
                goto metka;
            }

            if(strlen($newpassword)<6) {
                $error = 'Длина пароля должна быть не меньше шести символов!!!';
                goto metka;
            }

            if(empty($newpassword)) {
                $error = 'Нельзя установить пустой пароль!!!';
                goto metka;
            }



            if (empty($error)) {
                $newpasswordHash = md5($newpassword);
                $this->getUserTable()->changePassword($id, $newpasswordHash);
                $success = 'Ваш пароль успешно обнавлен';
            }

        }


        metka:


        $view = new ViewModel([
                'id' => $user->id,
                'title' => 'Сменить пароль  пользователя '.$user->email.',  '.$user->fio,
                'success' => $success,
                'error' => $error,
            ]
        );
        return $view;
    }



    public function indexAction()
    {
        if (!$this->getServiceLocator()->get('AuthService')->hasIdentity()) {
            return $this->redirect()->toRoute('login');
        }

        return $this->redirect()->toRoute('material');
    }


    public function logoutAction()
    {
        $this->getSessionStorage()->forgetMe();
        $this->getAuthService()->clearIdentity();

        //$this->flashmessenger()->addMessage("Вы вышли из системы");

        return $this->redirect()->toRoute('login');
    }


    /**
     * @return UserTable
     */
    public function getUserTable()
    {
        if (!$this->userTable) {
            $sm = $this->getServiceLocator();
            $this->userTable = $sm->get('UserTable');
        }
        return $this->userTable;
    }

    /**
     * @return SettingTable
     */
    public function getSettingTable()
    {
        if (!$this->settingTable) {
            $sm = $this->getServiceLocator();
            $this->settingTable = $sm->get('SettingTable');
        }
        return $this->settingTable;
    }

}<file_sep><?php

namespace Mebel\Controller;

use Mebel\Form\RateForm;
use Mebel\Model\Rate;
use Mebel\Model\RateTable;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;

class RateController extends AbstractActionController
{
    protected $rateTable;

    public function indexAction()
    {
        if (!$this->getServiceLocator()->get('AuthService')->hasIdentity()) {
            return $this->redirect()->toRoute('login');
        }

        $view = new ViewModel(array(
            'info' => $this->getServiceLocator()->get('AuthService')->getStorage(),
        ));

        return $view;
    }


    public function ajaxAction(){

        $request = $this->getRequest();
        $current = $request->getPost('current', 1); ;
        $rowCount = $request->getPost('rowCount', 10);
        $sort = $request->getPost('sort');
        $sortField = key($sort);
        $sortType = $sort[$sortField];
        $searchPhrase = $request->getPost('searchPhrase');

        $offset = intval($rowCount) * (intval($current)-1);
        $rates= $this->getRateTable()->fetchPage(intval($rowCount), $offset, $sortField.' '.$sortType, $searchPhrase);
        $count= $this->getRateTable()->getCount();

        return new JsonModel(array(
            'current' => intval($current),
            'rowCount' => intval($rowCount),
            'rows' => $rates->toArray(),
            "total"=> $count,
        ));
    }

    public function oneAction(){
        $id = (int)$this->params()->fromRoute('id');

        $rate= $this->getRateTable()->getRate($id);

        return new JsonModel($rate->getArrayCopy());
    }

    public function deleteAction()
    {
        $id = (int)$this->params()->fromRoute('id');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $del = $request->getPost('del', 'No');

            if ($del == 'Удалить') {
                $id = (int)$request->getPost('id');
                $this->getRateTable()->deleteRate($id);
            }

            return $this->redirect()->toRoute('rate');
        }

        $rate = $this->getRateTable()->getRate($id);


        $view = new ViewModel([
                'id' => $rate->id,
                'title' => 'Тарифті өшіру '.$rate->description,
                'description' => $rate->payment.'/'.$rate->amount,
                'url' => $this->url()->fromRoute('rate',['action' => 'delete', 'id' => $rate->id])
            ]
        );
        $view->setTemplate('mebel/admin/delete.phtml');
        return $view;
    }



    public function editAction()
    {
        $id = (int) $this->params()->fromRoute('id', 0);

        if($id){
            $rate = $this->getRateTable()->getRate($id);
        }
        else
            $rate = new Rate();


        $form  = new RateForm();
        $form->bind($rate);


        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $this->getRateTable()->saveRate($rate);
                $this->flashMessenger()->addSuccessMessage('Сәтті сақталды');

                if(empty($id))
                    $id = $this->getRateTable()->insertedRate();

                $this->redirect()->toRoute('rate', ['action' => 'edit', 'id' => $id]);
            }else {
                $this->flashMessenger()->addErrorMessage('Енгізуде қате бар');
                $form->highlightErrorElements();
            }
        }


        $view = new ViewModel([
            'form' => $form,
            'id' => $id,
        ]);
        return $view;
    }

    /**
     * @return RateTable
     */
    public function getRateTable()
    {
        if (!$this->rateTable) {
            $sm = $this->getServiceLocator();
            $this->rateTable = $sm->get('RateTable');
        }
        return $this->rateTable;
    }




}<file_sep><?php
namespace Mebel\Form;

use Zend\Db\Adapter\AdapterInterface;
use Zend\Form\Form;
use Zend\InputFilter\Factory;
use Zend\InputFilter\InputFilter;

class WorkForm extends Form
{
    protected $adapter;

    public function __construct(AdapterInterface $dbAdapter, $count)
    {
        $this->adapter =$dbAdapter;

        parent::__construct('work');

        $inputFilter = new InputFilter();
        $factory = new Factory();

        $this->add(array(
            'name' => 'id',
            'type' => 'Hidden',
        ));

        $this->add(array(
            'name' => 'rate',
            'type' => 'Select',
            'attributes' => array(
                'class' => 'form-control',
                'required' => 'required',
                'multiple' => 'multiple'

            ),
            'options' => array(
                'label' => 'Тариф',
                'label_attributes' => ['class' => 'control-label col-md-2'],
                'value_options' => $this->getRate(),
            ),
        ));

        $this->add(array(
            'name' => 'worker',
            'type' => 'Select',
            'attributes' => array(
                'class' => 'form-control',
                'required' => 'required',
            ),
            'options' => array(
                'label' => 'Жұмысшы',
                'label_attributes' => ['class' => 'control-label col-md-2'],
                'empty_option' => 'Жұмысшы таңдаңыз',
                'value_options' => $this->getWorker(),
            ),
        ));

        $inputFilter->add($factory->createInput([
            'name' => 'worker',
            'required' => true,
        ]));


        $this->add([
            'name' => 'total',
            'required' => true,
            'type' => 'Number',
            'attributes' => [
                'class' => 'form-control',
                'placeholder' => 'Жалпы төленетін сома(тенге)',
                'min' => '0',
                'step' => '0.01',
                'required' => 'required',
                'readonly' => 'readonly'
            ],
            'options' => [
                'label' => 'Жалпы төленетін сома(тенге)',
                'label_attributes' => ['class' => 'control-label col-md-2']
            ],
        ]);


        $inputFilter->add($factory->createInput([
            'name' => 'total',
            'required' => true,
        ]));

        $this->add([
            'name' => 'workdate',
            'type' => 'Date',
            'attributes' => [
                'class' => 'form-control',
            ],
            'options' => [
                'label' => 'Дата выполнения работы',
                'label_attributes' => ['class' => 'control-label col-md-2'],
            ],
        ]);


        $inputFilter->add($factory->createInput([
            'name'     => 'workdate',
            'required' => true
        ]));


        $this->add(array(
            'type' => 'Zend\Form\Element\Collection',
            'name' => 'workdones',
            'options' => array(
                'count' => $count,
                'should_create_template' => true,
                'allow_add' => true,
                'template_placeholder' => '__workdones_count__',
                'target_element' => array(
                    'type' => 'Mebel\Form\WorkdoneFieldset',
                ),
            ),
        ));


/*        $this->add(array(
            'type' => 'Zend\Form\Element\Csrf',
            'name' => 'csrf'
        ));*/



        $this->add([
            'name' => 'submit',
            'type' => 'Submit',
            'attributes' => [
                'value' => 'Сақтау',
                'id' => 'submitbutton',
                'class' => 'btn btn-success pull-right'
            ],
        ]);

        $this->setInputFilter($inputFilter);

    }

    public function highlightErrorElements()
    {
        foreach ($this->getElements() as $element) {
            if ($element->getMessages()) {
                $element->setAttribute('style', 'border-color:#a94442; box-shadow:inset 0 1px 1px rgba(0,0,0,.075);');
                $element->setLabelAttributes(array(
                    'class' => 'control-label col-xs-2',
                    'style' => 'color:#a94442'));
            }
        }
    }


    public function getWorker()
    {

        $dbAdapter = $this->adapter;
        $sql       = "SELECT id, fio FROM worker ORDER BY fio ASC";
        $statement = $dbAdapter->query($sql);
        $result    = $statement->execute();

        $selectData = [];

        foreach ($result as $res) {
            $selectData[$res['id']] = $res['fio'];
        }
        return $selectData;
    }

    public function getRate()
    {

        $dbAdapter = $this->adapter;
        $sql       = "SELECT id, description, payment, amount, metrik FROM rate ORDER BY id ASC";
        $statement = $dbAdapter->query($sql);
        $result    = $statement->execute();

        $selectData = [];

        foreach ($result as $res) {
            $selectData[$res['id']] = $res['description'].', төлемі '.$res['payment'].' тенге / '.$res['amount'].' '.$res['metrik'];
        }
        return $selectData;
    }


}<file_sep><?php
namespace Mebel\Model;

use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Sql;
use Zend\Db\TableGateway\TableGateway;

class RateTable
{
    protected $tableGateway;

    public static $tableName = 'rate';

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    public function fetchAll()
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }

    public function fetchPage($rowCount, $offset, $orderby, $searchPhrase)
    {

        $sql = new Sql($this->tableGateway->adapter);
        $select = $sql->select();
        $select->from($this->tableGateway->table);

        $select->columns(['*']);

        if ($rowCount < 0)
            $select->offset(0);
        else
            $select->limit($rowCount)->offset($offset);
        $select->order($orderby);
        $select->order('date desc');


        if ($searchPhrase) {
            $select->where->NEST->like('description', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->OR->like('payment', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->OR->like('amount', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->OR->like('metrik', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->UNNEST;
        }

        $statement = $sql->prepareStatementForSqlObject($select);
        $result = $statement->execute();

        $resultSet = new ResultSet();
        $resultSet->initialize($result);

        return $resultSet;
    }


    public function getCount()
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet->count();
    }

    public function getRate($id)
    {
        $id = (int)$id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }

    public function saveRate(Rate $rate)
    {
        $data = array(
            'description' => $rate->description,
            'payment' => $rate->payment,
            'amount' => $rate->amount,
            'metrik' => $rate->metrik,
        );

        $id = (int)$rate->id;
        if ($id == 0) {
            $this->tableGateway->insert($data);
        } else {
            if ($this->getRate($id)) {
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('Rate_id does not exist');
            }
        }
    }

    public function deleteRate($id)
    {
        $this->tableGateway->delete(array('id' => (int)$id));
    }


    public function insertedRate()
    {
        return $this->tableGateway->lastInsertValue;
    }
}<file_sep><?php

namespace Mebel\Model;

class Material
{
    public $id;
    public $type;
    public $name;
    public $description;
    public $wholesale;
    public $retail;
    public $count;
    public $image;
    public $date;

    public function exchangeArray($data)
    {
        $this->id = (!is_null($data['id'])) ? $data['id'] : null;
        $this->type = (!is_null($data['type'])) ? $data['type'] : null;
        $this->name = (!is_null($data['name'])) ? $data['name'] : null;
        $this->description = (!is_null($data['description'])) ? $data['description'] : null;
        $this->wholesale = (!is_null($data['wholesale'])) ? $data['wholesale'] : 0;
        $this->retail = (!is_null($data['retail'])) ? $data['retail'] : 0;
        $this->count = (!is_null($data['count'])) ? $data['count'] : 0;
        $this->image = (!empty($data['image'])) ? $data['image'] : null;
        $this->date = (!empty($data['date'])) ? $data['date'] : null;
    }

    public function getArrayCopy()
    {
        return get_object_vars($this);
    }


}<file_sep>CREATE TABLE `rate` (
  `id`          INT(10) UNSIGNED NOT NULL         AUTO_INCREMENT,
  `description` TEXT,
  `payment`     FLOAT            NOT NULL         DEFAULT 0,
  `amount`      FLOAT            NOT NULL         DEFAULT 1,
  `metrik`      VARCHAR(255)     NOT NULL,
  `date`        TIMESTAMP         NOT NULL         DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
)
  ENGINE = InnoDB;
<file_sep>CREATE TABLE `transaction` (
  `id`          INT(10) UNSIGNED NOT NULL         AUTO_INCREMENT,
  `type`        VARCHAR(50)      NOT NULL,
  `description` TEXT,
  `material`    INT(10) UNSIGNED NOT NULL,
  `quantity`    INT(11)          NOT NULL         DEFAULT 0,
  `sum`         FLOAT            NOT NULL         DEFAULT 0,
  `tarif`       FLOAT            NOT NULL         DEFAULT 0,
  `isWholesale` INT(11)          NOT NULL         DEFAULT 0,
  `isIncome`    INT(11)          NOT NULL         DEFAULT 0,
  `date`        TIMESTAMP         NOT NULL         DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  INDEX `FK1_material` (`material`),
  CONSTRAINT `FK1_material` FOREIGN KEY (`material`) REFERENCES `material` (`id`)
)
  ENGINE = InnoDB;
<file_sep><?php
namespace Mebel\Model;

use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Sql;
use Zend\Db\TableGateway\TableGateway;

class WorkTable
{
    protected $tableGateway;

    public static $tableName = 'work';

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    public function fetchAll()
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }

    public function fetchPage($rowCount, $offset, $orderby, $searchPhrase)
    {

        $sql = new Sql($this->tableGateway->adapter);
        $select = $sql->select();
        $select->from($this->tableGateway->table);

        $select->columns(['*']);
        $select->join('worker', 'work.worker = worker.id', ['fio'], Select::JOIN_LEFT);

        if ($rowCount < 0)
            $select->offset(0);
        else
            $select->limit($rowCount)->offset($offset);
        $select->order($orderby);
        $select->order('date desc');


        if ($searchPhrase) {
            $select->where->NEST
                ->OR->like('total', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->OR->like('fio', '%' . mb_strtolower($searchPhrase, 'UTF-8') . '%')
                ->UNNEST;
        }

        $statement = $sql->prepareStatementForSqlObject($select);
        $result = $statement->execute();

        $resultSet = new ResultSet();
        $resultSet->initialize($result);

        return $resultSet;
    }


    public function getCount()
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet->count();
    }

    /**
     * @param $id
     * @return Work
     * @throws \Exception
     */
    public function getWork($id)
    {
        $id = (int)$id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }

    public function saveWork(Work $work)
    {
        $data = array(
            'worker' => $work->worker,
            'total' => $work->total,
            'workdate' => $work->workdate,
        );

        $id = (int)$work->id;
        if ($id == 0) {
            $this->tableGateway->insert($data);
        } else {
            if ($this->getWork($id)) {
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('Work_id does not exist');
            }
        }
    }

    public function deleteWork($id)
    {
        $this->tableGateway->delete(array('id' => (int)$id));
    }


    public function insertedWork()
    {
        return $this->tableGateway->lastInsertValue;
    }
}