<?php
namespace Application\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;

/**
 * Class Modalita
 * @package Application\Model
 */
class Modalita
{
    const TABLE = 'ec_modalita';

    /**
     * @var \Zend\Db\Adapter\Adapter
     */
    public $adapter;

    /**
     * @var \Zend\Db\Sql\Sql
     */
    public $sql;

    /**
     * @var array
     */
    protected $_whitelist = array(
        'codice',
        'nome'
    );

    /**
     * @param Adapter $adapter
     */
    public function __construct(Adapter $adapter)
    {
        $this->adapter = $adapter;
        $this->sql     = new Sql($adapter);
    }

    /**
     * @param array $data
     * @return mixed|null
     */
    public function insert($data = array())
    {
        $values = array_intersect_key($data, array_flip($this->_whitelist));
        $insert = $this->sql->insert(self::TABLE);
        $insert->values($values);
        $statement = $this->sql->prepareStatementForSqlObject($insert);

        return $statement->execute()->getGeneratedValue();
    }

    /**
     * @param int $id
     * @param array $values
     * @return mixed|null
     */
    public function update($id = 0, $values = array())
    {
        $where = new Where();
        $where->equalTo('id', (int)$id);
        $values = array_intersect_key($values, array_flip($this->_whitelist));
        $update = $this->sql->update(self::TABLE);
        $update->set($values)->where($where);
        $statement = $this->sql->prepareStatementForSqlObject($update);

        return $statement->execute()->getGeneratedValue();
    }

    /**
     * @param int $id
     * @return \Zend\Db\Adapter\Driver\ResultInterface
     */
    public function delete($id = 0)
    {
        $delete = $this->sql->delete(self::TABLE);
        $delete->where(array(
            'id' => $id
        ));
        $deleteStatement = $this->sql->prepareStatementForSqlObject($delete);

        return $deleteStatement->execute();
    }

    /**
     * @param array $filterBy
     * @return mixed
     */
    public function findEqual($filterBy = array())
    {
        $select = $this->sql->select();
        $select->from(self::TABLE)->where($filterBy);

        $statement = $this->sql->prepareStatementForSqlObject($select);

        return $statement->execute()->current();
    }

    /**
     * @return \Zend\Db\Adapter\Driver\ResultInterface
     */
    public function full()
    {
        $select = $this->sql->select();
        $select->from(self::TABLE);
        $select->order('id ASC');
        $statement = $this->sql->prepareStatementForSqlObject($select);
        $dataset   = $statement->execute();

        return $dataset;
    }


}
