<?php

    define("DEBUG_EMAIL", "fernando.nascimento@arcasolutions.com");

    if ($_SERVER["HTTP_USER_AGENT"] == "eDirectoryOrdersPage_ArcaSolutions") {
	    
        define("SELECTED_DOMAIN_ID", 1);
        define("EDIRECTORY_ROOT", $_SERVER["DOCUMENT_ROOT"]);

        include_once(EDIRECTORY_ROOT."/functions/system_funct.php");
        include_once(EDIRECTORY_ROOT."/automation/register_funct.php");
        include_once(EDIRECTORY_ROOT."/classes/autoload.php");

        $s = DIRECTORY_SEPARATOR;
        $symfonyCore = EDIRECTORY_ROOT . "{$s}classes{$s}class_SymfonyCore.php";

        if (file_exists($symfonyCore)) {
            require_once $symfonyCore;
            SymfonyCore::initialize();
        } else {
            $mailMessage = "Unable to initialize framework.";
            mail(DEBUG_EMAIL, "account activation debug", $mailMessage);
            exit();
        }

        /*
        * POOL DB info
        */

        //DB host
        $pool_Host = "localhost";
        //DB port
        $pool_Port = "";
        //DB username
        $pool_Username = "automation";
        //DB password
        $pool_Password = "yn6xbn";
        //DB name
        $pool_DBName = "install_automation";

        //domainID - always 1 in production
        $domainID = 1;
        
        $mailMessage = "";

        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            
            extract($_POST);
            
            $mailMessage = "Starting Process\n";
            
            if (isset($feature_branding) && isset($feature_mobile)) {
                
                $mailMessage .= "Prepare to rewrite constants file.\n";
                
                //Rewrite constants file
                $fileConstPath = EDIRECTORY_ROOT."/custom/domain_".SELECTED_DOMAIN_ID."/conf/constants.inc.php";
                $constValues = array();
                
                //Default values
                $constValues["event_feature"] = "on";
                $constValues["banner_feature"] = "on";
                $constValues["classified_feature"] = "on";
                $constValues["article_feature"] = "on";
                $constValues["promotion_feature"] = "on";
                $constValues["blog_feature"] = "on";
                $constValues["zipproximity_feature"] = "on";
                
                $constValues["custominvoice_feature"] = "on";
                $constValues["claim_feature"] = "on";
                $constValues["listingtemplate_feature"] = "on";
                $constValues["multilanguage_feature"] = "on";
                $constValues["maintenance_feature"] = "on";
                
                $constValues["sitemap_feature"] = "on";
                $constValues["paymentsystem_feature"] = "on";
                $constValues["name"] = "eDirectory";
                $constValues["geoip_feature"] = "on";
                $constValues["date_format"] = ($lang == "en" ? "m/d/Y" : "d/m/Y");
                $constValues["clock_type"] = ($lang == "en" ? "12" : "24");

                $constValues["jpg_as_png"] = "off";
                $constValues["resize_images"] = "on";
                $constValues["sitemap_www"] = "off";
                
                $constValues["alias_listing_module"] = ($lang == "en" ? "listing" : "empresa");
                $constValues["alias_promotion_module"] = ($lang == "en" ? "deal" : "oferta");
                $constValues["alias_event_module"] = ($lang == "en" ? "event" : "evento");
                $constValues["alias_article_module"] = ($lang == "en" ? "article" : "artigo");
                $constValues["alias_classified_module"] = ($lang == "en" ? "classified" : "classificado");
                $constValues["alias_blog_module"] = "blog";

                $constValues["alias_claim_url_divisor"] = ($lang == "en" ? "claim" : "solicite");
                $constValues["alias_review_url_divisor"] = ($lang == "en" ? "reviews" : "avaliacoes");
                $constValues["alias_checkin_url_divisor"] = "checkins";
                $constValues["alias_listing_allcategories_url_divisor"] = ($lang == "en" ? "allcategories" : "categorias");
                $constValues["alias_event_allcategories_url_divisor"] = ($lang == "en" ? "allcategories" : "categorias");
                $constValues["alias_article_allcategories_url_divisor"] = ($lang == "en" ? "allcategories" : "categorias");
                $constValues["alias_classified_allcategories_url_divisor"] = ($lang == "en" ? "allcategories" : "categorias");
                $constValues["alias_promotion_allcategories_url_divisor"] = ($lang == "en" ? "allcategories" : "categorias");
                $constValues["alias_blog_allcategories_url_divisor"] = ($lang == "en" ? "allcategories" : "categorias");
                $constValues["alias_alllocations_url_divisor"] = ($lang == "en" ? "alllocations" : "localidades");
                $constValues["alias_advertise_url_divisor"] = ($lang == "en" ? "advertise" : "anuncie");
                $constValues["alias_contactus_url_divisor"] = ($lang == "en" ? "contactus" : "contato");
                $constValues["alias_faq_url_divisor"] = "faq";
                $constValues["alias_sitemap_url_divisor"] = ($lang == "en" ? "sitemap" : "mapa");
                $constValues["alias_lead_url_divisor"] = ($lang == "en" ? "enquire" : "solicite");
                $constValues["alias_terms_url_divisor"] = ($lang == "en" ? "terms" : "termos");
                $constValues["alias_privacy_url_divisor"] = ($lang == "en" ? "privacy" : "privacidade");
		
                define("LISTING_FEATURE_NAME", ($lang == "en" ? "listing" : "empresa"));
                define("PROMOTION_FEATURE_NAME", ($lang == "en" ? "deal" : "oferta"));
                define("EVENT_FEATURE_NAME", ($lang == "en" ? "event" : "evento"));
                define("CLASSIFIED_FEATURE_NAME", ($lang == "en" ? "classified" : "classificado"));
                define("ARTICLE_FEATURE_NAME", ($lang == "en" ? "article" : "artigo"));
                define("BLOG_FEATURE_NAME", "blog");
                define("BANNER_FEATURE_NAME", "banner");
                define("BRANDED_PRINT",($feature_branding == "on" ? "on" : "off"));
                
                $constValues["mobile_feature"] = ($feature_mobile == "on" ? "on" : "off");
                $constValues["branded_print"] = ($feature_branding == "on" ? "on" : "off");

                if (!system_writeConstantsFile($fileConstPath, SELECTED_DOMAIN_ID, $constValues)) {
                    $return["success"] = false;
                    $return["message"] = "Could not rewrite constants file. Check permissions in folder /custom";
                    $mailMessage .= "Could not rewrite constants file. Check permissions in folder /custom \n";
                } else {

                    // creates yamls file
                    //$path = EDIRECTORY_ROOT.'/../app/config/domain.yml';
                    //copy($path.'/domain.configs.yml.sample', $path.'/'.$domain.'.configs.yml');
                    //copy($path.'/domain.payment.yml.sample', $path.'/'.$domain.'.payment.yml');
                    //copy($path.'/domain.route.yml.sample', $path.'/'.$domain.'.route.yml');

                    //Rewrite htaccess
                    if ($lang == "pt") {
                        $htaccesscontent = file_get_contents(EDIRECTORY_ROOT."/.htaccess");
                        $htaccesscontent = str_replace("advertise", "anuncie", $htaccesscontent);
                        $htaccesscontent = str_replace("claim", "solicite", $htaccesscontent);
                        $htaccesscontent = str_replace("(listing)", "(empresa)", $htaccesscontent);
                        $htaccesscontent = str_replace("(event)", "(evento)", $htaccesscontent);
                        $htaccesscontent = str_replace("(classified)", "(classificado)", $htaccesscontent);
                        $htaccesscontent = str_replace("(article)", "(artigo)", $htaccesscontent);
                        $htaccesscontent = str_replace("anuncie.php", "advertise.php", $htaccesscontent);

                        file_put_contents(EDIRECTORY_ROOT."/.htaccess", $htaccesscontent);

                        $routes = array();
                        foreach($constValues as $key => $constaValue) {
                            if (strpos($key, "alias_") !== false) {
                                $routes[$key] = $constaValue;
                            }
                        }

                        // saves configuration in yaml file
                        $classSymfonyYml = new Symfony('domains/'.$domain.'.route.yml');
                        $classSymfonyYml->save('Configs', array('parameters' => $routes));
                        unset($classSymfonyYml);
                    }
                    
                    //Update table Domain
                    $mailMessage .= "Update table Domain\n";

                    if (isset($domain) && isset($domain_name) && isset($edir_db_host) && isset($edir_db_port) && isset($edir_db_user) && isset($edir_db_pass) && isset($edir_db_name) && isset($edir_version)) {

                        $edir_version = "v.".$edir_version;
                        $edir_main_db_name = str_replace("_domain1", "_main", $edir_db_name);
                        $edir_domain_db_name = $edir_db_name;

                        //Connection with Main DB
                        $mainlink = mysql_connect($edir_db_host, $edir_db_user, $edir_db_pass);
                        mysql_query("SET NAMES 'utf8'", $mainlink);
                        mysql_query('SET character_set_connection=utf8', $mainlink);
                        mysql_query('SET character_set_client=utf8', $mainlink);
                        mysql_query('SET character_set_results=utf8', $mainlink);
                        $db_selected = mysql_select_db($edir_main_db_name, $mainlink);
                        
                        //Truncate table Domain
                        $mailMessage .= "Truncate table Domain\n";
                        $sqlTrunc = "TRUNCATE `Domain`";
                        mysql_query($sqlTrunc, $mainlink);
                        
                        $mailMessage .= "Insert info on table Domain\n";
                        $sql = "INSERT INTO Domain"
                            . " (id, smaccount_id, name, database_host, database_port, database_username, database_password, database_name, url, status, activation_status, created, article_feature, banner_feature, classified_feature, event_feature, subfolder)"
                            . " VALUES"
                            . " ($domainID, 0, 'eDirectory', '".$edir_db_host."', '".$edir_db_port."', '".$edir_db_user."', '".$edir_db_pass."', '".$edir_domain_db_name."', '".$domain."', 'A','A',  CURDATE(), 'on', 'on', 'on', 'on', '')";
                            
                        $results = mysql_query($sql, $mainlink);
                        if (!$results) {
                            $mailMessage .= "SQL error: ".mysql_error()." \n";
                            $return["success"] = false;
                            $return["message"] = "SQL error:".mysql_error()."";

                        } else {
                        
                        	if ($customer_email) {
                                $mailMessage .= "Update sitemgr username\n";
                                $sqlSetting = "UPDATE Setting SET value = '$customer_email' WHERE name ='sitemgr_username' ";
                                mysql_query($sqlSetting, $mainlink);
	                        } else {
	                            $mailMessage .= "Update sitemgr username: email not found. Username not changed.\n";
	                        }

                            //Change sitemgr and frontend language
                            if ($lang == "pt") {
                                $mailMessage .= "Change sitemgr and frontend language\n";
                                $sqlSetting = "UPDATE Setting SET value = 'pt_br' WHERE name ='sitemgr_language' ";
                                mysql_query($sqlSetting, $mainlink);

                                //Rewrite language file
                                $filePath = EDIRECTORY_ROOT.'/custom/domain_1/lang/language.inc.php';
                                $file = fopen($filePath, 'w+');
                                $buffer = "<?php".PHP_EOL;
                                $buffer .= "\$edir_default_language = \"pt_br\";".PHP_EOL.PHP_EOL;
                                $buffer .= "\$edir_default_languagenumber = \"2\";".PHP_EOL.PHP_EOL;
                                $buffer .= "\$edir_languages = \"pt_br\";".PHP_EOL;
                                $buffer .= "\$edir_languagenames = \"Português\";".PHP_EOL;
                                $buffer .= "\$edir_languagenumbers = \"2\";".PHP_EOL;

                                fwrite($file, $buffer, strlen(utf8_encode($buffer)));
                                fclose($file);
                            }

                            //Update domain.yml with the new site URL
                            $domainYML = file_get_contents(EDIRECTORY_ROOT.'/../app/config/domain.yml');
                            $domainYML = str_replace("automation.arcasolutions.com", $domain, $domainYML);
                            file_put_contents(EDIRECTORY_ROOT.'/../app/config/domain.yml', $domainYML);

                            // saves name site in yml file
                            $classSymfonyYml = new Symfony('domain.yml');
                            $theme_domain = array(
                                'multi_domain' => array(
                                    'hosts' => array(
                                        $domain => array(
                                            'branded' => ($feature_branding == "on" ? "on" : "off"),
                                            'locale'  => ($lang == "en" ? "en-us" : "pt_br"),
                                        )
                                    )
                                )
                            );
                            $classSymfonyYml->save('Configs', $theme_domain);
                            unset($classSymfonyYml);
                        
	                        //Update domain.inc.php
	                        $mailMessage .= "Update domain.inc.php\n";
	                        $sql = "SELECT `id`, `url` FROM `Domain` WHERE `status` = 'A'";
	                        $result = mysql_query($sql, $mainlink);
	                        if (mysql_num_rows($result) > 0) {
	                            $domainFilePath = EDIRECTORY_ROOT."/custom/domain/domain.inc.php";
	                            $domainFile = fopen($domainFilePath, "w+");
	                            unset($buffer);
	                            $buffer = "<?".PHP_EOL;
	                            while ($row = mysql_fetch_assoc($result)) {
	                                $buffer .= "\$domainInfo[\"".$row["url"]."\"] = ".$row["id"].";".PHP_EOL;
	                            }
	                            $buffer .= "?>".PHP_EOL;
	                            fwrite($domainFile, $buffer, strlen($buffer));
	                            fclose($domainFile);
	                            
	                            //Update pool
	                            $mailMessage .= "Update pool\n";
	                            if ($pool_id && $pool_oid) {
	
	                                //Connection with Pool DB
	                                $link = mysql_connect($pool_Host, $pool_Username, $pool_Password);
	                                mysql_query("SET NAMES 'utf8'", $link);
	                                mysql_query('SET character_set_connection=utf8', $link);
	                                mysql_query('SET character_set_client=utf8', $link);
	                                mysql_query('SET character_set_results=utf8', $link);
	                                mysql_select_db($db);
	
	                                $sql = "UPDATE `install_automation`.`account_pool` SET status = 'U', oid_number = $pool_oid, updated = NOW() WHERE id =  $pool_id";
	                                mysql_query($sql, $link);
	
	                                $return["success"] = true; 
	                                $return["message"] = "ok"; 
	                                
	                                //Register
	                                $data["customer_url"] = $domain_name;
	                                $data["customer_database_name"] = $edir_main_db_name;
	                                $data["customer_version"] = $edir_version;
	                                $data["customer_feature_mobile"] = ($feature_mobile == "on" ? "on" : "off");
	                                $data["customer_feature_branding"] = ($feature_branding == "on" ? "on" : "off");
	                                
	                                define("_DIRECTORYDB_HOST",  $edir_db_host);
                                    define("_DIRECTORYDB_USER",  $edir_db_user);
                                    define("_DIRECTORYDB_PASS",  $edir_db_pass);
				        
	                                $mailMessage .= "Call register function\n";
	                                GetLicenseNumber($data);
	                            } else {
	                                $return["success"] = false; 
	                                $return["message"] = "Missing one or more parameters (pool_id, pool_oid)."; 
	                                $mailMessage .= "Missing one or more parameters (pool_id, pool_oid).\n";
	                            }
	
	                        }
                        } 
                    } else {
                        $return["success"] = false; 
                        $return["message"] = "Missing one or more parameters (domain, domain_name, edir_db_host, edir_db_port, edir_db_user, edir_db_pass, edir_db_name, edir_version)."; 
                        $mailMessage .= "Update table Domain: Missing one or more parameters (domain, domain_name, edir_db_host, edir_db_port, edir_db_user, edir_db_pass, edir_db_name, edir_version).\n";
                    }
                    
                }
                
            } else {
                $return["success"] = false; 
                $return["message"] = "Missing features branding and/or mobile."; 
                
                $mailMessage .= "Error - Missing features branding and/or mobile.\n";
            }
            
            header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");
            header("Cache-Control: no-store, no-cache, must-revalidate");
            header("Cache-Control: post-check=0, pre-check=0", FALSE);
            header("Pragma: no-cache");
            header("Content-Type: application/json; charset=UTF-8", TRUE);
            echo json_encode($return); 
            mail(DEBUG_EMAIL, "account activation debug", $mailMessage);
            exit;
            
            
        } else {
        	$mailMessage = "Invalid request method";
        }

    } else {
    	$mailMessage = "Invalid user agent and/or http referer";
    }
    mail(DEBUG_EMAIL, "account activation debug", $mailMessage);