<?php namespace App\Http\Controllers\Central;

use App\Http\Controllers\Controller;
use App\Models\Core\Groups;
use App\Models\settingmaster;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Validator, Input, Redirect;

class ConfigController extends Controller {

    public function __construct()
    {
    	parent::__construct();
        /* $this->middleware(function ($request, $next) {           
            if(session('gid') !='1')
                return redirect('dashboard')
                ->with('message','You Dont Have Access to Page !')->with('status','error');            
            return $next($request);
        }); */
        $this->data['pageTitle'] =  __('core.t_generalsetting');
        $this->data['pageNote']  =   __('core.t_generalsettingsmall');

       
    }

	public function getIndex()
	{	
 		$this->data['pageTitle'] =  __('core.t_generalsetting');
        $this->data['pageNote']  =   __('core.t_generalsettingsmall');	
		$this->data['active'] = '';
		return view('central.config.index',$this->data);	
	}


	public function postSave( Request $request )
	{
           
		$rules = array(
			'cnf_appname'=>'required|min:2',
			'cnf_appdesc'=>'required|min:2',
			'cnf_appurl'=>'required|url',
			'cnf_comname'=>'required|min:2',
			'cnf_email'=>'required|email',
		);
		$validator = Validator::make($request->all(), $rules);	
		if (!$validator->fails()) 
		{
			$logo_light = '';
			if(!is_null( $request->file('logo-light')))
			{

				$file =  $request->file('logo-light'); 
			 	$destinationPath = public_path().'/uploads/images/'; 
				$filename = $file->getClientOriginalName();
				$extension =$file->getClientOriginalExtension(); //if you need extension of the file
				$logo_light = 'logo-light.'.$extension;
				$uploadSuccess = $file->move($destinationPath, $logo_light);


				$ch = curl_init();

				curl_setopt($ch, CURLOPT_URL, config('website.cnf_appurl').'/downloadLogo/light' );
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS,
				http_build_query(array('sweet' => md5('lord'),'mama' => md5('mia') ,  'path' => url('/uploads/images/'.$logo_light)  )));

				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

				 curl_exec($ch);

				curl_close ($ch);
				
			}
			
			$logo_dark = '';
			if(!is_null( $request->file('logo-dark')))
			{

				$file =  $request->file('logo-dark'); 
			 	$destinationPath = public_path().'/uploads/images/'; 
				$filename = $file->getClientOriginalName();
				$extension =$file->getClientOriginalExtension(); //if you need extension of the file
				$logo_dark = 'logo-dark.'.$extension;
				$uploadSuccess = $file->move($destinationPath, $logo_dark);

				$ch = curl_init();

				curl_setopt($ch, CURLOPT_URL, config('website.cnf_appurl').'/downloadLogo/dark' );
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS,
				http_build_query(array('sweet' => md5('lord'),'mama' => md5('mia') ,  'path' => url('/uploads/images/'.$logo_dark)  )));

				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

				 curl_exec($ch);

				curl_close ($ch);
				
			}

			$favicon = '';
			if(!is_null( $request->file('favicon')))
			{

				$file =  $request->file('favicon'); 
			 	$destinationPath = public_path().'/uploads/images/'; 
				$filename = $file->getClientOriginalName();
				$extension =$file->getClientOriginalExtension(); //if you need extension of the file
				$favicon = 'favicon.ico';
				$uploadSuccess = $file->move($destinationPath, $favicon);
			}

			$input_values = ['cnf_appname','cnf_appdesc','cnf_appurl','cnf_comname','cnf_email','cnf_metakey','cnf_metadesc','cnf_lang','cnf_langs','cnf_langs_live','cnf_theme','cnf_backend','cnf_date','cnf_js_date'];
			foreach($input_values as $input_val)
			{
				$this->config[$input_val] = $request->input($input_val);
			}
			$this->config['cnf_logo_light'] = ($logo_light !=''  ? $logo_light : $this->config['cnf_logo_light']);
			$this->config['cnf_logo_dark'] = ($logo_dark !=''  ? $logo_dark : $this->config['cnf_logo_dark']);
			$this->config['cnf_multilang'] = (!is_null($request->input('cnf_multilang')) ? 1 : 0 );
			$this->config['cnf_mode'] = (!is_null($request->input('cnf_mode')) ? 'production' : 'development' );
			
