<?php

/*
+---------------------------------------------------------------------------+
| Revive Adserver                                                           |
| http://www.revive-adserver.com                                            |
|                                                                           |
| Copyright: See the COPYRIGHT.txt file.                                    |
| License: GPLv2 or later, see the LICENSE.txt file.                        |
+---------------------------------------------------------------------------+
*/

// Require the initialisation file
require_once '../../init.php';

// Required files
require_once MAX_PATH . '/lib/OA/Dal.php';
require_once MAX_PATH . '/www/admin/config.php';
require_once MAX_PATH . '/www/admin/lib-statistics.inc.php';
require_once MAX_PATH . '/www/admin/lib-zones.inc.php';
require_once MAX_PATH . '/www/admin/lib-size.inc.php';
require_once MAX_PATH . '/lib/max/Admin_DA.php';
require_once MAX_PATH . '/lib/max/other/html.php';
require_once MAX_PATH .'/lib/OA/Admin/UI/component/Form.php';
require_once MAX_PATH . '/lib/OA/Admin/NumberFormat.php';


if($GLOBALS['_MAX']['CONF']['database']['type']=='mysql'){
    require_once MAX_PATH . '/lib/OA/Dal/Delivery/mysql.php';
} else if($GLOBALS['_MAX']['CONF']['database']['type']=='pgsql'){
    require_once MAX_PATH . '/lib/OA/Dal/Delivery/pgsql.php';
} else if($GLOBALS['_MAX']['CONF']['database']['type']=='mysqli'){
    require_once MAX_PATH . '/lib/OA/Dal/Delivery/mysqli.php';
}

// Register input variables
phpAds_registerGlobalUnslashed(
    'zonename',
    'description',
    'delivery',
    'sizetype',
    'size',
    'width',
    'height',
    'submit',
    'comments'
);

/*-------------------------------------------------------*/
/* Affiliate interface security                          */
/*-------------------------------------------------------*/

OA_Permission::enforceAccount(OA_ACCOUNT_MANAGER, OA_ACCOUNT_TRAFFICKER);
OA_Permission::enforceAccessToObject('affiliates', $affiliateid);
OA_Permission::enforceAccessToObject('zones', $zoneid, true);

if (OA_Permission::isAccount(OA_ACCOUNT_TRAFFICKER)) {
    if (!empty($zoneid)) {
        OA_Permission::enforceAllowed(OA_PERM_ZONE_EDIT);
    } else {
        OA_Permission::enforceAllowed(OA_PERM_ZONE_ADD);
    }
}


/*-------------------------------------------------------*/
/* Store preferences									 */
/*-------------------------------------------------------*/
$session['prefs']['inventory_entities'][OA_Permission::getEntityId()]['affiliateid'] = $affiliateid;
phpAds_SessionDataStore();

/*-------------------------------------------------------*/
/* Initialise data                                       */
/*-------------------------------------------------------*/
if (!empty($zoneid)) {
    $doZones = OA_Dal::factoryDO('zones');
    $doZones->zoneid = $zoneid;
    if ($doZones->find() && $doZones->fetch()) {
        $zone = $doZones->toArray();
    }

    if ($zone['width'] == -1) $zone['width'] = '*';
    if ($zone['height'] == -1) $zone['height'] = '*';
}
else {
    $doAffiliates = OA_Dal::factoryDO('affiliates');
    $doAffiliates->affiliateid = $affiliateid;

    if ($doAffiliates->find() && $doAffiliates->fetch() && $affiliate = $doAffiliates->toArray())
        $zone["zonename"] = $affiliate['name'].' - ';
    else {
        $zone["zonename"] = '';
    }

    $zone['zonename']        .= $GLOBALS['strDefault'];
    $zone['description']     = '';
    $zone['width']           = '468';
    $zone['height']          = '60';
    $zone['delivery']        = phpAds_ZoneBanner;
    $zone['comments'] = null;
}
$zone['affiliateid']     = $affiliateid;


/*-------------------------------------------------------*/
/* MAIN REQUEST PROCESSING                               */
/*-------------------------------------------------------*/
//build form
$zoneForm = buildZoneForm($zone, $oComponent);

if ($zoneForm->validate()) {
    //process submitted values
    $errors = processForm($zoneForm, $oComponent);

    if(!empty($errors)) {
    }
}
//display the page - show any validation errors that may have occurred
displayPage($zone, $zoneForm, $errors);


