<?php

use Illuminate\Database\Capsule\Manager as Capsule;

if (!class_exists('MenuDbHandler')) {
	class MenuDbHandler {
	   private $themeprefix;
	   private $table_name;
	   public $field_list;  	
	   public $default;
	   public $settings;
	   public $settings_default_value;
	   public $core_urls;
	   function __construct($options) {
	       $this->themeprefix = $options['themeprefix'];
	       $this->table_name = 'mod_'.$this->themeprefix.'_menu_items';
	       $this->settings_table_name = 'mod_'.$this->themeprefix.'_menu_settings';

	       $this->settings_default_value = [
	       		"show_side_bar_munu" => '',
	       ];

	       $this->field_list = [
	       		'icon','name','url','soft_order','status','parent_id',
	       		'only_for_guest','only_for_user','class','id','url_type','preinstalled','show_type','show_for_id'
	       ];
		   $this->default = [
				    'icon' => '',
				    'name' => '',
				    'url' => '',
				    'soft_order' => '10',
				    'status' => '2',
				    'parent_id' => '0',
					'only_for_guest' => '0',
					'only_for_user' => '0',
					'new_window' => '0',
					'url_type' => '2',
					'class' => '',
					'preinstalled'=> 0,
					'show_type'=>0,
					'show_for_id'=>-1,
			];


			$this->core_urls = [
				//Core WHMCS Guest URLs
				0 => [
					'/index.php'=>'Portal',
					'/announcements.php'=>'Announcements',
					'/knowledgebase.php'=>'Knowledgebase',
					'/cart.php'=>'Cart',
					'/downloads.php'=>'Downloads'
				],
				//Core WHMCS Client URLs
				1 => [
					'/clientarea.php'=>'Client Summary',
					'/serverstatus.php'=>'Server Status',
					'/supporttickets.php'=>'Support Tickets',
					'/clientarea.php?action=services'=>'My Services',
					'/cart.php?gid=addons'=>'View Available Addons',
					'/clientarea.php?action=domains'=>'My Domains',
					'/cart.php?gid=renewals'=>'Renew Domains',
					'/clientarea.php?action=invoices'=>'My Invoices',
					'/clientarea.php?action=creditcard'=>'Manage Credit Card',
					'/clientarea.php?action=quotes'=>'My Quotes',
					'/clientarea.php?action=masspay&all=true'=>'Mass Payment',
					'/clientarea.php?action=details'=>'Edit Account Details',
					'/clientarea.php?action=contacts'=>'Contacts/Sub-Accounts',
					'/clientarea.php?action=emails'=>'Emails Sent',
					'/clientarea.php?action=changepw'=>'Change Password',
					'/logout.php'=>'Logout',
				]

			];

			$this->settings_load();
				       
	   }

	   public function migrate(){

		    if (!Capsule::schema()->hasTable($this->table_name)) {
		            try {
		                Capsule::schema()->create(
		                    $this->table_name,
		                    function ($table) {
		                        $table->increments('id');
		                        $table->string('icon');
		                        $table->string('name');
		                        $table->string('url');
		                        $table->integer('soft_order');
		                        $table->integer('status');
		                        $table->integer('parent_id');

		                        $table->integer('only_for_guest');
		                        $table->integer('only_for_user');
		                        $table->integer('new_window')->default('0');
		                        $table->integer('show_type')->default('0');
		                        $table->integer('show_for_id')->default('-1');
		                        $table->integer('url_type')->default('0');
		                        $table->integer('preinstalled')->default('0');

		                        $table->string('class');
		                        
	                        
		                        $table->timestamps('dlm');

		                        $table->index(['parent_id']);
		                        $table->index(['soft_order']);
		                    }
		                );
		            } catch (\Exception $e) {
		                echo "Unable to create ".$this->table_name.": {$e->getMessage()}";
		            }

				$this->migrate4();

		        return true;
		   }else{
		   		return false;
		   }
	   
	   }


	   public function migrate1(){
	        if (Capsule::schema()->hasTable($this->table_name)) {
	          if (!Capsule::schema()->hasColumn($this->table_name, 'new_window')) {

	                try {
	                    Capsule::schema()->table($this->table_name, function ($table) {
	                        $table->integer('new_window')->default('0');
	                        $table->integer('url_type')->default('2');
	                    });
	                } catch (\Exception $e) {
	                        echo "Unable to update ".$this->table_name.": {$e->getMessage()}";
	                        exit;
	                }


	          }
	        }
	   }

	   public function migrate2(){
	        if (Capsule::schema()->hasTable($this->table_name)) {
	          if (!Capsule::schema()->hasColumn($this->table_name, 'preinstalled')) {

	                try {
	                    Capsule::schema()->table($this->table_name, function ($table) {
	                        $table->integer('preinstalled')->default('0');
	                    });
	                } catch (\Exception $e) {
	                        echo "Unable to update ".$this->table_name.": {$e->getMessage()}";
	                        exit;
	                }

	            return true;    
	          }else{ 
	          	return false;
	          }
	        }
	   }
	   public function migrate3(){
	        if (Capsule::schema()->hasTable($this->table_name)) {
	          if (!Capsule::schema()->hasColumn($this->table_name, 'show_type')) {

	                try {
	                    Capsule::schema()->table($this->table_name, function ($table) {
	                        $table->integer('show_type')->default('0');
	                        $table->integer('show_for_id')->default('-1');
	                    });
	                } catch (\Exception $e) {
	                        echo "Unable to update ".$this->table_name.": {$e->getMessage()}";
	                        exit;
	                }


	          }
	        }
	   }

	   public function migrate4(){

		    if (!Capsule::schema()->hasTable($this->settings_table_name)) {
		            try {
		                Capsule::schema()->create(
		                    $this->settings_table_name,
		                    function ($table) {
		                        $table->increments('id');
		                        $table->string('setting');
		                        $table->mediumText('value');
	                        	$table->timestamps('dlm');
		                        $table->index(['setting']);
		                    }
		                );
		            } catch (\Exception $e) {
		                echo "Unable to create ".$this->settings_table_name.": {$e->getMessage()}";
		            }
		        return true;
		   }else{
		   		return false;
		   }
	   
	   }


	   public function migrateDown(){
	   		Capsule::schema()->dropIfExists($this->table_name);
	   }

	   public function create($item){
			return Capsule::table($this->table_name)->insertGetId(
			    [
				    'icon' => $item->icon,
				    'name' => $item->name,
				    'url' => $item->url,
				    'soft_order' => $item->soft_order,
				    'status' => $item->status,
				    'parent_id' => $item->parent_id,
					'only_for_guest' => $item->only_for_guest,
					'only_for_user' => $item->only_for_user,
					'url_type' => $item->url_type,
					'new_window' => $item->new_window,

					'show_type' => $item->show_type,
					'show_for_id' => $item->show_for_id,

					'preinstalled' => $item->preinstalled,

					'class' => $item->class,

				    'created_at' => date("Y-m-d H:i:s"),
				    'updated_at' => date("Y-m-d H:i:s")
			    ]
			);
	   }

	   function setting_get($setting){
	   		if(isset($this->settings[$setting])){
	   			return $this->settings[$setting];
	   		}else {
	   			if (isset($this->settings_default_value[$setting])){
	   				return $this->settings_default_value[$setting];
	   			}else{
	   				return null;	
	   			}
	   		}
	   }

	   function setting_update($setting,$value){
		    $r = Capsule::table($this->settings_table_name)->select('setting', 'value')
		            ->where('setting', $setting)
		            ->get();

		    if (!isset($r[0])){
		            Capsule::table($this->settings_table_name)->insert(
		                [
		                'setting' => $setting,
		                'value' => $value
		                ]
		            );
		    }else{
		        Capsule::table($this->settings_table_name)
		            ->where('setting',$setting)
		            ->update(['value' => $value]);
		    }
	   }

		function settings_load(){
			if (Capsule::schema()->hasTable($this->settings_table_name)) {
			    $this->settings = $this->settings_default_value;

			    $result = Capsule::table($this->settings_table_name)
			    		->select('setting', 'value')
			            ->get();

			    for ($i=0; $i < count($result) ; $i++) {
			        $this->settings[$result[$i]->setting] = $result[$i]->value;
			    }
			}
		}


	   public function update($item){
		    Capsule::table($this->table_name)
		        ->where('id',$item->id)
		        ->update([
				    'icon' => $item->icon,
				    'name' => $item->name,
				    'url' => $item->url,
				    'soft_order' => $item->soft_order,
				    'status' => $item->status,
				    'parent_id' => $item->parent_id,
					'only_for_guest' => $item->only_for_guest,
					'only_for_user' => $item->only_for_user,				    

					'url_type' => $item->url_type,
					'new_window' => $item->new_window,

					'show_type' => $item->show_type,
					'show_for_id' => $item->show_for_id,

					'preinstalled' => $item->preinstalled,

					'class' => $item->class,

				    'updated_at' => date("Y-m-d H:i:s")
		         ]
		    );
	   }

	   public function get($id){
		    $r = Capsule::table($this->table_name)
		    		->where('id', $id)
		            ->get();

		    if (isset($r[0])){

		    	$ch = Capsule::table($this->table_name)
		    		->where('parent_id', $r[0]->id)
		            ->get();

		        if (isset($ch[0])){
		        	$r[0]->childs = $ch;
		        }


		        if ($r[0]->show_type==0){
    					if ($r[0]->only_for_guest==1 && $r[0]->only_for_user==0){
    						$r[0]->show_type = 1;
    					}else{
    						if ($r[0]->only_for_guest==0 && $r[0]->only_for_user==1){
    							$r[0]->show_type = 2;
    						}
    					}
		        }



				if (strpos($r[0]->icon,'icon ')!==false ){
					$r[0]->icon_collection = 0;
					$r[0]->icon = str_replace("icon ", "", $r[0]->icon);
				}	
				if (strpos($r[0]->icon,'fas ')!==false ){
					$r[0]->icon_collection = 1;
					$r[0]->icon = str_replace("fas ", "", $r[0]->icon);
				}
				if (strpos($r[0]->icon,'far ')!==false ){
					$r[0]->icon_collection = 2;
					$r[0]->icon = str_replace("far ", "", $r[0]->icon);
				}
				if (strpos($r[0]->icon,'fab ')!==false ){
					$r[0]->icon_collection = 3;
					$r[0]->icon = str_replace("fab ", "", $r[0]->icon);
				}
				if (strpos($r[0]->icon,'fal ')!==false ){
					$r[0]->icon_collection = 4;
					$r[0]->icon = str_replace("fal ", "", $r[0]->icon);
				}														
				if ($r[0]->icon == '' ){
					$r[0]->icon_collection = -1;
				}



		

		    	return $r[0];
		    }else{
		    	return null;
		    }
	   }

	   public function getall(){
		    $r = Capsule::table($this->table_name)
		            ->get();

			return $r;
	   }

	   public function list_front(){
		    $r = Capsule::table($this->table_name)
		    		->where('status', 2)
		            ->get();
		    $n = [];

		    $r = $this->sort_items_front($r);

		    foreach ($r as $k => $v) {
		    	$this->MenuIconHolderTag($v);
		    	if (isset($v->child)){
		    		foreach ($v->child as $kk => $vv) {
		    			$this->MenuIconHolderTag($vv);
		    			$v->child[$kk] = (array)$vv;
		    		}
		    	}		    	
		    	$n[] = (array)$v;

		    }

			return $n;
	   }

	   public function MenuIconHolderTag(&$item){
	   		if ($item->icon != ''){

				if (strpos($item->icon,'icon ')!==false ){
					$item->icon_collection = 0;
					$item->icon_holder_tag = 'span';
				}if (strpos($item->icon,'fas ')!==false || strpos($item->icon,'far ')!==false  || strpos($item->icon,'fab ')!==false || strpos($item->icon,'fal ')!==false){
					$item->icon_collection = 1;
					$item->icon_holder_tag = 'i';
				}

	   		}
	   }

	   public function parents($id){
		    $r = Capsule::table($this->table_name)
		    		->where('parent_id',0)
		    		->where('id', '<>', $is)
		            ->get();

		    $p = [0=>'(none)'];

		    foreach ($r as $key => $value) {
		    	$p[$value->id] = $value->name;
		    }


			return $p;
	   }

	   public function enable($id){
		    Capsule::table($this->table_name)
		        ->where('ID',$id)
		        ->update([
				    'status' => 2,
				    'updated_at' => date("Y-m-d H:i:s")
		         ]
		    );
	   }

	   public function disable($id){
		    Capsule::table($this->table_name)
		        ->where('ID',$id)
		        ->update([
				    'status' => 9,
				    'updated_at' => date("Y-m-d H:i:s")
		         ]
		    );
	   }


	   public function delete($id){
		    Capsule::table($this->table_name)
		        ->where('ID',$id)
		        ->where('preinstalled', '<>', 1)
		    ->delete();
	   }

	   public function sort_items($a){
	   		$p = [];
	   		$c = [];

	   		foreach ($a as $key => $value) {
	   			if ($value->parent_id == 0){
	   				$p[] = $value;
	   			}else{
	   				$c[$value->parent_id][] = $value;
	   			}
	   		}

	   		$new = [];
			usort($p, function($a, $b) { 
			    $rdiff = $a->soft_order - $b->soft_order;
			    return $rdiff; 
			});

			foreach ($p as $key => $value) {
				$new[] = $value;
				if(isset($c[$value->id])){
					usort($c[$value->id], function($a, $b) { 
					    $rdiff = $a->soft_order - $b->soft_order;
					    return $rdiff; 
					});
					foreach ($c[$value->id] as $k => $v) {
						$new[] = $v;
					}
				}
			}

			return $new;

	   }

	   public function sort_items_front($a){
	   		$p = [];
	   		$c = [];

	   		foreach ($a as $key => $value) {
	   			if ($value->parent_id == 0){
	   				$p[] = $value;
	   			}else{
	   				$c[$value->parent_id][] = $value;
	   			}
	   		}

	   		$new = [];
			usort($p, function($a, $b) { 
			    $rdiff = $a->soft_order - $b->soft_order;
			    return $rdiff; 
			});

			foreach ($p as $key => $value) {
				if(isset($c[$value->id])){
					usort($c[$value->id], function($a, $b) { 
					    $rdiff = $a->soft_order - $b->soft_order;
					    return $rdiff; 
					});
					$value->child = $c[$value->id];
				}
				$new[] = $value;

			}

			return $new;

	   }

	   public function init_menu_from_array($menu,$preinstalled=1){

	   		$soft_order = 10;
	   		foreach ($menu as $key => $menu_item) {
	   			$parent_soft_order = 10;
	   			$parent_id = 0;

				$item = new stdClass();
					foreach ($this->field_list as $value){
						if (isset($menu_item[$value])){
							$item->$value = $menu_item[$value];	
						}else{
							if(isset($this->default[$value])){
								$item->$value = $this->default[$value];
							}
						}
					}

				if (!isset($item->new_window)){
					$item->new_window = 0;
				}
				$item->preinstalled	= $preinstalled;
				$item->soft_order = $soft_order;

				$parent_id = $this->create($item);

				if (isset($menu_item['child'])){
					foreach ($menu_item['child'] as $key => $sub_menu_item) {
						$item = new stdClass();
						foreach ($this->field_list as $value){
							if (isset($sub_menu_item[$value])){
								$item->$value = $sub_menu_item[$value];	
							}else{
								if(isset($this->default[$value])){
									$item->$value = $this->default[$value];
								}
							}
						}
						$item->soft_order = $parent_soft_order;
						$item->parent_id = $parent_id;
						$item->preinstalled	= $preinstalled;

						if (!isset($item->new_window)){
							$item->new_window = 0;
						}	

						$this->create($item);
						$parent_soft_order += 10;
					}
				}

	   			$soft_order += 10;
	   		}


	   }

	   public function init_menu_from_array_fix_migration2($menu){

	   		$soft_order = 10;
	   		foreach ($menu as $key => $menu_item) {

		    Capsule::table($this->table_name)
		        ->where('name',$menu_item['name'])
		        ->where('url',$menu_item['url'])
		        ->update([
					'preinstalled' => 1,
				    'updated_at' => date("Y-m-d H:i:s")
		         ]
		    );

				if (isset($menu_item['child'])){
					foreach ($menu_item['child'] as $key => $sub_menu_item) {

					    Capsule::table($this->table_name)
					        ->where('name',$sub_menu_item['name'])
					        ->where('url',$sub_menu_item['url'])
					        ->update([
								'preinstalled' => 1,
							    'updated_at' => date("Y-m-d H:i:s")
					         ]
					    );

					}
				}

	   		}


	   }

	}
}