<?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 . '/lib/RV/Admin/Languages.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 . '/lib/OA/Dll/Publisher.php';
require_once MAX_PATH . '/lib/OA/Admin/Menu.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/Template.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'] == 'mysqli') {
    require_once MAX_PATH . '/lib/OA/Dal/Delivery/mysqli.php';
} else if ($GLOBALS['_MAX']['CONF']['database']['type'] == 'pgsql') {
    require_once MAX_PATH . '/lib/OA/Dal/Delivery/pgsql.php';
}

// Register input variables
phpAds_registerGlobalUnslashed ('move', 'name', 'website', 'contact', 'email',
                               'errormessage', 'submit', 'publiczones_old', 'formId');

// Security check
OA_Permission::enforceAccount(OA_ACCOUNT_MANAGER);
OA_Permission::enforceAccessToObject('affiliates', $affiliateid, true);


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

/*-------------------------------------------------------*/
/* Initialise data                                    */
/*-------------------------------------------------------*/
if ($affiliateid != "") {
    // Do not get this information if the page
    // is the result of an error message
    if (!isset($affiliate)) {
        $doAffiliates = OA_Dal::factoryDO('affiliates');
        if ($doAffiliates->get($affiliateid)) {
            $affiliate = $doAffiliates->toArray();
        }
    }
} else {
    //set some default
    $affiliate['website'] = 'http://';
    $affiliate['agencyid'] = $agencyid;
    // $affiliate['margin'] = 20;
}


/*-------------------------------------------------------*/
/* MAIN REQUEST PROCESSING                               */
/*-------------------------------------------------------*/
//  check if Thorium plugin is enabled
$oComponent = null;
if ( isset($GLOBALS['_MAX']['CONF']['plugins']['openXThorium']) &&
     $GLOBALS['_MAX']['CONF']['plugins']['openXThorium']) {
    $oComponent = &OX_Component::factory('admin', 'oxThorium', 'oxThorium');
}

//build form
$websiteForm = buildWebsiteForm($affiliate);

if ($websiteForm->validate()) {
    //process submitted values
    $oPublisherDll = processForm($affiliateid, $websiteForm, $oComponent);
    if ($oPublisherDll->_errorMessage || $oPublisherDll->_noticeMessage) {
        displayPage($affiliateid, $websiteForm, $oPublisherDll);
    }
}
else { //either validation failed or form was not submitted, display the form
    displayPage($affiliateid, $websiteForm);
}


/*-------------------------------------------------------*/
/* Build form                                            */
/*-------------------------------------------------------*/
function checkimpression($affiliateid)
{
    $table_prefix = $GLOBALS['_MAX']['CONF']['table']['prefix'];
    $zonesdata               = OA_Dal_Delivery_query("SELECT  balance,remaining_imp from {$table_prefix}affiliates where affiliateid=" . $affiliateid);
    $impression_count_query1 = OA_Dal_Delivery_fetchAssoc($zonesdata);
    return $impression_count_query1;
} 



function websiteToDomain($website)
{
    $pieces = parse_url($website);
    $domain = isset($pieces['host']) ? $pieces['host'] : '';    
    if(preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)){
        return $regs['domain'];
    }
    return FALSE;    
}