/*-------------------------------------------------------*/
/* Build form                                            */
/*-------------------------------------------------------*/
function buildZoneForm($zone, $oComponent = null)
{
    global $conf;
    $newZone = empty($zone['zoneid']);

    $form = new OA_Admin_UI_Component_Form("zoneform", "POST", $_SERVER['SCRIPT_NAME']);
    $form->forceClientValidation(true);
    $form->addElement('hidden', 'zoneid', $zone['zoneid']);
    $form->addElement('hidden', 'affiliateid', $zone['affiliateid']);
    $form->addElement('hidden', 'sel_vidtype', $zone['vidtype']);

    $form->addElement('header', 'zone_basic_info', $GLOBALS['strBasicInformation']);
    $form->addElement('text', 'zonename', $GLOBALS['strName']);
    $form->addElement('text', 'description', $GLOBALS['strDescription']);

    //zone type group
    $zoneTypes[] = $form->createElement('radio', 'delivery', '',
        "<img src='".OX::assetPath()."/images/icon-zone.gif' align='absmiddle'>&nbsp;".$GLOBALS['strBannerButtonRectangle'],
        phpAds_ZoneBanner, array('id' => 'delivery-b',
            'class' => 'website_zone app_zone',
            'onClick' => 'phpAds_formEnableSize();',
            'onChange' => 'oa_hide("warning_change_zone_type");'));
    if ($conf['oxInvocationTags']['isAllowedAdlayer'] || $zone['delivery'] == phpAds_ZoneInterstitial) {
        $zoneTypes[] = $form->createElement('radio', 'delivery', '',
            "<img src='".OX::assetPath()."/images/icon-interstitial.gif' align='absmiddle'>&nbsp;".$GLOBALS['strInterstitial'],
            phpAds_ZoneInterstitial, array('id' => 'delivery-i',  'class' => 'website_zone',
                'onClick' => 'phpAds_formEnableSize();',
                'onChange' => 'oa_hide("warning_change_zone_type");'));
    }
    if ($conf['oxInvocationTags']['isAllowedPopup'] || $zone['delivery'] == phpAds_ZonePopup) {
        $zoneTypes[] = $form->createElement('radio', 'delivery', '',
            "<img src='".OX::assetPath()."/images/icon-popup.gif' align='absmiddle'>&nbsp;".$GLOBALS['strPopup'],
            phpAds_ZonePopup, array('id' => 'delivery-p',  'class' => 'website_zone',
                'onClick' => 'phpAds_formEnableSize();',
                'onChange' => 'oa_hide("warning_change_zone_type");'));
    }
    $zoneTypes[] = $form->createElement('radio', 'delivery', '',
        "<img src='".OX::assetPath()."/images/icon-textzone.gif' align='absmiddle'>&nbsp;".$GLOBALS['strTextAdZone'],
        phpAds_ZoneText, array('id' => 'delivery-t', 'class' => 'website_zone app_zone', 'onClick' => 'phpAds_formDisableSize();',
            'onChange' => 'oa_hide("warning_change_zone_type");'));
     $zoneTypes[] = $form->createElement('radio', 'delivery', '',
         "<img src='".OX::assetPath()."/images/icon-zone-email.gif' align='absmiddle'>&nbsp;".$GLOBALS['strEmailAdZone'],
         MAX_ZoneEmail, array('id' => 'delivery-e',  'class' => 'website_zone', 'onClick' => 'phpAds_formEnableSize();',
             'onChange' => 'oa_hide("warning_change_zone_type");'));
    if (!empty($conf['allowedBanners']['video'])) {
        $zoneTypes[] = $form->createElement('radio', 'delivery', '',
            "<img src='".OX::assetPath()."/images/icon-zone-video-instream.png' align='absmiddle'>&nbsp;".$GLOBALS['strZoneVideoInstream'],
            OX_ZoneVideoInstream, array('id' => 'delivery-vi',  'class' => 'app_zone', 'onClick' => 'phpAds_formDisableSize();',
                'onChange' => 'oa_hide("warning_change_zone_type");'));
        $zoneTypes[] = $form->createElement('radio', 'delivery', '',
            "<img src='".OX::assetPath()."/images/icon-zone-video-overlay.png' align='absmiddle'>&nbsp;".$GLOBALS['strZoneVideoOverlay'],
            OX_ZoneVideoOverlay, array('id' => 'delivery-vo',  'class' => 'app_zone', 'onClick' => 'phpAds_formDisableSize();',
                'onChange' => 'oa_hide("warning_change_zone_type");'));
       
    }
    
    
    
    $zoneTypes[] = $form->createElement('radio', 'delivery', '',
            "<img src='".OX::assetPath()."/images/icon-zone-video-overlay.png' align='absmiddle'> Native Image",
            12, array('id' => 'delivery-oi', 'class' => 'website_zone', 'onClick' => 'phpAds_formDisableSize();',
                'onChange' => 'oa_hide("warning_change_zone_type");'));  
                
    
    $form->addGroup($zoneTypes, 'zone_types', $GLOBALS['strZoneType'], "<br/>");

    //~ WEBSITE APP TYPE

    $table_prefix = $GLOBALS['_MAX']['CONF']['table']['prefix'];
    $query = OA_Dal_Delivery_query("SELECT comments FROM {$table_prefix}affiliates WHERE affiliateid = ".$zone['affiliateid']);
    $apptype = OA_Dal_Delivery_fetchAssoc($query);
    $app_type = unserialize($apptype['comments']);

    $form->addElement('hidden', 'app_type', $app_type['app_type']);

    //size
    global $phpAds_IAB;
    switch ($zone['delivery']) {
        case phpAds_ZoneText:
        case 12:
        case OX_ZoneVideoInstream:
        case OX_ZoneVideoOverlay:
        
        default:
            $sizeDisabled = false;
        break;

    }

    $aDefaultSize['radio'] = $form->createElement('radio', 'sizetype', '', '',
        'default', array('id' => 'size-d'));
    foreach (array_keys($phpAds_IAB) as $key)
    {
        $iabSizes[$phpAds_IAB[$key]['width']."x".$phpAds_IAB[$key]['height']] =
            $GLOBALS['strIab'][$key];
    }
    $iabSizes['-'] = $GLOBALS['strCustom'];
    $aDefaultSize['select'] = $form->createElement('select', 'size', null, $iabSizes,
        array('onchange' => 'phpAds_formSelectSize(this); oa_sizeChangeUpdateMessage("warning_change_zone_size");', 'class' => 'medium'));


    $aCustomSize['radio'] = $form->createElement('radio', 'sizetype', '', '', 'custom',
        array('id' => 'size-c'));

    $aCustomSize['width'] = $form->createElement('text', 'width', $GLOBALS['strWidth'].':',
        array('onkeydown' => 'phpAds_formEditSize();',
            'onChange' => 'oa_sizeChangeUpdateMessage("warning_change_zone_size");'));
    $aCustomSize['width']->setSize(5);
    $aCustomSize['height'] = $form->createElement('text', 'height', $GLOBALS['strHeight'].':',
        array('onkeydown' => 'phpAds_formEditSize();',
            'onChange' => 'oa_sizeChangeUpdateMessage("warning_change_zone_size");'));
    $aCustomSize['height']->setSize(5);

    $sizeTypes['default'] = $form->createElement('group', 'defaultSizeG', null, $aDefaultSize, null, false);
    $sizeTypes['custom'] = $form->createElement('group', 'customSizeG', null, $aCustomSize, null, false);

    //disable fields if necessary
    if ($sizeDisabled) {
        $aDefaultSize['radio']->setAttribute('disabled', $sizeDisabled);
        $aDefaultSize['select']->setAttribute('disabled', $sizeDisabled);
        $aCustomSize['radio']->setAttribute('disabled', $sizeDisabled);
        $aCustomSize['width']->setAttribute('disabled', $sizeDisabled);
        $aCustomSize['height']->setAttribute('disabled', $sizeDisabled);
    }

    $form->addGroup($sizeTypes, 'size_types', $GLOBALS['strSize'], "<br/>");

    if($app_type['app_type'] == 3)
    {
        $form->addElement('text', 'floor_price', "Floor price"); //CUSTOM FIELD
    }
   

    /** CUSTOM INVENTORY TYPE START **/
    
    $inventoryTypes[] = $form->createElement('radio', 'inventory_type', '',
        "Private",'1');
    
    $inventoryTypes[] = $form->createElement('radio', 'inventory_type', '',
        "Public",'2');
    
    $inventoryTypes[] = $form->createElement('radio', 'inventory_type', '',
        "Public Private",'3');

    $inventoryTypes[] = $form->createElement('radio', 'inventory_type', '',
        "Private Public",'4');

    $form->addGroup($inventoryTypes, 'inventory', 'Inventory selection', "<br/>");

    /** CUSTOM INVENTORY TYPE END **/

    /** SSP BUYERS BASED ON INVENTORY TYPES START **/

    $inv_type[] = $form->createElement('radio', 'inv_type', '',
        "Open Market",'1');
    
    $inv_type[] = $form->createElement('radio', 'inv_type', '',
        "Programmatic Deal",'2');
    
    $inv_type[] = $form->createElement('radio', 'inv_type', '',
        "Both",'3');

    $form->addGroup($inv_type, 'inv_type', 'Inventory Type', "<br/>");

    $ssp_buyer = [];

    if($zone['inv_type'])
    {
        $condition = '';

        if($zone['inv_type'] == 1){
            $condition = 'open_market = 1';
        }else if($zone['inv_type'] == 2){
            $condition = 'prog_deal = 1';  
        }else if($zone['inv_type'] == 3){
            $condition = 'both_val = 1';
        }

        $table_prefix = $GLOBALS['_MAX']['CONF']['table']['prefix'];
        $query = OA_Dal_Delivery_query("SELECT exchange_name, exchange_id FROM {$table_prefix}dj_ad_exchange WHERE {$condition} and status = 1");

        if(OA_Dal_Delivery_numRows($query)>0)
        {
            while ($row = OA_Dal_Delivery_fetchAssoc($query)) 
            {           
                $ssp_buyer[$row['exchange_id']] =   $row['exchange_name'];
            } 
        }
    }

    $form->addElement('select', 'ssp_buyer[]', 'SSP Buyers', $ssp_buyer, array('multiple'=> true,'style' => 'width:250px; height: 100px;', 'class' => 'medium','id' => 'ssp_buyer', 'selected' => true));
    
    $selected_ssp = unserialize($zone['ssp_buyer']);
    $form->addElement('hidden', 'selected_ssp', '', array('values' => json_encode($selected_ssp)) );
    
    /** SSP BUYERS ENDS **/

    $form->addElement('textarea', 'comments', $GLOBALS['strComments']);

    /** CUSTOM PASSBACK START **/

    if($app_type['app_type'] == 3){
        $form->addElement('textarea', 'passbacktag','PassBack Tag',array('id'=>'new'));
    }

    /** CUSTOM PASSBACK END **/

    if ($oComponent && method_exists($oComponent, 'extendZoneForm')) {
        $oComponent->extendZoneForm($form, $zone, $newZone);
    }

    $form->addElement('controls', 'form-controls');
    $form->addElement('submit', 'submit', $GLOBALS['strSaveChanges']);


    //validation rules
    $translation = new OX_Translation();
    $urlRequiredMsg = $translation->translate($GLOBALS['strXRequiredField'], array($GLOBALS['strName']));
    $form->addRule('zonename', $urlRequiredMsg, 'required');

    if($newZone)
    {
    	$zone['inventory_type'] = 1 ;
    }
	
    //set form values
    $form->setDefaults($zone);

    //sizes radio
    if (phpAds_sizeExists ($zone['width'], $zone['height'])) {
        $size = $zone['width']."x".$zone['height'];
        $sizeType = 'default';
    }
    else {
        $size = "-";
        $sizeType = 'custom';
    }
    $form->setDefaults(array('size' => $size, 'sizetype' => $sizeType));
    
    return $form;
}


