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

    class pjModifyPriceModel extends pjAppModel
    {
        const TYPE_INCREASE = 'increase';
        const TYPE_DECREASE = 'decrease';
        const APPLY_TO_DEFAULT = 'default';
        const APPLY_TO_CUSTOM = 'custom';
        const APPLY_TO_BOTH = 'both';

        /**
         * The name of table's primary key. If PK is over 2 or more columns set this to boolean null
         *
         * @var string
         * @access public
         */
        var $primaryKey = 'id';

        /**
         * The name of table associate with current model
         *
         * @var string
         * @access protected
         */
        var $table = 'modify_prices';

        /**
         * Table schema
         *
         * @var array
         * @access protected
         */
        protected $schema = array(
            array('name' => 'id', 'type' => 'int', 'default' => ':NULL'),
            array('name' => 'date_from', 'type' => 'date', 'default' => ':NULL'),
            array('name' => 'date_to', 'type' => 'date', 'default' => ':NULL'),
            array('name' => 'percent', 'type' => 'int', 'default' => ':NULL'),
            array('name' => 'type', 'type' => 'enum', 'default' => ':NULL'),
            array('name' => 'apply_to', 'type' => 'enum', 'default' => self::APPLY_TO_BOTH)
        );

        protected $validate = array();

        public $i18n = array();

        public static function factory($attr = array())
        {
            return new self($attr);
        }

        /**
         * Get modify price
         *
         * @param string $dateFrom Y-m-d
         * @param string $dateTo Y-m-d
         * @param int $locationId
         * @param int $typeId
         * @param string $applyTo Default is BOTH.
         *
         * @return array
         * @throws Exception
         */
        public function get($dateFrom, $dateTo, $locationId, $typeId, $applyTo = self::APPLY_TO_BOTH)
        {
            $price = $this->reset()
                ->join('pjModifyPriceType', 't2.modify_price_id = t1.id')
                ->join('pjModifyPriceLocation', 't3.modify_price_id = t1.id')
                ->where('t1.date_from <=', $dateFrom)
                ->where('t1.date_to >=', $dateTo)
                ->where('(t3.location_id = ' . $locationId . ' OR t3.location_id = 0)')
                ->where('(t2.type_id = ' . $typeId . ' OR t2.type_id = 0)')
                ->where('(t1.apply_to = "' . $applyTo . '" OR t1.apply_to = "' . self::APPLY_TO_BOTH . '")')
                ->findAll()
                ->getDataIndex(0);

            return $price;
        }
    }

?>