<?php

/******************************************************************************
 *
 *	PROJECT: Flynax Classifieds Software
 *	VERSION: 4.5.2
 *	LISENSE: FL4HLD2A8696 - http://www.flynax.com/license-agreement.html
 *	PRODUCT: Real Estate Agency
 *	DOMAIN: gevimmo.com
 *	FILE: RLPRICEHISTORY.CLASS.PHP
 *
 *	This script is a commercial software and any kind of using it must be 
 *	coordinate with Flynax Owners Team and be agree to Flynax License Agreement
 *
 *	This block may not be removed from this file or any other files with out 
 *	permission of Flynax respective owners.
 *
 *	Copyrights Flynax Classifieds Software | 2017
 *	http://www.flynax.com/
 *
 ******************************************************************************/

class rlPriceHistory extends reefless
{
    /**
    * get price history
    *
    * @return array - price history array
    **/
    public function getPriceHistory()
    {
        global $lang, $config, $listing, $listing_id, $aHooks;

        $this->loadClass('Valid');

        $sql = "SELECT * FROM `" . RL_DBPREFIX . "price_history` WHERE `Listing_id` = {$listing_id}";
        $price_history_array = $this->getAll($sql);
        $data = array();
        $listing_fields = array();

        foreach ($listing as $group => $gr_value) {
            foreach ($gr_value['Fields'] as $field_key => $field) {
                $listing_fields[$field_key] = $field;
            }
        }

        foreach ($price_history_array as $key => $value) {
            $price_array = explode("|", $value['Price']);
            $current_price = $price_array[0];
            $currency = $price_array[1] ? $lang['data_formats+name+' . $price_array[1]] : '';

            $tmp_price_array['Price'] = $current_price;
            $price_string = $GLOBALS['rlValid']->str2money($current_price);
            if ($config['system_currency_position'] == 'before') {
                $tmp_price_array['Price_value'] = $currency . " " .  $price_string;
            } else {
                $tmp_price_array['Price_value'] = $price_string . " " . $currency;
            }
            $tmp_price_array['Date'] = date('Y/m/d', strtotime($value['Date']));
            $tmp_price_array['Event'] = $lang['ph_listed_for_sale'];
    
            if ($config['ph_sqft_enable']) {
                if ($config['square_feet_price_key']) {
                    $tmp_price_array['square_feet_price'] = $listing_fields[$config['square_feet_price_key']]['value'];
                } else {
                    $square_feet_tag = $config['square_feet_key'] ?: 'square_feet';
                    if ($listing_fields[$square_feet_tag]) {
                        if ($listing_fields[$square_feet_tag]['Type'] == 'mixed') {
                            $square_feet_source = explode('|', $listing_fields[$square_feet_tag]['source'][0]);
                            $square_feet_price = round($current_price / $square_feet_source[0], 3);
                            $tmp_price_array['square_feet_price'] = $square_feet_price;
                        }
                    } else {
                        $tmp_price_array['square_feet_price'] = "--";
                    }
                }
            } 


            if (isset($prev_key)) {
                $prev_price_array = explode("|", $price_history_array[$prev_key]['Price']);
                $prev_price = $prev_price_array[0];
                $prev_currency = $prev_price_array[1] ? $lang['data_formats+name+' . $prev_price_array[1]] : '';

                if ($prev_currency != $currency && $aHooks['currencyConverter']) {
                    $price_history_exist = $this->getOne('ID', "`Key` = 'price_history'", 'plugins');
                    $currency_rate = $this->getOne('Rate', "`Key` = '" . $price_array[1] . "'", 'currency_rate');
                    $converted_price = $current_price / $currency_rate;
                    $current_price = round($converted_price, 2);

                } else {
                    if ($prev_price != $current_price) {
                        if ($current_price > $prev_price) {
                            $tmp_price_array['price_diff_class'] = 'increase';
                            $diff = $current_price - $prev_price;
                        }
                        if ($current_price < $prev_price) {
                            $tmp_price_array['price_diff_class'] = 'reduce';
                            $diff = $prev_price - $current_price;
                        }
                    }
                }
                $tmp_price_array['tmp_price'] = $current_price;
                $tmp_price_array['price_diff'] = $diff;
                $price_percent = round(($diff * 100) / $prev_price, 1);
                $tmp_price_array['precent_diff'] = $price_percent;
                $tmp_price_array['Event'] = $lang['ph_price_changed'];
            }

            $data[$key] = $tmp_price_array;
            $prev_key = $key;
        }
        return $data;
    }