/*-------------------------------------------------------*/
/* Process submitted form                                */
/*-------------------------------------------------------*/
/**
 * Processes submit values of zone form
 *
 * @param OA_Admin_UI_Component_Form $form form to process
 * @return An array of Pear::Error objects if any
 */
function processForm($form, $oComponent = null)
{
    $aFields = $form->exportValues();

    switch ($aFields['delivery']) {
        case phpAds_ZoneText:
            $aFields['width'] = $aFields['height'] = 0;
            break;
        case OX_ZoneVideoOverlay:
            $aFields['width'] = $aFields['height'] = -2;
            break;
        case OX_ZoneVideoInstream:
            $aFields['width'] = $aFields['height'] = -3;
            break;
        case 12:
            $aFields['width'] = $aFields['height'] = -12; 
            break;
        default: 
            if ($aFields['sizetype'] == 'custom') {
                if (isset($aFields['width']) && $aFields['width'] == '*') {
                    $aFields['width'] = -1;
                }
                if (isset($aFields['height']) && $aFields['height'] == '*') {
                    $aFields['height'] = -1;
                }
            } else {
                list($aFields['width'], $aFields['height']) = explode ('x', $aFields['size']);
            }
        break;
    }

    if (!(is_numeric($aFields['oac_category_id'])) || ($aFields['oac_category_id'] <= 0)) {
            $aFields['oac_category_id'] = 'NULL';
    }


    $out_height = $out_width = '0';

    if($_POST['vidtype'] == 1){
        $out_height = $out_width='-21';
    }else if($_POST['vidtype'] == 2){
        $out_height = $out_width='-22';
    }else if($_POST['vidtype'] == 3){
        $out_height = $out_width='-23';
    }else if($_POST['vidtype'] == 4){
        $out_height = $out_width='-24';
    }else if($_POST['vidtype'] == 5){
        $out_height = $out_width='-25';
    }else if($_POST['vidtype'] == 6){
        $out_height = $out_width='-26';
    }else if($_POST['vidtype'] == 7){
        $out_height = $out_width='-27';
    }

    if (empty($errors)) {

        // Edit
        if (!empty($aFields['zoneid']))
        {
            // before we commit any changes to db, store whether the size has changed
            $aZone = Admin_DA::getZone($aFields['zoneid']);
            $size_changed = ($aFields['width'] != $aZone['width'] || $aFields['height'] != $aZone['height']) ? true : false;
            $type_changed = ($aFields['delivery'] != $aZone['type']) ? true : false;

            $doZones = OA_Dal::factoryDO('zones');
            $doZones->zonename = $aFields['zonename'];
            $doZones->description = $aFields['description'];
            $doZones->width = $aFields['width'];
            $doZones->height = $aFields['height'];
            $doZones->comments = $aFields['comments'];
            $doZones->delivery = $aFields['delivery'];
            if ($aFields['delivery'] != phpAds_ZoneText && $aFields['delivery'] != phpAds_ZoneBanner) {
                $doZones->prepend = '';
                $doZones->append = '';
            }

            $doZones->oac_category_id  = $aFields['oac_category_id'];
            $doZones->zoneid = $aFields['zoneid'];
            $doZones->update();


            /** CUSTOM UPDATE START **/

            $table_prefix = $GLOBALS['_MAX']['CONF']['table']['prefix'];
            OA_Dal_Delivery_query("UPDATE {$table_prefix}zones SET passbacktag = '".OX_escapeString($aFields['passbacktag'])."', inventory_type = '".$aFields['inventory_type']."', inv_type = '".$aFields['inv_type']."', ssp_buyer = '".serialize($_POST['ssp_buyer'])."',floor_price='".$_POST['floor_price']."'  WHERE zoneid = ".$aFields['zoneid']);

            //~MOBILE ZONE OR WRB ZONE
            
            $vidtype = $_POST['vidtype'];
            if($_POST['delivery'] == 10)
            {
                if($_POST['app_type'] == 1 || $_POST['app_type'] == 2)
                {
                    //~CUSTOM NATIVE VIDEO UPDATE
                    if($vidtype == 2)
                    {       
                        $nativepos = $_POST['adposition'];
                        $nativeads = $_POST['adinterval'];

                        OA_Dal_Delivery_query("UPDATE {$table_prefix}zones SET adposition = '".$nativepos."', adinterval = '".$nativeads."', vidtype = '".$_POST['vidtype']."', reward = '', amount = '', position = '', layout = '', infeedads = '', infeedpos = '', width='".$out_width."', height='".$out_height."' WHERE zoneid =".$aFields['zoneid']);
                    }

                    //~CUSTOM INTERSTITIAL UPDATE
                    else if($vidtype == 3)
                    {
                        if(isset($_POST['layout']))
                        {
                            $layoutposition=$_POST['layout'];
                            OA_Dal_Delivery_query("UPDATE {$table_prefix}zones SET layout = '".$layoutposition."', reward = '', amount = '', position = '', adposition = '', adinterval = '', infeedads = '', infeedpos = '', vidtype = '".$_POST['vidtype']."',adposition = '',adinterval = '', width='".$out_width."', height='".$out_height."' WHERE zoneid = ".$aFields['zoneid']);
                        }
                    }

                    //~CUSTOM IN-FEED UPDATE
                    else if($vidtype == 4)
                    { 
                        if(isset($_POST['infeedpos']))
                        {
                            OA_Dal_Delivery_query("UPDATE {$table_prefix}zones SET layout = '',reward = '',amount = '',position = '',infeedpos = '".$_POST['infeedpos']."',infeedads='".$_POST['infeedads']."', vidtype = '".$_POST['vidtype']."',adposition = '',adinterval = '', width='".$out_width."', height='".$out_height."' WHERE zoneid = ".$aFields['zoneid']);

                        }
                    }

                    //~CUSTOM REWARDED UPDATE
                    else if($vidtype == 6)
                    {
                        if(isset($aFields['reward']) && isset($aFields['amount']))
                        {
                            $reward = implode("|",$_POST['reward']);
                            $amt = implode("|",$_POST['amount']);
                            
                            OA_Dal_Delivery_query("UPDATE {$table_prefix}zones SET reward = '".$reward."',amount = '".$amt."',layout = '',adposition = '',adinterval = '',infeedads = '',infeedpos = '', vidtype = '".$_POST['vidtype']."',adposition = '',adinterval = '', width='".$out_width."', height='".$out_height."' WHERE zoneid = ".$aFields['zoneid']);
                        } 
                          
                        if(isset($_POST['layout']))
                        {
                            $layoutposition=$_POST['layout'];
                            OA_Dal_Delivery_query("UPDATE {$table_prefix}zones SET layout = '".$layoutposition."', position = '', adposition = '', adinterval = '', infeedads = '', infeedpos = '', vidtype = '".$_POST['vidtype']."',adposition = '',adinterval = '', width='".$out_width."', height='".$out_height."' WHERE zoneid = ".$aFields['zoneid']);
                        }
                    } 

                    else
                    {
                        OA_Dal_Delivery_query("UPDATE {$table_prefix}zones SET layout = '',reward = '',amount = '',position = '',adposition = '',adinterval = '',infeedads = '',infeedpos = '', vidtype = '".$_POST['vidtype']."', width='".$out_width."', height='".$out_height."' WHERE zoneid = ".$aFields['zoneid']);
                    }
                }
                else
                {
                    OA_Dal_Delivery_query("UPDATE {$table_prefix}zones SET vidtype = '".$_POST['vidtype']."', layout = '',reward = '',amount = '',position = '',adposition = '',adinterval = '',infeedads = '',infeedpos = '', width='".$out_width."', height='".$out_height."' WHERE zoneid = ".$aFields['zoneid']);
                }

            }
            else
            {
                OA_Dal_Delivery_query("UPDATE {$table_prefix}zones SET layout = '',reward = '',amount = '',position = '',adposition = '',adinterval = '',infeedads = '',infeedpos = '' WHERE zoneid = ".$aFields['zoneid']);
            }

            
            /* CUSTOM INVENTORY TYPE UPDATE END*/

            // Reset append codes which called this zone
            $doZones = OA_Dal::factoryDO('zones');
            $doZones->appendtype = phpAds_ZoneAppendZone;

            if (OA_Permission::isAccount(OA_ACCOUNT_MANAGER))
            {
                $doZones->addReferenceFilter('agency', OA_Permission::getEntityId());
            }
            elseif (OA_Permission::isAccount(OA_ACCOUNT_TRAFFICKER))
            {
                  $doZones->addReferenceFilter('affiliates', OA_Permission::getEntityId());
            }
            $doZones->find();

            while ($doZones->fetch() && $row = $doZones->toArray())
            {
                $append = phpAds_ZoneParseAppendCode($row['append']);

                if ($append[0]['zoneid'] == $aFields['zoneid'])
                {
                    $doZonesClone = clone($doZones);
                    $doZonesClone->appendtype = phpAds_ZoneAppendRaw;
                    $doZonesClone->append = '';
                    $doZonesClone->update();
                }
            }

            if ($type_changed && $aFields['delivery'] == MAX_ZoneEmail) {
                // Unlink all campaigns/banners linked to this zone
                $aPlacementZones = Admin_DA::getPlacementZones(array('zone_id' => $aFields['zoneid']), true, 'placement_id');
                if (!empty($aPlacementZones)) {
                    foreach ($aPlacementZones as $placementId => $aPlacementZone) {
                        Admin_DA::deletePlacementZones(array('zone_id' => $aFields['zoneid'], 'placement_id' => $placementId));
                    }
                }
                $aAdZones = Admin_DA::getAdZones(array('zone_id' => $aFields['zoneid']), false, 'ad_id');
                if (!empty($aAdZones)) {
                    foreach ($aAdZones as $adId => $aAdZone) {
                        Admin_DA::deleteAdZones(array('zone_id' => $aFields['zoneid'], 'ad_id' => $adId));
                    }
                }
            }
            else if ($size_changed) {
                $aZone = Admin_DA::getZone($aFields['zoneid']);

                // Loop through all appended banners and make sure that they still fit...
                $aAds = Admin_DA::getAdZones(array('zone_id' => $aFields['zoneid']), false, 'ad_id');
                if (!empty($aAds)) {
                 foreach ($aAds as $adId => $aAd) {
                    $aAd = Admin_DA::getAd($adId);
                        if ( (($aZone['type'] == phpAds_ZoneText) && ($aAd['type'] != 'txt'))
                        || (($aAd['width'] != $aZone['width']) && ($aZone['width'] != -1))  
                        || (($aAd['height'] != $aZone['height']) && ($aZone['height'] != -1)) ) {
                            Admin_DA::deleteAdZones(array('zone_id' => $aFields['zoneid'], 'ad_id' => $adId));
                        }
                    }
                }

                // Check if any campaigns linked to this zone have ads that now fit.
                // If so, link them to the zone.
                $aPlacementZones = Admin_DA::getPlacementZones(array('zone_id' => $aFields['zoneid']), true);
                if (!empty($aPlacementZones)) {
                    foreach($aPlacementZones as $aPlacementZone) {
                    // get ads in this campaign
                    $aAds = Admin_DA::getAds(array('placement_id' => $aPlacementZone['placement_id']), true);
                        foreach ($aAds as $adId => $aAd) {
                            Admin_DA::addAdZone(array('zone_id' => $aFields['zoneid'], 'ad_id' => $adId));
                        }
                    }
                }
            }
            if ($oComponent && method_exists($oComponent, 'processZoneForm')) {
                $oComponent->processZoneForm($aFields);
            }

            // Queue confirmation message
            $translation = new OX_Translation();
            $translated_message = $translation->translate ( $GLOBALS['strZoneHasBeenUpdated'],
                array(
                MAX::constructURL(MAX_URL_ADMIN, "zone-edit.php?affiliateid=".$aFields['affiliateid']."&zoneid=".$aFields['zoneid']),
                htmlspecialchars($aFields['zonename'])
                ));
            OA_Admin_UI::queueMessage($translated_message, 'local', 'confirm', 0);

            OX_Admin_Redirect::redirect("zone-edit.php?affiliateid=".$aFields['affiliateid']."&zoneid=".$aFields['zoneid']);
        }
        // Add
        else
        {
            $doZones = OA_Dal::factoryDO('zones');
            $doZones->affiliateid = $aFields['affiliateid'];
            $doZones->zonename = $aFields['zonename'];
            $doZones->zonetype = phpAds_ZoneCampaign;
            $doZones->description = $aFields['description'];
            $doZones->comments = $aFields['comments'];
            $doZones->width = $aFields['width'];
            $doZones->height = $aFields['height'];
            $doZones->delivery = $aFields['delivery'];
            $doZones->oac_category_id  = $aFields['oac_category_id'];

            // The following fields are NOT NULL but do not get values set in the form.
            // Should these fields be changed to NULL in the schema or should they have a default value?
            $doZones->category = '';
            $doZones->ad_selection = '';
            $doZones->chain = '';
            $doZones->prepend = '';
            $doZones->append = '';

            $doZones->show_capped_no_cookie = 0;

            $aFields['zoneid'] = $doZones->insert();

            if ($oComponent && method_exists($oComponent, 'processZoneForm')) {
                $oComponent->processZoneForm($aFields);
            }


            /** CUSTOM UPDATE START **/

            $table_prefix = $GLOBALS['_MAX']['CONF']['table']['prefix'];
            OA_Dal_Delivery_query("UPDATE {$table_prefix}zones SET passbacktag = '".OX_escapeString($aFields['passbacktag'])."', inventory_type = '".$aFields['inventory_type']."', inv_type = '".$aFields['inv_type']."', ssp_buyer = '".serialize($_POST['ssp_buyer'])."',floor_price='".$_POST['floor_price']."'  WHERE zoneid = ".$aFields['zoneid']);

            //~MOBILE ZONE OR WRB ZONE
            
            $vidtype = $_POST['vidtype'];
            if($_POST['delivery'] == 10)
            {
                if($_POST['app_type'] == 1 || $_POST['app_type'] == 2)
                {
                    //~CUSTOM NATIVE VIDEO UPDATE
                    if($vidtype == 2)
                    {       
                        $nativepos = $_POST['adposition'];
                        $nativeads = $_POST['adinterval'];

                        OA_Dal_Delivery_query("UPDATE {$table_prefix}zones SET adposition = '".$nativepos."', adinterval = '".$nativeads."', vidtype = '".$_POST['vidtype']."', reward = '', amount = '', position = '', layout = '', infeedads = '', infeedpos = '', width='".$out_width."', height='".$out_height."' WHERE zoneid =".$aFields['zoneid']);
                    }

                    //~CUSTOM INTERSTITIAL UPDATE
                    else if($vidtype == 3)
                    {
                        if(isset($_POST['layout']))
                        {
                            $layoutposition=$_POST['layout'];
                            OA_Dal_Delivery_query("UPDATE {$table_prefix}zones SET layout = '".$layoutposition."', reward = '', amount = '', position = '', adposition = '', adinterval = '', infeedads = '', infeedpos = '', vidtype = '".$_POST['vidtype']."',adposition = '',adinterval = '', width='".$out_width."', height='".$out_height."' WHERE zoneid = ".$aFields['zoneid']);
                        }
                    }

                    //~CUSTOM IN-FEED UPDATE
                    else if($vidtype == 4)
                    { 
                        if(isset($_POST['infeedpos']))
                        {
                            OA_Dal_Delivery_query("UPDATE {$table_prefix}zones SET layout = '',reward = '',amount = '',position = '',infeedpos = '".$_POST['infeedpos']."',infeedads='".$_POST['infeedads']."', vidtype = '".$_POST['vidtype']."',adposition = '',adinterval = '', width='".$out_width."', height='".$out_height."' WHERE zoneid = ".$aFields['zoneid']);

                        }
                    }

                    //~CUSTOM REWARDED UPDATE
                    else if($vidtype == 6)
                    {
                        if(isset($aFields['reward']) && isset($aFields['amount']))
                        {
                            $reward = implode("|",$_POST['reward']);
                            $amt = implode("|",$_POST['amount']);
                            
                            OA_Dal_Delivery_query("UPDATE {$table_prefix}zones SET reward = '".$reward."',amount = '".$amt."',layout = '',adposition = '',adinterval = '',infeedads = '',infeedpos = '', vidtype = '".$_POST['vidtype']."',adposition = '',adinterval = '', width='".$out_width."', height='".$out_height."' WHERE zoneid = ".$aFields['zoneid']);
                        }  
                        
                           
                        if(isset($_POST['layout']))
                        {
                            $layoutposition=$_POST['layout'];
                            OA_Dal_Delivery_query("UPDATE {$table_prefix}zones SET layout = '".$layoutposition."', position = '', adposition = '', adinterval = '', infeedads = '', infeedpos = '', vidtype = '".$_POST['vidtype']."',adposition = '',adinterval = '', width='".$out_width."', height='".$out_height."' WHERE zoneid = ".$aFields['zoneid']);
                        }
                         
                        
                    } 

                    else
                    {
                        OA_Dal_Delivery_query("UPDATE {$table_prefix}zones SET layout = '',reward = '',amount = '',position = '',adposition = '',adinterval = '',infeedads = '',infeedpos = '', vidtype = '".$_POST['vidtype']."', width='".$out_width."', height='".$out_height."' WHERE zoneid = ".$aFields['zoneid']);
                    }
                }
                else
                {
                    OA_Dal_Delivery_query("UPDATE {$table_prefix}zones SET vidtype = '".$_POST['vidtype']."', layout = '',reward = '',amount = '',position = '',adposition = '',adinterval = '',infeedads = '',infeedpos = '', width='".$out_width."', height='".$out_height."' WHERE zoneid = ".$aFields['zoneid']);
                }

            }
            else
            {
                OA_Dal_Delivery_query("UPDATE {$table_prefix}zones SET layout = '',reward = '',amount = '',position = '',adposition = '',adinterval = '',infeedads = '',infeedpos = '' WHERE zoneid = ".$aFields['zoneid']);
            }

            
            /* CUSTOM INVENTORY TYPE UPDATE END*/

            // Queue confirmation message
            $translation = new OX_Translation ();
            $translated_message = $translation->translate ( $GLOBALS['strZoneHasBeenAdded'], array(
                MAX::constructURL(MAX_URL_ADMIN, 'zone-edit.php?affiliateid=' .  $aFields['affiliateid'] . '&zoneid=' . $aFields['zoneid']),
                htmlspecialchars($aFields['zonename'])
            ));
            OA_Admin_UI::queueMessage($translated_message, 'local', 'confirm', 0);

            OX_Admin_Redirect::redirect("affiliate-zones.php?affiliateid=".$aFields['affiliateid']);
        }
    }

    return $errors;
}


