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

        if (isset($_GET['sort']))
            if ($_GET['sort'] == 'page') {
                $sort = "page";
            } 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', $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', $multipleWhere);
			$search_res->groupEnd();
		}
        if (isset($where) && !empty($where)) {
            $search_res->where($where);
        }

        $brand_search_res = $search_res->orderBy("page", "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) {
               $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['id'] = $row['id'];
           // $tempRow['image'] = "<p><a href='".base_url().'/uploads/'.$row['image']. "' class='glightbox'> <img class='rounded' src='".base_url().'/uploads/'. $row['image']. "' width='200' height='auto'></a><script>var lightbox=GLightbox({selector:'.glightbox',title:false,});</script></p>";
            $tempRow['page'] = $row['page'];
            /* $tempRow['lastname'] = $row['lastname'];
            $tempRow['email'] = $row['email'];
            $tempRow['phone'] = $row['phone']; */
           	$tempRow['operate'] = $operate;
			$rows[] = $tempRow;
        }
        $bulkData['rows'] = $rows;
        print_r(json_encode($bulkData));
		
	}
	/* public function addDataProcess($data) {
		if($this->db->insert('header', $data)){
				return 1; 
			 }else{
				return 0;
		}
	} */
	public function addDataProcess($data,$files,$files1,$page) {
		$builder = $this->db->table('header');
		if($builder->insert($data)){
			$header_id=$this->db->insertID();
		}
		$csss = '';
		$tmp_name=array();
		//echo "<pre>";print_r($files);	exit;
			if (!empty($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."/css/" . $uniqueName;
						if (move_uploaded_file($tmp_name, $filePath)) {
							$csss = $filePath;
							//array_push($datafile['csss'],$filePath);
						} else {
							echo "Failed to move file55: " . $files['name'][$i] . "<br>";
						}
					} else {
						echo "Error uploading CSS file: " . $files['error'][$i] . "<br>";
					}
					//$csss = $csss, ',');
					$data1=array("header_id"=>$header_id,"css"=>$csss);
					$builder1 = $this->db->table('header_details');
					$builder1->insert($data1);				} 
			}/* else{
				return 0;
			} */	
			$images = '';
			$tmp_name1=array();
			//echo "<pre>";print_r($files);	exit;
				if (!empty($files1)) {
					//echo $tmp_name=$files['css']['tmp_name'][0];exit;
					foreach ($files1['tmp_name'] as $i => $tmp_name1) {
						if ($files1['error'][$i] == UPLOAD_ERR_OK) {
							// Generate a unique file name
							$uniqueName1 = basename($files1['name'][$i]);
							
							$filePath1 = "pages/".$page."/images/" . $uniqueName1;
							if (move_uploaded_file($tmp_name1, $filePath1)) {
								$images = $filePath1;
								//array_push($datafile['csss'],$filePath);
							} else {
								echo "Failed to move file: " . $files1['name'][$i] . "<br>";
							}
						} else {
							echo "Error uploading Image file: " . $files1['error'][$i] . "<br>";
						}
						//$csss = $csss, ',');
						$data2=array("header_id"=>$header_id,"image"=>$images);
						$builder2 = $this->db->table('header_image_details');
						$builder2->insert($data2);
					} 
					
				//return 1; 
			}/* else{
				return 0;
			} */
	return 1; 		
	}
	public function updateDataProcessImage($data,$id,$oldImage,$files,$files1,$page) {
		
		$builder = $this->db->table('header');
		$builder->where('id', $id);
		if($builder->update($data)){
		if(!empty($oldImage)){
			unlink($oldImage);
		}
		$header_id=$id;
		$csss = '';
		$tmp_name=array();
		//echo "<pre>";print_r($files);	exit;
			if (!empty($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."/css/" . $uniqueName;
						if (move_uploaded_file($tmp_name, $filePath)) {
							$csss = $filePath;
							//array_push($datafile['csss'],$filePath);
						} else {
							echo "Failed to move file: " . $files['name'][$i] . "<br>";
						}
					} else {
						echo "Error uploading CSS file: " . $files['error'][$i] . "<br>";
					}
					//$csss = $csss, ',');
					$data1=array("header_id"=>$header_id,"css"=>$csss);
					$builder1 = $this->db->table('header_details');
					$builder1->insert($data1);
				} 	
				
			
			}/* else{
				$csss="";
			} */
			$images = '';
			$tmp_name1=array();
			//echo "<pre>";print_r($files);	exit;
				if (!empty($files1)) {
					//echo $tmp_name=$files['css']['tmp_name'][0];exit;
					foreach ($files1['tmp_name'] as $i => $tmp_name1) {
						if ($files1['error'][$i] == UPLOAD_ERR_OK) {
							// Generate a unique file name
							$uniqueName1 = basename($files1['name'][$i]);
							
							$filePath1 = "pages/".$page."/images/" . $uniqueName1;
							if (move_uploaded_file($tmp_name1, $filePath1)) {
								$images = $filePath1;
								//array_push($datafile['csss'],$filePath);
							} else {
								echo "Failed to move file: " . $files1['name'][$i] . "<br>";
							}
						} else {
							echo "Error uploading Image file: " . $files1['error'][$i] . "<br>";
						}
						//$csss = $csss, ',');
						$data2=array("header_id"=>$header_id,"image"=>$images);
						$builder2 = $this->db->table('header_image_details');
						$builder2->insert($data2);
					} 
					
				//return 1; 
			}
			
			}else{
				return 0;
		}
		return 1; 
	}
	public function updateDataProcess($data,$id)
	{
		if($this->db->update('header', $data, array('id' => $id))){
				return 1; 
			 }else{
				return 0;
		}
	}
	public function editData($id) {
		$builder = $this->db->table('header'); // 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 getHeaderDetails($id) {
		$builder = $this->db->table('header_details'); // Get builder for a specific table
        $builder->select('*');
		$builder->where('header_id', $id);
        $query = $builder->get(); // Runs the query

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

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

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

	}
	
	public function deleteImage($id) {
			 $builder = $this->db->table('header_image_details');
			 $row = $builder->select('image')->where('id', $id)->get()->getRow();
			 $image = $row->image;
			 
			 /* DATA UPDATE ONLY --NOT DELETE END */
			 $builder->where('id', $id);
			 if($builder->delete()){
				unlink($image);
				return 1; 
			 }else{
				return 0;
			}
	} 
	
	
	/* UPDATE WITH IMAGE */
	public function updateDataProcessImage1($data,$id,$oldImage)
	{   
		if($this->db->update('header', $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('header');
		$builder->where('id', $id);
		if($builder->delete()){
				return 1; 
			 }else{
				return 0;
			}	 
	}
	
	/* DELETE WITH IMAGE */
	 public function deleteDataProcessImage($id) {
			 
			 $builder = $this->db->table('header');
			 $row = $builder->select('favicon')->where('id', $id)->get()->getRow();
			 $favicon = $row->favicon;
			 
			 $builder->where('id', $id);
			 if($builder->delete()){
				if($favicon != ""){
				unlink($favicon);
				}
				
				$builder1 = $this->db->table('header_details'); // Get builder for a specific table
				$builder1->select('css');
				$builder1->where('header_id', $id);
				$query = $builder1->get(); // Runs the query
				$csss = $query->getResult(); // Get results as an array of arrays

				foreach($csss as $cs){
				$css=$cs->css;	
				if($css != ""){
				unlink($css);
				}
				}
				$builder1->where('header_id', $id);
				$builder1->delete();
	
				$builder2 = $this->db->table('header_image_details'); // Get builder for a specific table
				$builder2->select('image');
				$builder2->where('header_id', $id);
				$query = $builder2->get(); // Runs the query
				$images = $query->getResult(); // Get results as an array of arrays

				foreach($images as $img){
				$image=$img->image;	
				if($image != ""){
				unlink($image);
				}
				}
				$builder2->where('header_id', $id);
				$builder2->delete();
				
				return 1; 
			 }else{
				return 0;
			}
	} 
	
	public function deleteCSS($id) {
			 $builder = $this->db->table('header_details');
			 $row = $builder->select('css')->where('id', $id)->get()->getRow();
			 $css = $row->css;
			 
			 /* DATA UPDATE ONLY --NOT DELETE END */
			 $builder->where('id', $id);
			 if($builder->delete()){
				//if($image != "no-user-image.jpg"){
				unlink($css);
				//}
				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('header')){
			 }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('header');
			 $this->db->where('id', $ids[$i]);
			 $image=$this->db->get()->row('image');
			 //DATA UPDATE ONLY-- NOT DELETE
			 //$data['isDelete'] = 1;
			 //if($this->db->update('header', $data, array('id' => $ids[$i]))){
			 //DATA UPDATE ONLY-- NOT DELETE  END
			  if($this->db->delete('header',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('header');
		$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('header');
		$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('header');
		$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('header');
		$this->db->where('page_name', $name);
		//$this->db->where('isDelete', 0);
		$this->db->where('id !=', $id);
		return $this->db->get()->num_rows();
	}

}