    /**
    * Edit some price history row
    *
    * @param array $ph_array - array of editing pricehistory row from the Admin panel 
    * @return void 
    **/
    public function apEditPriceHistory($ph_array)
    {
        global $listing_id;

        $this->loadClass('Actions');

        $insertData = array();
        $updateData = array();

        foreach ($ph_array as $ph_key => $ph_val) {
            if ($ph_val['id']) {
                $updateData['Price'] = $ph_val['price'] . "|" . $ph_val['ccode'];
                $updateData['Date'] = $ph_val['ph_data'];
                $updateData['Listing_id'] = $listing_id;
                
                if (function_exists($this->getClientIpAddress())) {
                    $updateData['IP'] = $this->getClientIpAddress();
                } else {
                    $updateData['IP'] = $_SERVER['REMOTE_ADDR'];
                }

                $update_price_history = array(
                    'fields' => $updateData,
                    'where' => array(
                        'ID' => $ph_val['id']
                    ),
                );
                $GLOBALS['rlActions']->updateOne($update_price_history, 'price_history');
            } else {
                $insertData['Price'] = $ph_val['price'] . "|" . $ph_val['ccode'];
                $insertData['Date'] = $ph_val['ph_data'];
                $insertData['Listing_id'] = $listing_id;
                $insertData['IP'] = $this->getClientIpAddress();
                $GLOBALS['rlActions']->insertOne($insertData, 'price_history');
            }
        }
    }

    /**
     * Remove price history row from admin panel
     * 
     * @param $id - id of the pricehistory record in database 
     * @param $row_id - count of the row in the price history grid (AP)
     * @return $_respoinse 
     */
    public function ajaxDeletePriceHistory($id = false, $row_id)
    {
        global $_response;

        $id = (int) $id;

        if (!$id) {
            return $_response;
        }
        // delete price history row
        $this->query("DELETE FROM `" . RL_DBPREFIX . "price_history` WHERE `ID` = {$id} LIMIT 1");

        $_response->script("
                $('#row-'+{$row_id}).slideUp('2000').remove();
            ");

        return $_response;
    }

    function hookEditListingAdditionalInfo()
    {
        global $listing_id, $listing, $data;
        $price_tag = $GLOBALS['config']['price_tag_field'] ?: 'price';
        $old_price = $GLOBALS['rlDb'] -> getOne('price', "`ID` = {$listing_id}", 'listings');
        $new_price = $data['price']['value']."|".$data['price']['currency'];
        $price_history_exist = $GLOBALS['rlDb']->getOne('ID', "`Listing_id` = '{$listing_id}'", 'price_history');
        if(!$price_history_exist) {
            $listing_first_price =  $listing[$price_tag];
            if($listing_first_price) {
                if($listing_first_price  != $new_price) {
                    $first_price['price'] = $listing_first_price;
                    $first_price['Date']  = $listing['Date'];
                    $first_price['Listing_id'] = $listing_id;
                    $first_price['IP'] = $GLOBALS['reefless']->getClientIpAddress();
                    $GLOBALS['rlActions']->insertOne($first_price,'price_history');

                    $insert_data['price'] = $new_price;
                    $insert_data['Date']  = date("Y-m-d H:i:s");
                    $insert_data['Listing_id'] = $listing_id;
                    $insert_data['IP'] = $GLOBALS['reefless']->getClientIpAddress();
                    $GLOBALS['rlActions']->insertOne($insert_data,'price_history');
                }
            }
        } else {
            if($old_price != $new_price ) {
                $insert_data['price'] = $new_price;
                $insert_data['Date']  = date("Y-m-d H:i:s");
                $insert_data['Listing_id'] = $listing_id;
                $insert_data['IP'] = $GLOBALS['reefless']->getClientIpAddress();
                $GLOBALS['rlActions']->insertOne($insert_data,'price_history');
            }
        }
    }
    
}
