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

        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();
		$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('content', $data)){
				return 1; 
			 }else{
				return 0;
		}
	} */
	public function addDataProcess($data,$files,$page) {
		$builder = $this->db->table('content');
		if($builder->insert($data)){
		$content_id=$this->db->insertID();
		$images = '';
		$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."/images/" . $uniqueName;
						if (move_uploaded_file($tmp_name, $filePath)) {
							$images = $filePath;
							//array_push($datafile['csss'],$filePath);
						} else {
							echo "Failed to move file: " . $files['name'][$i] . "<br>";
						}
					} else {
						echo "Error uploading Image file: " . $files['error'][$i] . "<br>";
					}
					//$csss = $csss, ',');
					$data1=array("content_id"=>$content_id,"image"=>$images);
					$builder1 = $this->db->table('content_details');
					$builder1->insert($data1);
					} 
				} 
				
			return 1; 
			/*} else{
				$csss="";
			} */
			}else{
				return 0;
		}
	}
	public function updateDataProcessImage($data,$id,$files,$page) {
		$builder = $this->db->table('content');
		$builder->where('id', $id);
		if($builder->update($data)){
		/* if(!empty($oldImage)){
			unlink($oldImage);
		} */
		$content_id=$id;
		$images = '';
		$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."/images/" . $uniqueName;
						if (move_uploaded_file($tmp_name, $filePath)) {
							$images = $filePath;
							//array_push($datafile['csss'],$filePath);
						} else {
							echo "Failed to move file: " . $files['name'][$i] . "<br>";
						}
					} else {
						echo "Error uploading Image file: " . $files['error'][$i] . "<br>";
					}
					//$csss = $csss, ',');
					$data1=array("content_id"=>$content_id,"image"=>$images);
					$builder1 = $this->db->table('content_details');
					$builder1->insert($data1);
				} 
				
			
			}/* else{
				$csss="";
			} */
			return 1; 
			}else{
				return 0;
		}
	}
	public function updateDataProcess($data,$id)
	{
		if($this->db->update('content', $data, array('id' => $id))){
				return 1; 
			 }else{
				return 0;
		}
	}
	public function editData($id) {
		$builder = $this->db->table('content'); // 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 getContentDetails($id) {
		$builder = $this->db->table('content_details'); // Get builder for a specific table
        $builder->select('*');
		$builder->where('content_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('content', $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('content');
		$builder->where('id', $id);
		if($builder->delete()){
				return 1; 
			 }else{
				return 0;
			}	 
	}
	/* DELETE WITH IMAGE */
	 
	public function deleteDataProcessImage($id) {
			 $builder = $this->db->table('content');
			 $builder->where('id', $id);
			 if($builder->delete()){
				$builder1 = $this->db->table('content_details'); // Get builder for a specific table
				$builder1->select('image');
				$builder1->where('content_id', $id);
				$query = $builder1->get(); // Runs the query
				$imagess = $query->getResult(); // Get results as an array of arrays

				foreach($imagess as $images){
				$image=$images->image;	
				if($image != ""){
				unlink($image);
				}
				}
				$builder1->where('content_id', $id);
				$builder1->delete();
				return 1; 
			 }else{
				return 0;
			}
	} 
	
	public function deleteImage($id) {
			 $builder = $this->db->table('content_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;
			}
	} 
	
	/* 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('content')){
			 }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('content');
			 $this->db->where('id', $ids[$i]);
			 $image=$this->db->get()->row('image');
			 //DATA UPDATE ONLY-- NOT DELETE
			 //$data['isDelete'] = 1;
			 //if($this->db->update('content', $data, array('id' => $ids[$i]))){
			 //DATA UPDATE ONLY-- NOT DELETE  END
			  if($this->db->delete('content',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('content');
		$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('content');
		$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('content');
		$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('content');
		$this->db->where('page_name', $name);
		//$this->db->where('isDelete', 0);
		$this->db->where('id !=', $id);
		return $this->db->get()->num_rows();
	}

}