/*-------------------------------------------------------*/
/* Display page                                          */
/*-------------------------------------------------------*/
function displayPage($zone, $form, $zoneErrors = null)
{
    //header and breadcrumbs
    $pageName = basename($_SERVER['SCRIPT_NAME']);
    $agencyId = OA_Permission::getAgencyId();
    $aEntities = array('affiliateid' => $zone['affiliateid'], 'zoneid' => $zone['zoneid']);

    $aOtherPublishers = Admin_DA::getPublishers(array('agency_id' => $agencyId));
    $aOtherZones = Admin_DA::getZones(array('publisher_id' => $zone['affiliateid']));
    MAX_displayNavigationZone($pageName, $aOtherPublishers, $aOtherZones, $aEntities);

    //get template and display form
    $oTpl = new OA_Admin_Template('zone-edit.html');
    $oTpl->assign('zoneid', $zone['zoneid']);
    $oTpl->assign('zoneHeight', $zone["height"]);
    $oTpl->assign('zoneWidth', $zone["width"]);

    $oTpl->assign('zoneErrors', $zoneErrors);
    $oTpl->assign('form', $form->serialize());

    $oTpl->display();

    //footer
    phpAds_PageFooter();
}

//~CUSTOM OUTSTREA REWARDED VALUES

$reward =explode("|",$zone['reward']);
$amount =explode("|",$zone['amount']);
$count_reward = (empty($zone['reward']) ? '0' :count($reward));
$zone_type = (empty($zone['delivery']) ? '0' :$zone['delivery']);
$vid_type = (empty($zone['vidtype']) ? '0' :$zone['vidtype']);

