<?php
namespace App\Models;
use CodeIgniter\Model;
/**
 * SubmenuModel class.
 * 
 * @extends Model
 */
class SubmenuModel extends Model {
	
	public function getData()
    {
        $offset = 0;
        $limit = 1;
        $sort = 'menu_order';
        $order = 'ASC';
        $multipleWhere = '';
        $where = "";
		$builder = $this->db->table('submenu');
		
        if (isset($_GET['offset']))
            $offset = $_GET['offset'];
        if (isset($_GET['limit']))
            $limit = $_GET['limit'];

        if (isset($_GET['sort']))
            if ($_GET['sort'] == 'page_name') {
                $sort = "page_name";
            } else {
                $sort = $_GET['sort'];
            }
        if (isset($_GET['order']))
            $order = $_GET['order'];

        if (isset($_GET['search']) and $_GET['search'] != '') {
            $multipleWhere = $_GET['search'];
        }
        $count_res = $builder->select(' COUNT(id) as `total` ');

        if(!empty($multipleWhere)){
			$count_res->groupStart();
			$count_res->orLike('page_name', $multipleWhere);
			$count_res->orLike('parent_menu', $multipleWhere);
			$count_res->groupEnd();
		}
        $brand_count = $count_res->get()->getResultArray();
        foreach ($brand_count as $row) {
            $total = $row['total'];
        }

        $search_res = $builder->select(' * ');
        if(!empty($multipleWhere)){
			$search_res->groupStart();
			$search_res->orLike('page_name', $multipleWhere);
			$search_res->orLike('parent_menu', $multipleWhere);
			$search_res->groupEnd();
		}
        if (isset($where) && !empty($where)) {
            $search_res->where($where);
        }

        $brand_search_res = $search_res->orderBy("menu_order", "ASC")->limit($limit, $offset)->get()->getResultArray();
        $bulkData = array();
        $bulkData['total'] = $total;
        $rows = array();
        $tempRow = array();
		helper('url');
		// Get the URI object
		$uri = current_url(true);
        foreach ($brand_search_res as $row) {
               $original_url = base_url().$row['page_slug'];
			   $operate = '<a href="#" onclick=\'copyLink("'.$original_url.'")\' title="Copy Link"><button class="dropdown-item"><i class="ri-link align-bottom me-2 text-muted" aria-hidden="true"></i> </button></a>';
               $operate .= '<a href="#" data-bs-toggle="modal" data-bs-target="#modalAdd" onclick=\'addForm('.$row['id'].',"Edit '.ucfirst($uri->getSegment(2)).'","modal-lg","addForm")\' title="Edit"><button class="dropdown-item"><i class="ri-pencil-fill align-bottom me-2 text-muted"></i> </button></a>';
               //$operate ='<a href="'.base_url($this->uri->segment(1)."/".$this->uri->segment(2)."/addFormPage/".$row['id']).'" title="Edit"><button class="dropdown-item"><i class="ri-pencil-fill align-bottom me-2 text-muted"></i> </button></a>';
               //$operate .= '<a href="#" data-bs-toggle="modal" data-bs-target="#modalView" onclick=\'viewForm('.$row['id'].',"modal-lg")\' title="View"><button class="dropdown-item"><i class="ri-eye-fill align-bottom me-2 text-muted"></i> </button></a>';
               $operate .= '<a href="#" data-bs-toggle="modal" data-bs-target="#modalDelete" onclick=\'deleteForm('.$row['id'].')\' title="Delete"><button class="dropdown-item"><i class="ri-delete-bin-fill align-bottom me-2 text-muted"></i> </button></a>';
            
            $tempRow['page_name'] = $row['page_name'];
			$tempRow['parent_menu'] = $row['parent_menu'];
            $tempRow['page_slug'] = base_url().$row['page_slug'];
			$tempRow['menu_order'] = $row['menu_order'];
           	$tempRow['operate'] = $operate;
			$rows[] = $tempRow;
        }
        $bulkData['rows'] = $rows;
        print_r(json_encode($bulkData));
		
	}
	/* public function addDataProcess($data) {
		if($this->db->insert('submenu', $data)){
				return 1; 
			 }else{
				return 0;
		}
	} */
	public function addDataProcess($data) {
		$builder = $this->db->table('submenu');
		if($builder->insert($data)){
			return 1; 
			}else{
				return 0;
		}
	}
	public function updateDataProcessImage($data,$id,$files,$page) {
		if($this->db->update('submenu', $data, array('id' => $id))){
		/* if(!empty($oldImage)){
			unlink($oldImage);
		} */
		$footer_id=$id;
		$jss = '';
		$tmp_name=array();
		//echo "<pre>";print_r($files);	exit;
			if (isset($files)) {
				//echo $tmp_name=$files['css']['tmp_name'][0];exit;
				foreach ($files['tmp_name'] as $i => $tmp_name) {
					if ($files['error'][$i] == UPLOAD_ERR_OK) {
						// Generate a unique file name
						$uniqueName = basename($files['name'][$i]);
						
						$filePath = "pages/".$page."/js/" . $uniqueName;
						if (move_uploaded_file($tmp_name, $filePath)) {
							$jss = $filePath;
							//array_push($datafile['csss'],$filePath);
						} else {
							echo "Failed to move file: " . $files['name'][$i] . "<br>";
						}
					} else {
						echo "Error uploading JS file: " . $files['error'][$i] . "<br>";
					}
					//$csss = $csss, ',');
					$data1=array("footer_id"=>$footer_id,"js"=>$jss);
					$this->db->insert('footer_details', $data1);
				} 
				
			return 1; 
			}/* else{
				$csss="";
			} */
			}else{
				return 0;
		}
	}
	public function updateDataProcess($data,$id)
	{
		$builder = $this->db->table('submenu');
		$builder->where('id', $id);
		if($builder->update($data)){ return 1;}
		else{return 0;}
	}
	public function editData($id) {
		$builder = $this->db->table('submenu'); // Get builder for a specific table
        $builder->select('*');
		$builder->where('id', $id);
        $query = $builder->get(); // Runs the query

        return $query->getResult(); // Get results as an array of arrays

	}
	public function getPages() {
		$builder = $this->db->table('pages'); // Get builder for a specific table
        $builder->select('*');
		//$builder->where('id', $id);
        $query = $builder->get(); // Runs the query

        return $query->getResult(); // Get results as an array of arrays

	}
	public function getMenus() {
		$builder = $this->db->table('menu'); // Get builder for a specific table
        $builder->select('*');
		//$builder->where('id', $id);
        $query = $builder->get(); // Runs the query
        return $query->getResult(); // Get results as an array of arrays
	}
	
