<?php

/******************************************************************************
 *
 *	PROJECT: Flynax Classifieds Software
 *	VERSION: 4.X
 *	LICENSE: FL4HLD2A8696 - http://www.flynax.com/license-agreement.html
 *	PRODUCT: Real Estate Agency
 *	DOMAIN: gevimmo.com
 *	FILE: RLNEARBYSCHOOLS.CLASS.PHP
 *
 *	The software is a commercial product delivered under single, non-exclusive,
 *	non-transferable license for one domain or IP address. Therefore distribution,
 *	sale or transfer of the file in whole or in part without permission of Flynax
 *	respective owners is considered to be illegal and breach of Flynax License End
 *	User Agreement.
 *
 *	You are not allowed to remove this information from the file without permission
 *	of Flynax respective owners.
 *
 *	Flynax Classifieds Software 2017 |  All copyrights reserved.
 *
 *	http://www.flynax.com/
 *
 ******************************************************************************/

class rlNearbySchools extends reefless
{
    private $api_key = "";
    private $state_key = "";

    /**
     *  Constructor
     */
    public function __construct()
    {
        global $config;

        $this->api_key = $config['nbs_api_key'];
        $this->state_key = $config['nbs_state_key'];
    }

    /**
     * Get all schools by lat & long of the listing
     * @return schools array
     */
    public function getSchools()
    {
        global $listing_data, $page_info, $config, $rlCommon, $rlSmarty, $rlActions, $rlDebug;

        if ($page_info['Key'] != 'view_details' || !$this->api_key || !$this->state_key || !$config['nbs_enable_module']) {
            $need_unset = true;
        }

        $nbs_errors = array();
        $state = "";
        $lat = $listing_data['Loc_latitude'];
        $lon = $listing_data['Loc_longitude'];
        $result = array();

        if ($listing_data[$this->state_key]) {
            $state = $this->getState($listing_data[$this->state_key]);
        }
        if ($state && $lat && $lon && $listing_data['Status'] == 'active' && !$need_unset) {


            $listing_id = $listing_data['ID'];
            $is_cached  = $this->getOne('Data', "`Listing_ID` = {$listing_id}", 'nearby_schools');
            if ($is_cached) {
                $schools = unserialize(base64_decode($is_cached));
                if (!empty($schools)) {
                    foreach ($schools['school'] as $key => $school) {
                        $result[] = $school;
                    }
                    $need_unset = false;
                } else {
                    $need_unset = true;
                }
            } else {
                $parametrs = array(
                    'key' => $this->api_key,
                    'state' => $state,
                    'lat' => $lat,
                    'lon' => $lon,
                    'radius' => $config['nbs_radius'],
                    'limit' => $config['nbs_limit'],
                );

                $parametrs = array_filter($parametrs);
                $request_url = "http://api.greatschools.org/schools/nearby?" . http_build_query($parametrs);

                $xml_response = file_get_contents($request_url);
                if ($xml_response) {
                    $xml = simplexml_load_string($xml_response);
                    $schools = json_decode(json_encode((array) $xml), true);
                    $insert_data = array(
                        'Listing_ID' => $listing_id,
                        'Data' => base64_encode(serialize($schools))
                    );
                    $rlActions->insertOne($insert_data, 'nearby_schools');
                    
                    if (!empty($xml)) {
                        if (!isset($xml->errorCode)) {
                            foreach ($schools['school'] as $key => $school) {
                                $result[] = $school;
                            }
                            $need_unset  = false;
                        } else {
                            $error_message = "Nearby Schools plugin Error: Xml response error. Error code {$xml->errorCode}";
                            $need_unset  = true;
                        }
                    }  else {
                        $error_message = "Nearby Schools plugin Error: No schools found for {$state}, {$lat}, {$lon} - listing id {$listing_id}";
                        $need_unset  = true;
                    }
                } else {
                    $error_message = "Nearby Schools plugin Error: Xml response empty"; 
                    $need_unset  = true;
                }
            }
        } else {
            $error_message = "Nearby Schools plugin Error: Wrong configuration or missing coordinates";
            $need_unset = true;
        }

        if ($need_unset) {
            unset($GLOBALS['blocks']['nearbyschools']);
            unset($GLOBALS['block_keys']['nearbyschools']);
            $rlCommon->defineBlocksExist($GLOBALS['blocks']);
            $rlSmarty->assign('blocks', $GLOBALS['blocks']);
            if ($error_message) {
                $rlDebug->logger($error_message);
            }
        } else {
            return $result;
        }
    }

