1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 
<?php

/* --------------------------------------------------------------
   QuickEditProductSpecialPricesReader.inc.php 2017-04-03
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2017 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/

/**
 * Class QuickEditProductSpecialPricesReader
 *
 * @category   System
 * @package    QuickEdit
 * @subpackage Repositories
 */
class QuickEditProductSpecialPricesReader implements QuickEditProductSpecialPricesReaderInterface
{
    /**
     * @var CI_DB_query_builder
     */
    protected $db;
    
    /**
     * @var string
     */
    protected $brutto;
    
    /**
     * @var QuickEditSpecialPricesOverviewColumns
     */
    protected $quickEditSpecialPricesOverviewColumns;
    
    
    /**
     * QuickEditProductsSpecialPriceReader constructor.
     *
     * @param CI_DB_query_builder                   $db                                    Database query builder
     *                                                                                     instance.
     * @param QuickEditSpecialPricesOverviewColumns $quickEditSpecialPricesOverviewColumns QuickEdit special price
     *                                                                                     overview columns
     */
    public function __construct(CI_DB_query_builder $db,
                                QuickEditSpecialPricesOverviewColumns $quickEditSpecialPricesOverviewColumns)
    {
        $this->db                                    = $db;
        $this->quickEditSpecialPricesOverviewColumns = $quickEditSpecialPricesOverviewColumns;
        
        if(PRICE_IS_BRUTTO === 'true')
        {
            $this->brutto = ' / (1 + (`tax_rates`.`tax_rate` / 100))';
        }
    }
    
    
    /**
     * Returns the special prices of the indicated products.
     *
     * @param array $productIds       Array containing the product IDs to be processed.
     * @param array $filterParameters Contains filter parameters.
     *
     * @return array Returns the query result as a pure array, or an empty array when no result is produced.
     */
    public function getFilteredSpecialPrices(array $productIds, array $filterParameters)
    {
        $this->_join();
        $specialPriceOverviewColumns = $this->_delegateFilterToColumn();
        
        foreach($filterParameters as $column => $value)
        {
            $value = preg_replace('/[^\w\s-+<>*.,"\']/', '', $value);
            $valueWithoutLetters = preg_replace('/\D/', '', $value);
            
            if(($column === 'specialPrice' || $column === 'productsPrice') && empty($valueWithoutLetters))
            {
                return [];
            }
            
            if(is_array($value))
            {
                $this->_addSqlWhereGroupCondition($specialPriceOverviewColumns[$column], $value);
                
                continue;
            }
            
            if(strpos($value, '<') === 0 || strpos($value, '>') >= 1)
            {
                $this->_addSqlWhereLessThanCondition($specialPriceOverviewColumns[$column], $value);
                
                continue;
            }
            
            if(strpos($value, '>') === 0 || strpos($value, '<') >= 1)
            {
                $this->_addSqlWhereMoreThanCondition($specialPriceOverviewColumns[$column], $value);
                
                continue;
            }
            
            if(strpos($value, '*') !== false)
            {
                $this->_addSqlWhereLikeCondition($specialPriceOverviewColumns[$column], $value);
                
                continue;
            }
            
            $this->_addSqlWhereCondition($specialPriceOverviewColumns[$column], $value);
        }
        
        return $this->db->select($this->_columns())
                        ->where_in('products.products_id', $productIds)
                        ->group_by('products.products_id')
                        ->get('products')
                        ->result_array();
    }
    
    
    /**
     * Returns the record number of the filtered special prices.
     *
     * @param array $productIds       Array containing the product IDs to be processed.
     * @param array $filterParameters Contains filter parameters.
     *
     * @return int Returns the number of special prices found.
     */
    public function getFilteredSpecialPricesCount(array $productIds, array $filterParameters)
    {
        return count($this->getFilteredSpecialPrices($productIds, $filterParameters));
    }
    
    
    /**
     * Get special prices record count.
     *
     * @return int Returns the number of all special prices found.
     */
    public function getSpecialPricesCount()
    {
        return (int)$this->db->count_all('specials');
    }
    
    
    /**
     * Sets the starting point of the pagination and the number of products.
     *
     * @param IntType|null $start  Starting point.
     * @param IntType|null $length Number of products.
     *
     * @return QuickEditProductSpecialPricesReaderInterface Returns same instance for chained method calls.
     */
    public function paginateSpecialPrices(IntType $start = null, IntType $length = null)
    {
        $this->db->limit($length->asInt(), $start->asInt());
        
        return $this;
    }
    
    
    /**
     * Sets the sorting order of the products.
     *
     * @param StringType|null $orderBy Sorting order (ASC or DESC)
     *
     * @return QuickEditProductSpecialPricesReaderInterface Returns same instance for chained method calls.
     */
    public function sortSpecialPrices(StringType $orderBy = null)
    {
        $this->db->order_by($orderBy->asString());
        
        return $this;
    }
    
    
    /**
     * Specifies the where conditions for the database query
     *
     * @param $column Column.
     * @param $value  Value.
     */
    protected function _addSqlWhereCondition($column, $value)
    {
        if($column === 'specials.specials_new_products_price' || $column === 'products.products_price')
        {
            $this->_addSqlWhereRoundCondition($column, $value);
            
            return;
        }
        
        if($column === 'specials.expires_date')
        {
            $this->_addSqlWhereDateCondition($column, $value);
            
            return;
        }
        
        $this->db->where($column, $value);
    }
    
    
    /**
     * Starts and ends a group expression with 'where' condition in conjunction with a round function.
     *
     * @param $column Column.
     * @param $value  Value.
     */
    protected function _addSqlWhereRoundCondition($column, $value)
    {
        $this->db->where($column . ' = ROUND(' . $value . $this->brutto . ', 4)');
    }
    
    
    /**
     * Sets the 'where date' condition.
     *
     * @param       $column Column.
     * @param array $value  Value.
     */
    protected function _addSqlWhereDateCondition($column, $value)
    {
        $dateFormat = ($_SESSION['language_code'] === 'de') ? 'd.m.y' : 'm.d.y';
        $dateValue  = DateTime::createFromFormat($dateFormat, $value);
        
        $this->db->where($column, $dateValue->format('Y-m-d'));
    }
    
    
    /**
     * Starts and ends a group expression with 'where group' condition.
     *
     * @param       $column Column.
     * @param array $value  Value.
     */
    protected function _addSqlWhereGroupCondition($column, array $value)
    {
        if($column === 'specials.expires_date')
        {
            $this->_addSqlWhereBetweenCondition($column, $value);
            
            return;
        }
        
        $this->db->group_start()->where($column, array_shift($value));
        
        foreach($value as $item)
        {
            $this->db->or_where($column, $item);
        }
        
        $this->db->group_end();
    }
    
    
    /**
     * Starts and ends a group expression with 'like' condition.
     *
     * @param $column Column.
     * @param $value  Value.
     */
    protected function _addSqlWhereLikeCondition($column, $value)
    {
        $this->db->where($column . ' LIKE ', str_replace('*', '%', $value));
    }
    
    
    /**
     * Starts and ends a group expression with 'where between' condition.
     *
     * @param       $column Column.
     * @param array $value  Value.
     */
    protected function _addSqlWhereBetweenCondition($column, array $value)
    {
        $value = str_replace(['<', '>'], '', $value);
        
        if($column === 'specials.specials_new_products_price' || $column === 'products.products_price')
        {
            $this->db->group_start()->where($column . ' >= ROUND(' . reset($value) . $this->brutto . ', 4)');
            $this->db->where($column . ' <= ROUND(' . end($value) . $this->brutto . ', 4)');
            $this->db->group_end();
            
            return;
        }
        
        if($column === 'specials.expires_date')
        {
            $dateFormat     = ($_SESSION['language_code'] === 'de') ? 'd.m.y' : 'm.d.y';
            $dateStartValue = DateTime::createFromFormat($dateFormat, reset($value));
            $dateEndValue   = DateTime::createFromFormat($dateFormat, end($value));
            
            $this->db->where($column . ' >=', $dateStartValue->format('Y-m-d 00:00:00'));
            $this->db->where($column . ' <=', $dateEndValue->format('Y-m-d 23:59:59'));
            
            return;
        }
        
        $this->db->where($column . ' >= ' . reset($value));
        $this->db->where($column . ' <= ' . end($value));
    }
    
    
    /**
     * Starts and ends a group expression with 'less than' condition.
     *
     * @param $column Column.
     * @param $value  Value.
     */
    protected function _addSqlWhereLessThanCondition($column, $value)
    {
        $value = str_replace(['<', '>'], '', $value);
        
        if($column === 'specials.specials_new_products_price' || $column === 'products.products_price')
        {
            $this->db->where($column . ' < ROUND(' . $value . $this->brutto . ', 4)');
            
            return;
        }
        
        $this->db->where($column . ' < ', $value);
    }
    
    
    /**
     * Starts and ends a group expression with 'more than' condition.
     *
     * @param $column Column.
     * @param $value  Value.
     */
    protected function _addSqlWhereMoreThanCondition($column, $value)
    {
        $value = str_replace(['<', '>'], '', $value);
        
        if($column === 'specials.specials_new_products_price' || $column === 'products.products_price')
        {
            $this->db->where($column . ' > ROUND(' . $value . $this->brutto . ', 4)');
            
            return;
        }
        
        $this->db->where($column . ' > ', $value);
    }
    
    
    /**
     * Provides required columns.
     *
     * @return array Returns an array of the required columns.
     */
    protected function _columns()
    {
        $specialPriceOverviewColumns = [];
        
        foreach($this->quickEditSpecialPricesOverviewColumns->serializeColumns() as $columns)
        {
            $specialPriceOverviewColumns[] = $columns['field'];
        }
        
        return array_merge($specialPriceOverviewColumns, $this->_addAdditionalColumns());
    }
    
    
    /**
     * Specifies the database relationships.
     */
    protected function _join()
    {
        $this->db->join('specials', 'specials.products_id = products.products_id', 'left');
        $this->db->join('products_description', 'products_description.products_id = products.products_id');
        $this->db->join('languages', 'languages.languages_id = ' . $_SESSION['languages_id']);
        $this->db->join('zones_to_geo_zones', 'zones_to_geo_zones.zone_country_id = ' . (int)STORE_COUNTRY);
        $this->db->join('tax_rates',
                        'tax_rates.tax_class_id = products.products_tax_class_id AND tax_rates.tax_zone_id = zones_to_geo_zones.geo_zone_id',
                        'left');
        
        $this->db->where('products_description.language_id = languages.languages_id');
    }
    
    
    /**
     * Returns the required columns for the overview of the properties.
     *
     * @return array Returns an array of the required columns for the overview of the properties.
     */
    protected function _delegateFilterToColumn()
    {
        $specialPriceOverviewColumns = [];
        
        foreach($this->quickEditSpecialPricesOverviewColumns->serializeColumns() as $columns)
        {
            $specialPriceOverviewColumns[$columns['name']] = $columns['field'];
        }
        
        return $specialPriceOverviewColumns;
    }
    
    
    /**
     * Provides additionally required columns.
     *
     * @return array Returns an array of the additional columns.
     */
    protected function _addAdditionalColumns()
    {
        return [
            'products.products_id',
            'tax_rates.tax_rate',
        ];
    }
}