	/* UPDATE WITH IMAGE */
	public function updateDataProcessImage1($data,$id,$oldImage)
	{   
		if($this->db->update('submenu', $data, array('id' => $id))){
				if(!empty($oldImage)){
				unlink('uploads/'.$oldImage);
				}
				return 1; 
			 }else{
				return 0;
		}
	}
	/* UPDATE WITH IMAGE END */
	
	public function deleteDataProcess($id) {
		$builder = $this->db->table('submenu');
		$builder->where('id', $id);
		if($builder->delete()){
				return 1; 
			 }else{
				return 0;
			}	
	}
	
	/* DELETE WITH IMAGE */
	 public function deleteDataProcessImage($id) {
			 /* $this->db->select('favicon');
			 $this->db->from('submenu');
			 $this->db->where('id', $id);
			 $favicon=$this->db->get()->row('favicon'); */
			 if($this->db->delete('submenu',array('id' => $id))){
				/* if($favicon != ""){
				unlink($favicon);
				} */
				$this->db->select('js');
				$this->db->from('footer_details');
				$this->db->where('footer_id', $id);
			    $jss=$this->db->get()->result();
				foreach($jss as $js){
				$js=$js->js;	
				if($js != ""){
				unlink($js);
				}
				}
				$this->db->delete('footer_details',array('footer_id' => $id));
				
				return 1; 
			 }else{
				return 0;
			}
	} 
	public function deleteJS($id) {
			 $this->db->select('js');
			 $this->db->from('footer_details');
			 $this->db->where('id', $id);
			 $js=$this->db->get()->row('js');
			 /* DATA UPDATE ONLY-- NOT DELETE */
			 //$data['isDelete'] = 1;
			 //if($this->db->update('submenu', $data, array('id' => $id))){
			 
			 /* DATA UPDATE ONLY --NOT DELETE END */
			 if($this->db->delete('footer_details',array('id' => $id))){
				//if($image != "no-user-image.jpg"){
				unlink($js);
				//}
				return 1; 
			 }else{
				return 0;
			}
	} 
	/* DELETE WITH IMAGE END */
	
	/* public function deleteAll($id) {
		 $id = trim($id);
		 $ids=explode(",",$id);
		 $size=sizeof($ids);
		 for($i=0;$i<$size;$i++){
			 $this->db->where('id', $ids[$i]);
			 if($this->db->delete('submenu')){
			 }else{
				return 0;
			}
		}
		return 1; 
	} */
	
/* DELETE ALL WITH IMAGE */
	public function deleteAll($id) {
		 $id = trim($id);
		 $ids=explode(",",$id);
		 $size=sizeof($ids);
		 for($i=0;$i<$size;$i++){
			 $this->db->select('image');
			 $this->db->from('submenu');
			 $this->db->where('id', $ids[$i]);
			 $image=$this->db->get()->row('image');
			 //DATA UPDATE ONLY-- NOT DELETE
			 //$data['isDelete'] = 1;
			 //if($this->db->update('submenu', $data, array('id' => $ids[$i]))){
			 //DATA UPDATE ONLY-- NOT DELETE  END
			  if($this->db->delete('submenu',array('id' => $ids[$i]))){
				//if($image != "no-user-image.jpg"){
				unlink('profileimage/'.$image);
				//}
			 }else{
				return 0;
			}
		}
		return 1; 
	} 
	/* DELETE ALL WITH IMAGE END */
	public function checkDuplicateEmail($name) {
		$this->db->select('*');
		$this->db->from('submenu');
		$this->db->where('email', $name);
		//$this->db->where('isDelete', 0);
		return $this->db->get()->num_rows();
	}
	public function checkDuplicateEmailEdit($id,$name) {
		$this->db->select('*');
		$this->db->from('submenu');
		$this->db->where('email', $name);
		//$this->db->where('isDelete', 0);
		$this->db->where('id !=', $id);
		return $this->db->get()->num_rows();
	}
	public function checkDuplicatePagename($name) {
		$this->db->select('*');
		$this->db->from('submenu');
		$this->db->where('page_name', $name);
		//$this->db->where('isDelete', 0);
		return $this->db->get()->num_rows();
	}
	public function checkDuplicatePagenameEdit($id,$name) {
		$this->db->select('*');
		$this->db->from('submenu');
		$this->db->where('page_name', $name);
		//$this->db->where('isDelete', 0);
		$this->db->where('id !=', $id);
		return $this->db->get()->num_rows();
	}

}