$php_array = $reward;
$reward_array = json_encode($php_array);

$php_array1 = $amount;
$amount_array = json_encode($php_array1);


?>


<script type="text/javascript">

    //** SSP MULTIPLE SELECTION START **//

    var edit = '<?php echo $_GET['zoneid']; ?>';
    var selected_ssp = $("input[name=selected_ssp]").attr('values');
    var ssps = JSON.parse(selected_ssp);

    if(ssps){

        $("#ssp_buyer > option").each(function() {
            if(ssps.includes(this.value)){
                $(this).attr("selected", true);
            }
        });
    }

    //** SSP MULTIPLE SELECTION END **//


    //** SSP LISTING BASED ON INVENTORY TYPE START **//

    $("input[name=inv_type]").click(function(){

        var type = $(this).val();
        var condition = '';

        if(type == 1){
                        condition = 'open_market = 1';


        }else if(type == 2){
            condition = 'prog_deal = 1';

        }else if(type == 3){
            condition = 'both_val = 1';
        }

        ssp_buyer(condition);
    });

    function ssp_buyer(condition){

        $.ajax({

            type: 'POST',
            url: 'zone_ajax.php',
            data: { 'condition' : condition },

            success: function(result)
            {
                var result = JSON.parse(result);
                $("#ssp_buyer").empty();

                if(result.length > 0)
                {
                    for(var i=0; i < result.length; i++)
                    {
                        var option=`<option id='opt_${i}' selected value=${result[i]['exchange_id']}> ${result[i]['exchange_name']}  </option>`;
                        $("#ssp_buyer").append(option);
                    }
                }
                else
                {
                    var option = "<option style='background:rgb(255, 0, 0, 0.5);' value='0'>No Zones Available for this Website!</option>";
                    $("#ssp_buyer").append(option);
                }
                
                // a = i-1;
                // b = a;                
            }
        });
    }

    //** SSP LISTING BASED ON INVENTORY TYPE END **//

    //** SHOW ZONE TYPE BASED ON APP TYPE START **//

    var app_type = $("input[name=app_type]").val();

    if(app_type == 1 || app_type == 2){

        $(".website_zone").attr('disabled', true);
        $(".app_zone").attr('disabled', false);


    }

    //** SHOW ZONE TYPE BASED ON APP TYPE END **//




    //~CUSTOM NATIIVE COMMANDS START

    $("#nativepos").before('<td>To place position controls, you must use the ad pacer code when integrating  SDK.<br>Note : the position in your current streaming is zero(0).<br><br>place ads in these positions<br></td>');
    $("#nativeads").before('<td>After placed  ads show ads every </td>');
    
    $("#infeedpos").before('<td>To place position controls, you must use the ad pacer code when integrating  SDK.<br>Note : the position in your current streaming is zero(0).<br><br>place ads in these positions<br></td>');
    $("#infeedads").before('<td>After placed  ads show ads every </td>');
   
    //~CUSTOM REWARDED ADD REWARD ACTION 

    var db_value = <?php echo $count_reward ?>-1;
    var db_value_count = <?php echo $count_reward ?>;
    var count =1;
    var i =0;
        
    if(db_value_count !='')
    {
        for(var j=0;j<db_value;j++)
        {
            var a = '<tr id="added_'+count+'"><td width="30"></td><td width="170" valign="top" style="padding-top: 5px"></td>&nbsp;<td width="100%"><input name="reward['+count+']" type="text" id="rvpoint_'+count+'" placeholder="Reward" class="x-small">&nbsp;<input name="amount['+count+']" type="text" id="rvamount_'+count+'" placeholder="Amount" class="x-small">&nbsp;</td></tr>';
        
            $("#rvamount_"+j).after(a);
            count++;
        }
        count =db_value_count;
        i=db_value;
    }   

    var reward_array =<?php echo $reward_array ?>;
    var amount_array =<?php echo $amount_array ?>;

    $.each(reward_array, function( index, value ) {

        $('#rvpoint_'+index).val(value);
      
    });
    $.each(amount_array, function( index, value ) {
        
        $('#rvamount_'+index).val(value);
      
    });


    $("#rvaddrw").click(function(){

        var a = '<tr id="added_'+count+'"><td width="30"></td><td width="170" valign="top" style="padding-top: 5px"></td>&nbsp;<td width="100%"><input name="reward['+count+']" type="text" id="rvpoint_'+count+'" placeholder="Reward" class="x-small">&nbsp;<input name="amount['+count+']" type="text" id="rvamount_'+count+'" placeholder="Amount" class="x-small">&nbsp;</td></tr>';
        
        $("#rvamount_"+i).after(a);
        count++;
        i++;
    
    });

   


	$('input[name="inventory_type"]').change(function()
	{
		
		if($(this).val() == 1 )
		{
			 $('input[name="inv_type"]').parent().parent().hide();
			 $('#ssp_buyer').parent().parent().hide();
		}
		else
		{
			 $('input[name="inv_type"]').parent().parent().show();
			 $('#ssp_buyer').parent().parent().show();
		}
	});
	
	if($('input[name="inventory_type"]:checked').val() == "1" )
		{
			 $('input[name="inv_type"]').parent().parent().hide();
			 $('#ssp_buyer').parent().parent().hide();
		}
		else
		{
			 $('input[name="inv_type"]').parent().parent().show();
			 $('#ssp_buyer').parent().parent().show();
		}
	
</script>