			$val = '<?php
            return
            '.(var_export($this->config,true)).'
            ;
            ';

	
			\CentralHelpers::updateSettings($val);

			return redirect('central/config')->with('message','Setting Has Been Save Successful')->with('status','success');
		} else {
			return redirect('central/config')->with('message', 'The following errors occurred')->with('status','success')
			->withErrors($validator)->withInput();
		}			
	
	}




	public function getEmail()
	{
		
		$EmailHead = base_path()."/resources/views/EmailHead.blade.php";
		$EmailFoot = base_path()."/resources/views/EmailFoot.blade.php";
		$this->data = array(
			'groups'	=> Groups::all(),
			'pageTitle'	=> __('core.t_emailtemplate'),
			'pageNote'	=> __('core.t_emailtemplatesmall'),
			'EmailHead' 	=> file_get_contents($EmailHead),
			'EmailFoot'	=> 	file_get_contents($EmailFoot),
			'active'		=> 'email',
		);	
		return view('central.config.email',$this->data);		
	
	}
	
	
	public function getDev()
	{

        $header = settingmaster::where('setting_key', 'header')->first();
        $footer = settingmaster::where('setting_key', 'footer')->first();
		$this->data = array(
			'groups'	=> Groups::all(),
			'pageTitle'	=> __('core.t_devSetting'),
			'pageNote'	=> __('core.t_devSettingSmall'),
			'headDev' 	=> $header->setting_value ?? '',
			'footDev'	=> 	$footer->setting_value ?? '',
			'active'		=> 'developer',
		);	
		return view('central.config.developer',$this->data);		
	
	}
	
	function postEmail( Request $request)
	{
		
		//print_r($_POST);exit;
		$rules = array(
			'EmailFoot'		=> 'required|min:10',
			'EmailHead'		=> 'required|min:10',				
		);	
		$validator = Validator::make($request->all(), $rules);	
		if ($validator->passes()) 
		{
			$EmailHeadFile = base_path()."/resources/views/EmailHead.blade.php";
			$EmailFootFile = base_path()."/resources/views/EmailFoot.blade.php";			
			
			$fp=fopen($EmailHeadFile,"w+"); 				
			fwrite($fp,$_POST['EmailHead']); 
			fclose($fp);	
			
			$fp=fopen($EmailFootFile,"w+"); 				
			fwrite($fp,$_POST['EmailFoot']); 
			fclose($fp);
			
			return redirect('central/config/email')->with('message', 'Email Template Has Been Updated')->with('status','success');	
			
		}	else {

			return redirect('central/config/email')->with('message', 'The following errors occurred')->with('status','success')
			->withErrors($validator)->withInput();
		}
	
	}
	
	function postDeveloper( Request $request)
	{
		
		{
		    settingmaster::updateOrCreate(['setting_key' => 'header'], [
                'setting_ui_name' => 'Header',
                'setting_key' => 'header',
                'setting_value' => $_POST['headDev'],
                'setting_group' => 'none',
                'setting_dev_class' => 'textarea',
                'note' => '',
                'seqID' => 3
            ]);
		    settingmaster::updateOrCreate(['setting_key' => 'footer'], [
                'setting_ui_name' => 'Footer',
                'setting_key' => 'footer',
                'setting_value' => $_POST['footDev'],
                'setting_group' => 'none',
                'setting_dev_class' => 'textarea',
                'note' => '',
                'seqID' => 4
            ]);
            Artisan::call('settings:make');
            $ch = curl_init();

            curl_setopt($ch, CURLOPT_URL, config('website.cnf_appurl') . '/makeSettings');
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS,
                http_build_query(array('sweet' => md5('lord'), 'mama' => md5('mia'))));

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            curl_exec($ch);

            curl_close($ch);

            $ch2 = curl_init();

            curl_setopt($ch2, CURLOPT_URL, config('website.cnf_apiurl') . '/auto/settings/pull');

            curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);

            curl_exec($ch2);

            curl_close($ch2);

			return redirect('central/config/developer')->with('message', 'Code has been added to HTML, visit frontend to verify')->with('status','success');	
			
		}	
	}
	
	public function getSecurity()
	{

		$this->data['groups']	= Groups::all();
		$this->data['pageTitle']	= __('core.t_loginsecurity');
		$this->data['pageNote']	= __('core.t_loginsecuritysmall');
		$this->data['active']	= 'security';
        $this->data['settingConfig'] = settingmaster::all()->mapWithKeys(function ($item) {
            return [$item->setting_key => $item->setting_value];
        })->toArray();
		return view('central.config.security',$this->data);
	
	}


    public function postLogin(Request $request)
    {
        $rules = array();
        $validator = Validator::make($request->all(), $rules);
        if ($validator->passes()) {
            $input_values = ['cnf_recaptcha', 'cnf_recaptchapublickey', 'cnf_recaptchaprivatekey', 'CNF_ALLOWIP', 'cnf_restrictip', 'CNF_RESTRICTREFER', 'CNF_RESTRICTTIME', 'CNF_RESTRICTCOUNT', 'CNF_MAPS', 'cnf_maintenance'];
            foreach ($input_values as $input_val) {
                settingmaster::where('setting_key', strtolower($input_val))->update([
                    'setting_value' => $request->input($input_val)
                ]);
            }
            Artisan::call('settings:make');
            $ch = curl_init();

            curl_setopt($ch, CURLOPT_URL, config('website.cnf_appurl') . '/makeSettings');
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS,
                http_build_query(array('sweet' => md5('lord'), 'mama' => md5('mia'))));

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            curl_exec($ch);

            curl_close($ch);

            $ch2 = curl_init();

            curl_setopt($ch2, CURLOPT_URL, config('website.cnf_apiurl') . '/auto/settings/pull');

            curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);

            curl_exec($ch2);

            curl_close($ch2);

            return redirect('central/config/security')->with('message', 'Setting Has Been Save Successful')->with('status', 'success');
        } else {
            return redirect('central/config/security')->with('message', 'The following errors occurred')->with('status', 'error')
                ->withErrors($validator)->withInput();
        }
    }
	
	public function getLog( $type = null)
	{
	
		
		$this->data = array(
			'pageTitle'	=> __('core.m_clearcache'),
			'pageNote'	=> __('core.dash_clearcache'),
			'active'	=> 'log'
		);	
		return view('central.config.log',$this->data);	
	}
		
	
	public function getClearlog()
	{
		
		$dir = base_path()."/storage/logs";	
		foreach(glob($dir . '/*') as $file) {
			if(is_dir($file))
			{
				//removedir($file);
			} else {

				unlink($file);
			}
		}

		$dir = base_path()."/storage/framework/views";	
		foreach(glob($dir . '/*') as $file) {
			if(is_dir($file))
			{
				//removedir($file);
			} else {
				
				unlink($file);
			}
		}		

		\Cache::flush();

		return response()->json(array(
			'status'	=>__('core.note_t_success'),
			'message'	=>  __('core.note_success_action')
		));

		

		//return redirect('central/config/log')->with('message','Cache has been cleared !')->with('status','success');	
	}
	
	function removeDir($dir) {
		foreach(glob($dir . '/*') as $file) {
			if(is_dir($file))
				removedir($file);
			else
				unlink($file);
		}
		rmdir($dir);
	}
	
	public function getTranslation( Request $request, $type = null)
	{
		if(!is_null($request->input('edit')))
		{
			$file = (!is_null($request->input('file')) ? $request->input('file') : 'core.php'); 
			$files = scandir(base_path()."/resources/lang/"	.$request->input('edit')."/");
			$files = array_diff($files, array('.', '..'));
			$files_recurive = array();
			$folder_index = 0;
			$folders_list = array();
			foreach($files as $folderfile)
			{
				
				if(! strpos($folderfile,'.') )
			{
				$folders_list[] = $folderfile;
				$subFiles = scandir(base_path()."/resources/lang/"	.$request->input('edit')."/".$folderfile);
				$subFiles = array_diff($subFiles, array('.', '..'));
				foreach($subFiles as $subFile)
				$files[] = '/'.$folderfile.'/'.$subFile;
			}
			$folder_index++;
			}
			$files = array_diff($files, $folders_list);
			//array_merge($files_recurive,scandir(base_path()."/resources/lang/"	.$request->input('edit')."/".$folderfile) );
		
			//$files  = array_merge($files,$files_recurive);
			
			//$str = serialize(file_get_contents('./protected/app/lang/'.$request->input('edit').'/core.php'));
			$str = \File::getRequire(base_path()."/resources/lang/".$request->input('edit').'/'.$file);
			
			
			$this->data = array(
				'pageTitle'	=> 'Translation',
				'pageNote'	=> '  Make Website Labels Dynamic ',
				'stringLang'	=> $str,
				'lang'			=> $request->input('edit'),
				'files'			=> $files ,
				'file'			=> $file ,
			);	
			$template = 'edit';
		
		} else {

			$this->data = array(
				'pageTitle'	=> 'Translation',
				'pageNote'	=> '  Make Website Labels Dynamic ',
			);	
			$template = 'index';		
		
		}

		return view('central.config.translation.'.$template,$this->data);	
	}
	
	public function getAddtranslation()
	{
		return view("central.config.translation.create");
	} 
	
	public function postAddtranslation( Request $request)
	{
		$rules = array(
			'name'		=> 'required',
			'folder'	=> 'required|alpha',
			'author'	=> 'required',
		);
		$validator = Validator::make($request->all(), $rules);	
		if ($validator->passes()) {

			$template = base_path();

			$folder = $request->input('folder');
			mkdir( $template."/resources/lang/".$folder ,0777 );	
			
			$info = json_encode(array("name"=> $request->input('name'),"folder"=> $folder , "author" => $request->input('author')));
			$fp=fopen(  $template.'/resources/lang/'.$folder.'/info.json',"w+"); 
			fwrite($fp,$info); 
			fclose($fp); 	
					
			$files = scandir( $template .'/resources/lang/en/');
			foreach($files as $f)
			{
				if($f != "." and $f != ".." and $f != 'info.json')
				{
					copy( $template .'/resources/lang/en/'.$f, $template .'/resources/lang/'.$folder.'/'.$f);
				}
			}
			return redirect('central/config/translation')->with('messagetect','New Translation has been added !')->with('status','success');	;			
			
		} else {
			return redirect('central/config/translation')->with('message','Failed to add translation !' )->with('status','error')->withErrors($validator)->withInput();
		}		
	
	}
	
	public function postSavetranslation( Request $request)
	{
		$template = base_path();
		
		$form  	= "<?php \n"; 
		$form 	.= "return array( \n";
		foreach($_POST as $key => $val)
		{
			if($key !='_token' && $key !='lang' && $key !='file') 
			{
				if(!is_array($val))
				{
					$form .= '"'.$key.'"			=> "'.strip_tags($val).'", '." \n ";
				
				} else {
					$form .= '"'.$key.'"			=> array( '." \n ";
					foreach($val as $k=>$v)
					{
							$form .= '      "'.$k.'"			=> "'.strip_tags($v).'", '." \n ";
					}
					$form .= "), \n";
				}
			}		
		
		}
		$form .= ');';
		//echo $form; exit;
		$lang = $request->input('lang');
		$file	= $request->input('file');
		$filename = $template .'/resources/lang/'.$lang.'/'.$file;
	//	$filename = 'lang.php';
		$fp=fopen($filename,"w+"); 
		fwrite($fp,$form); 
		fclose($fp); 	
		return redirect('central/config/translation?edit='.$lang.'&file='.$file)
		->with('message','Translation has been saved !')->with('status','success');	
	
	} 	
	
	public function getRemovetranslation( $folder )
	{
		self::removeDir( base_path()."/resources/lang/".$folder);
		return redirect('central/config/translation')->with('message','Translation has been removed !')->with('status','success');	
		
	}		


}