function buildWebsiteForm($affiliate)
{
    $form = new OA_Admin_UI_Component_Form("affiliateform", "POST", $_SERVER['SCRIPT_NAME']);
    $form->forceClientValidation(true);
    $form->addElement('hidden', 'affiliateid', $affiliate['affiliateid']);

    //CUSTOM FIELDS
    $values = unserialize($affiliate['comments']);

    $form->addElement('hidden', 'apptype', $values['app_type']);
    $form->addElement('hidden', 'appversion', $values['app_version']);
    $form->addElement('hidden', 'bundleid', $values['bundle_id']);
    $form->addElement('hidden', 'appurl', $values['app_url']);
    $form->addElement('hidden', 'privacy', $values['app_pp']);

    $form->addElement('header', 'basic_info', $GLOBALS['strBasicInformation']);

    /* CUSTOM FIELDS START */    

    $custom_dm['android'] = $form->createElement ( 'radio', 'app_type', '', 'Android', 1, array ('id' => 'app_type1') );
    $custom_dm['ios'] = $form->createElement ( 'radio', 'app_type', '', 'IOS', 2,array ('id' => 'app_type2') );
    $custom_dm['site'] = $form->createElement ( 'radio', 'app_type', '', 'Website', 3,array ('id' => 'app_type3') );

    $form->addElement( 'group', 'app_type', 'Ad Type', $custom_dm, null, false );

    $form->addElement('text', 'name', $GLOBALS['strName']);
    $form->addElement('text', 'contact', $GLOBALS['strContact']);
    $form->addElement('text', 'email', $GLOBALS['strEMail']);
    $form->addElement('text', 'website', $GLOBALS['strWebsiteURL']);

    $app_version['paid'] = $form->createElement ( 'radio', 'app_version', '', 'Paid', 1, array ('id' => 'version1') );
    $app_version['free'] = $form->createElement ( 'radio', 'app_version', '', 'Free', 2, array ('id' => 'version2') );
    $form->addElement( 'group', 'app_version', 'App Type', $app_version, null, false );
    
    $form->addElement('text', 'bundle_id', 'App Bundle ID');
    $form->addElement('text', 'app_url', 'App Store URL');
    $form->addElement('text', 'app_pp', 'Privacy Policy');

    /* CUSTOM FIELDS END */    

    $form->addElement('checkbox', 'programatic_deal','Programatic Deal');
    $form->addElement('checkbox', 'open_market', 'Open Market');

 
    $form->addElement('controls', 'form-controls');
    $form->addElement('submit', 'save', 'Save changes');

    //Form validation rules
    $translation = new OX_Translation();
    $urlRequiredMsg = $translation->translate($GLOBALS['strXRequiredField'], array($GLOBALS['strWebsiteURL']));
    //~ $form->addRule('website', $urlRequiredMsg, 'required');
    //~ $form->addRule('website', $GLOBALS['strInvalidWebsiteURL'], 'regex', '#^http(s?)\://.+$#');
    $contactRequiredMsg = $translation->translate($GLOBALS['strXRequiredField'], array($GLOBALS['strContact']));
    $form->addRule('contact', $contactRequiredMsg, 'required');
    $nameRequiredMsg = $translation->translate($GLOBALS['strXRequiredField'], array($GLOBALS['strName']));
    $form->addRule('name', $nameRequiredMsg, 'required');
    $emailRequiredMsg = $translation->translate($GLOBALS['strXRequiredField'], array($GLOBALS['strEMail']));
    $form->addRule('email', $emailRequiredMsg, 'required');
    $form->addRule('email', $GLOBALS['strEmailField'], 'email');


    //set form  values
    $form->setDefaults($affiliate);
    return $form;
}