    /**
     * Mapping function
     * @param $state_key State key
     * @return biliteral code of the state
     */
    public function getState($state_key)
    {
        global $lang;

        $state = "";
        $key = 'data_formats+name+' . $state_key;
        $phrase = $this->getOne('Value', "`Key` = '{$key}' AND `Code` = 'en'", 'lang_keys');

        $mapping_by_phrase = array(
            'Alabama' => 'AL', 'Alaska' => 'AK', 'Arizona' => 'AZ', 'Arkansas' => 'AR', 'California' => 'CA', 'Colorado' => 'CO',
            'Connecticut' => 'CT', 'Delaware' => 'DE', 'Florida' => 'FL', 'Georgia' => 'GA', 'Hawaii' => 'HI', 'Idaho' => 'ID', 'Illinois' => 'IL',
            'Indiana' => 'IN', 'Iowa' => 'IA', 'Kansas' => 'KS', 'Kentucky' => 'LA', 'Maine' => 'ME', 'Maryland' => 'MD', 'Massachusetts' => 'MA',
            'Michigan' => 'MI', 'Minnesota' => 'MN', 'Mississippi' => 'MS', 'Missouri' => 'MO', 'Montana' => 'MT', 'Nebraska' => 'NE',
            'Nevada' => 'NV', 'New Hampshire' => 'NH', 'New Jersey' => 'NJ', 'New Mexico' => 'NM', 'New York' => 'NY', 'North Carolina' => 'NC',
            'North Dakota' => 'ND', 'Ohio' => 'OK', 'Oklahoma' => 'IA', 'Oregon' => 'OR', 'Pennsylvania' => 'PA', 'Rhode Island' => 'RI',
            'South Carolina' => 'SC', 'South Dakota' => 'SD', 'Tennessee' => 'TN', 'Texas' => 'TX', 'Utah' => 'UT', 'Vermont' => 'VT',
            'Virginia' => 'VA', 'Washington' => 'WA', 'Wisconsin' => 'WI', 'Wyoming' => 'WY'
        );

        if ($phrase) {
            $state = $mapping_by_phrase[$phrase];
        }

        return $state;
    }

    /**
     *  Validate block in the front end
     *  @return bool  - false (block validation filed block removed ); true - validation passed;
     */
    public function blockValidate()
    {
        global $config, $blocks, $page_info, $listing_data;

        $nbsEnabled = $config['nbs_enable_module'];
        if ($nbsEnabled) {
            $need_unset = false;

            if ($page_info['Key'] != 'view_details') {
                $need_unset = true;
            }
        } else {
            $need_unset = true;
        }

        if ($need_unset) {
            unset($blocks['nearbyschools']);
            return false;
        } else {
            return true;
        }
    }

    /**
     * Remove cache of edited listing  
     */
    function listingEdit()
    {
        global $listing_id;
        $this->query("DELETE FROM `". RL_DBPREFIX ."nearby_schools` WHERE `Listing_ID` = {$listing_id}");
    } 
    
    /**
    * @hook staticDataRegister
    * 
    * @since 1.0.0
    **/
    function hookStaticDataRegister()
    {
        $GLOBALS['rlStatic']->addBoxFooterCSS(RL_PLUGINS_URL . 'nearbySchools/static/style.css', 'nearbySchools', true);
    }

    /**
    * @hook apPhpConfigBeforeUpdate
    * 
    * @since 1.0.0
    **/
    function hookApPhpConfigBeforeUpdate()
    {
        if ($GLOBALS['dConfig']['nbs_limit']['value'] != $GLOBALS['config']['nbs_limit']) {
            $this->query("TRUNCATE TABLE `" . RL_DBPREFIX . "nearby_schools`");
        }
    }

    /**
    * @hook tplFooter
    * 
    * @since 1.0.0
    **/
    function hookTplFooter()
    {
        global $rlStatic;

        if (!is_object($rlStatic)) {
            echo "<link rel='stylesheet' href='" . RL_PLUGINS_URL . "neabrySchools/static/style.css' />";
        }
    }

    /**
    * @hook listingDetailsTop
    * 
    * @since 1.0.0
    **/
    function hookListingDetailsTop()
    {
        $nearby_schools = $this->getSchools();
        $GLOBALS['rlSmarty']->assign('schools', $nearby_schools);
    }

    /**
    * @hook specialBlock
    * 
    * @since 1.0.0
    **/
    function hookSpecialBlock()
    {
        $this->blockValidate();
    }


    /**
    * @hook apMixConfigItem
    * 
    * @since 1.0.0
    **/
    function hookApMixConfigItem(&$value)
    {
        global $lang;
        
        if ($value['Key'] == 'nbs_state_key') {
            $this->setTable('listing_fields');
            
            $value['Values'] = array();
            $l_fields = $this->fetch(
                array('Key'), 
                array('Status' => 'active', 'Map' => '1'), 
                "AND `Type` IN ('text','select')"
            );

            foreach ($l_fields AS $item) {
                $value['Values'][] = array('ID' => $item['Key'], 'name' => $lang['listing_fields+name+'.$item['Key'] ]);
            }
        }
    }

    /**
    * @hook afterListingEdit
    * 
    * @since 1.0.0
    **/
    function hookAfterListingEdit()
    {
       $this->listingEdit();
    }

    /**
    * @hook apPhpListingsAfterEdit
    * 
    * @since 1.0.0
    **/
    function hookApPhpListingsAfterEdit()
    {
       $this->listingEdit();
    }

    /**
     * Plugin install method 
     */
    function nbsInstall()
    {
        $this->query("
           CREATE TABLE IF NOT EXISTS `". RL_DBPREFIX ."nearby_schools` (
              `ID` int(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
              `Listing_ID` int(10) NOT NULL,
              `Data` TEXT NOT NULL
            ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
        ");

        $this->query("
            UPDATE `". RL_DBPREFIX ."blocks` 
            SET  `Page_ID` = '25', `Sticky` = '0' 
            WHERE `Key` = 'nearbyschools';
        ");
    }
    
    /**
     * Plugin uninstall method 
     */
    function nbsUninstall()
    {
        $this->query("DROP TABLE IF EXISTS`" . RL_DBPREFIX . "nearby_schools`");
    }
}
