<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use File;
use App\SkinConfig;
use App\Classes\simple_html_dom;
use App\Skin;
use App\Template;

class Site extends Model
{
    protected $fillable = ['is_active', 'url', 'description', 'tag', 'template_id', 'country', 'language', 'updated_by'];

    public function template(){
    	return $this->belongsTo('App\Template');
    }

    public function skins(){
    	return $this->belongsToMany('App\Skin', 'site_skins')->withPivot('begin_date', 'end_date');
    }

    public function user(){
        return $this->belongsTo('App\User', 'updated_by');
    }

    public function domain(){
        return $this->belongsTo('App\Domain');
    }

    public function genericSiteCreator($site_gtm, $skin_default_id, $special_skin_id = null){

        // Create folder in public_html
        $site_directory = '/home/bluemark/sites/'.$this->domain()->first()->domain.'/';
        if(!File::exists($site_directory)) {
            flash('Pasta não existe.')->warning();
            return false;
        }

        // Get template
        $template = Template::find($this->template_id);
        $contents = File::get(public_path($template->file_path));
        // Crawl html code
        $dom = new simple_html_dom();
        $dom->load($contents);


        //Skin Default
        $skin_configs = SkinConfig::where('skin_id', $skin_default_id)->where('type', 'html')->get();

        foreach($skin_configs as $key => $config){
            $field_number = str_after($config->item_name, 'field');

            if ($dom->find('.lp_edit', (int)$field_number-1)->tag == 'img'){
                $dom->find('.lp_edit', (int)$field_number-1)->setAttribute('src', $config->value);
            } else if ($dom->find('.lp_edit', (int)$field_number-1)->tag == 'i'){
                $replace = str_replace('fa', $config->value, $dom->find('.lp_edit', (int)$field_number-1)->outertext);
                $dom->find('.lp_edit', (int)$field_number-1)->setAttribute('outertext', $replace);
            } else if ($config->item_name == 'field_meta1') {
                $field_meta = str_after($config->item_name, 'field_meta');
                $dom->find( ".lp_meta", $field_meta-1)->setAttribute('content', utf8_decode($config->value));
            } else  if ($config->item_name == 'field_meta2') {
                $field_meta = str_after($config->item_name, 'field_meta');
                $dom->find( ".lp_meta", $field_meta-1)->setAttribute('content', utf8_decode($config->value));
            } else{
                $dom->find('.lp_edit', (int)$field_number-1)->setAttribute('innertext', utf8_decode($config->value));
            }
        }
        //echo '<pre>' . $config;
        //dd('fim');
         //dd($skin_default_id);
        $skin_css_default = SkinConfig::where('skin_id', $skin_default_id)->where('type', 'css')->first();
        $css_code_default = $skin_css_default->value;


        // Special Skin
        if($special_skin_id != null) {
            $skin_configs = SkinConfig::where('skin_id', $special_skin_id)->where('type', 'html')->get();

            foreach($skin_configs as $key => $config){
                $field_number = str_after($config->item_name, 'field');
                if($dom->find('.lp_edit', (int)$field_number-1)->tag == 'img'){
                    $dom->find('.lp_edit', (int)$field_number-1)->setAttribute('src', $config->value);
                }else if($dom->find('.lp_edit', (int)$field_number-1)->tag == 'i'){
                    $replace = str_replace('fa', $config->value, $dom->find('.lp_edit', (int)$field_number-1)->outertext);
                    $dom->find('.lp_edit', (int)$field_number-1)->setAttribute('outertext', $replace);
                }else{
                    $dom->find('.lp_edit', (int)$field_number-1)->setAttribute('innertext', utf8_decode($config->value));
                }
            }

            // $skin_css_special = SkinConfig::where('skin_id', $skin_default_id)->where('type', 'css')->get();
            // $css_code_special = $skin_css_special->value;
        }

        $content = trim(preg_replace('/\t/', '', trim($dom->innertext)));
        $content = trim(preg_replace('/\r/', '', trim($content)));

        $content = str_replace('GTM-EXAMPLE', $site_gtm, $content);

        $phpcode = '<?php
            include("/home/bluemark/sites/bma24.com/Chat/landings/con.php");
            include("/home/bluemark/sites/bma24.com/Chat/landings/templating.php");

            $utm_source = $_GET["utm_source"];
            $utm_campaign = $_GET["utm_campaign"];

            $custom_style = getTemplatingCSS($utm_campaign, $utm_source, $con);
            
            include("/home/bluemark/sites/bma24.com/Chat/pptcpc/policies.php");
        ?>';

        $php_head_code = '<?php
              if($custom_style != "fail"){
                  echo $custom_style;
              }
          ?>';

        $content = $phpcode . $content;

        $content = str_replace('<phpcode></phpcode>', $php_head_code, $content);
        // dd($content);

		$htaccessCode = '
        RewriteEngine On
        RewriteCond %{HTTPS} !=on
        RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

        RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
        RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [R=301,QSA,NC,L]
        <ifModule mod_headers.c> 
        Header set Connection keep-alive 
        </ifModule>';

        File::put($site_directory . 'index.php', utf8_encode($content)); //This is Template File. Copy template file to this path with the name index.html
        File::put($site_directory . 'style.css', $css_code_default); //This is Template File. Copy template file to this path with the name index.html

        if(File::exists($site_directory . '.htaccess')) {
            File::delete($site_directory . '.htaccess');
        }

		File::put($site_directory . '.htaccess', $htaccessCode); //This is htacess code to implement https url.

    }
}