/*-------------------------------------------------------*/
/* Process submitted form                                */
/*-------------------------------------------------------*/
 function processForm($affiliateid, $form, $oComponent)
{
    $aFields = $form->exportValues();
    $newWebsite = empty($aFields['affiliateid']);

    // Setup a new publisher object and set the fields passed in from the form:
    $oPublisher = new OA_Dll_PublisherInfo();
    $oPublisher->agencyId       = $aFields['agencyid'];
    $oPublisher->contactName    = $aFields['contact'];
    $oPublisher->emailAddress   = $aFields['email'];
    $oPublisher->publisherId    = $aFields['affiliateid'];
    $oPublisher->publisherName  = $aFields['name'];
    $oPublisher->website        = $aFields['website'];

    //~CUSTOM WORK START

    $table_prefix  = $GLOBALS['_MAX']['CONF']['table']['prefix'];
    $app_details = array(

            'app_type' => $aFields['app_type'],
            'app_version' => $aFields['app_version'],
            'bundle_id' => $aFields['bundle_id'],
            'app_url' => $aFields['app_url'],
            'app_pp' => $aFields['app_pp'],
    );

    $app_details = serialize($app_details);

    $app_type = array(

            'app_type' => $aFields['app_type']

        );
    $app_type = serialize($app_type);

    $oPublisher->programatic_deal = ($aFields['programatic_deal'] > 0) ? $aFields['programatic_deal']: 0;
    $oPublisher->open_market   = ($aFields['open_market']) ? $aFields['open_market']: 0;
    $oPublisher->margin   = ($aFields['margin']) ? $aFields['margin']: 0;
    $oPublisher->cpm   = ($aFields['cpm']) ? $aFields['cpm']: 0;

    //~CUSTOM WORK END
    
    // process form data for oxThorium if this is edit existing website
    if (!$newWebsite && $oComponent)
    {
        $aFields['affiliateid'] = $oPublisher->publisherId;
        $oComponent->processAffiliateForm($aFields);
    }

    $oPublisherDll = new OA_Dll_Publisher();
    if ($oPublisherDll->modify($oPublisher) && !$oPublisherDll->_noticeMessage) {

        // Queue confirmation message
        $translation = new OX_Translation ();
        if ($newWebsite) {
            //process form data for oxThorium for new website
            if ($oComponent)
            {
                $aFields['affiliateid'] = $oPublisher->publisherId;
                $oComponent->processAffiliateForm($aFields);
            }
            $translated_message = $translation->translate ( $GLOBALS['strWebsiteHasBeenAdded'], array(
                MAX::constructURL(MAX_URL_ADMIN, 'affiliate-edit.php?affiliateid=' .  $oPublisher->publisherId),
                htmlspecialchars($oPublisher->publisherName),
                MAX::constructURL(MAX_URL_ADMIN, 'zone-edit.php?affiliateid=' .  $oPublisher->publisherId),
            ));

            /* CUSTOM FIELD UPDATE START */

            if($aFields['app_type'] == 1 || $aFields['app_type'] == 2){

                OA_Dal_Delivery_query("UPDATE {$table_prefix}affiliates SET programatic_deal = {$oPublisher->programatic_deal}, open_market = {$oPublisher->open_market}, cpm = {$oPublisher->cpm}, margin = {$oPublisher->margin}, comments = '{$app_details}', website = '' WHERE affiliateid = {$oPublisher->publisherId} ");
            }else{

                OA_Dal_Delivery_query("UPDATE {$table_prefix}affiliates SET programatic_deal = {$oPublisher->programatic_deal}, open_market = {$oPublisher->open_market}, cpm = {$oPublisher->cpm}, margin = {$oPublisher->margin}, comments = '{$app_type}' WHERE affiliateid = {$oPublisher->publisherId} ");
            }

            /* CUSTOM FIELD UPDATE END */

            OA_Admin_UI::queueMessage($translated_message, 'local', 'confirm', 0);
            $redirectURL = "website-index.php";
        }
        else 
        {
            $translated_message = $translation->translate ( $GLOBALS['strWebsiteHasBeenUpdated'], array(
                MAX::constructURL(MAX_URL_ADMIN, 'affiliate-edit.php?affiliateid=' .  $oPublisher->publisherId),
                htmlspecialchars($oPublisher->publisherName),
            ));

            /* CUSTOM FIELD UPDATE START */

            if($aFields['app_type'] == 1 || $aFields['app_type'] == 2){

                OA_Dal_Delivery_query("UPDATE {$table_prefix}affiliates SET programatic_deal = {$oPublisher->programatic_deal}, open_market = {$oPublisher->open_market}, cpm = {$oPublisher->cpm}, margin = {$oPublisher->margin}, comments = '{$app_details}', website = '' WHERE affiliateid = {$oPublisher->publisherId} ");
            }else{

                OA_Dal_Delivery_query("UPDATE {$table_prefix}affiliates SET programatic_deal = {$oPublisher->programatic_deal}, open_market = {$oPublisher->open_market}, cpm = {$oPublisher->cpm}, margin = {$oPublisher->margin}, comments = '{$app_type}' WHERE affiliateid = {$oPublisher->publisherId} ");
            }

            /* CUSTOM FIELD UPDATE END */

            $redirectURL = "affiliate-edit.php?affiliateid={$oPublisher->publisherId}";
        }

        $programatic_deal = 0;
        $open_market = 0;
      
     

        if($oPublisher->programatic_deal == 1){

                $programatic_deal = 1;
        }
        if($oPublisher->open_market == 1){

            $open_market = 1;
        }

        OA_Dal_Delivery_query("UPDATE {$table_prefix}zones SET programatic_deal = {$programatic_deal}, open_market = {$open_market} WHERE affiliateid = {$oPublisher->publisherId} ");
            
        OA_Admin_UI::queueMessage($translated_message, 'local', 'confirm', 0);
        OX_Admin_Redirect::redirect($redirectURL);

    }
    return $oPublisherDll;
}

/*-------------------------------------------------------*/
/* Display page                                          */
/*-------------------------------------------------------*/
function displayPage($affiliateid, $form, $oPublisherDll = null)
{
    //header and breadcrumbs
    $oHeaderModel = MAX_displayWebsiteBreadcrumbs($affiliateid);
    if ($affiliateid != "") {
        OA_Admin_Menu::setPublisherPageContext($affiliateid, 'affiliate-edit.php');
        addWebsitePageTools($affiliateid);
        phpAds_PageHeader(null, $oHeaderModel);
    }
    else {
        phpAds_PageHeader("affiliate-edit_new", $oHeaderModel);
    }

    //get template and display form
    $oTpl = new OA_Admin_Template('affiliate-edit.html');
    $oTpl->assign('affiliateid', $affiliateid);
    $oTpl->assign('form', $form->serialize());

    if (isset($oPublisherDll)) {
        $oTpl->assign('error',  $oPublisherDll->_errorMessage);
        $oTpl->assign('notice', $oPublisherDll->_noticeMessage);
    }

    $oTpl->assign('showAdDirect', (defined('OA_AD_DIRECT_ENABLED') && OA_AD_DIRECT_ENABLED === true) ? true : false);
    $oTpl->assign('keyAddNew', $keyAddNew);

    $oTpl->display();

    //footer
    phpAds_PageFooter();
}
?>

<script type="text/javascript">

    var pub = $("#publisher_id").val();

    $("#publisher_id").click(function()
    {
        if(pub == null)
        {
            alert("No Publisher available!");
            return false;
        }
    });

    var apptype = $("input[name=apptype]").val();
    $('#app_type'+apptype).attr('checked', true);


    var version = $("input[name=appversion]").val();
    $('#version'+version).attr('checked', true);

    $("#bundle_id").val($('input[name=bundleid]').val());
    $("#app_url").val($('input[name=appurl]').val());
    $("#app_pp").val($('input[name=privacy]').val());

    if(apptype){
        show_appad(apptype);
    } else{
        $('#app_type1').attr('checked', true);
        show_appad(1);
        // if(!'".$_GET['affiliateid']."')
        //         {
        //             $('#app_type1').trigger('click');
        //             show_appad(1);
        //         }
        //         else
        //         {
        //             show_appad(0);
        //         }
        // show_appad(0);
    }

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

        var type = $(this).val();
        show_appad(type);
    });

    function show_appad(type){

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

            $("input[name=app_version]").parent().parent().show();
            $("#bundle_id").parent().parent().show();
            $("#app_url").parent().parent().show();
            $("#app_pp").parent().parent().show();

            $("#website").parent().parent().hide();
            $("#name").parent().parent().show();
            $("#contact").parent().parent().show();
            $("#email").parent().parent().show();
            $("input[name=programatic_deal]").parent().parent().show();
            $("input[name=open_market]").parent().parent().show();

        } else if(type == 3){
            
            $("input[name=app_version]").parent().parent().hide();
            $("#bundle_id").parent().parent().hide();
            $("#app_url").parent().parent().hide();
            $("#app_pp").parent().parent().hide();

            $("#website").parent().parent().show();
            $("#name").parent().parent().show();
            $("#contact").parent().parent().show();
            $("#email").parent().parent().show();
            $("input[name=programatic_deal]").parent().parent().show();
            $("input[name=open_market]").parent().parent().show();
        }else{

            $("#name").parent().parent().hide();
            $("#contact").parent().parent().hide();
            $("#email").parent().parent().hide();
            $("#website").parent().parent().hide();

            $("input[name=app_version]").parent().parent().hide();
            $("#bundle_id").parent().parent().hide();
            $("#app_url").parent().parent().hide();
            $("#app_pp").parent().parent().hide();
            $("input[name=programatic_deal]").parent().parent().hide();
            $("input[name=open_market]").parent().parent().hide();
        }
    }


</script>
