<?php
namespace App\Models;
use CodeIgniter\Model;
/**
 * PagesModel class.
 * 
 * @extends Model
 */
class PagesModel extends Model {

	public function getData()
    {
		$offset = 0;
        $limit = 1;
        $sort = 'page_name';
        $order = 'DESC';
        $multipleWhere = '';
        $where = "";
		$builder = $this->db->table('pages');

        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->groupEnd();
		}
        $brand_count = $count_res->get()->getResultArray();
        //echo "<pre>";print_r($brand_count);exit();
		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->groupEnd();
		}
        if (isset($where) && !empty($where)) {
            $search_res->where($where);
        }

       // $brand_search_res = $search_res->orderBy("page_name", "ASC")->limit($limit, $offset)->get('pages')->result_array();
        $brand_search_res = $search_res->orderBy("page_name", "ASC")->limit($limit, $offset)->get()->getResultArray();
        $bulkData = array();
        $bulkData['total'] = $total;
        $rows = array();
        $tempRow = array();

        foreach ($brand_search_res as $row) {
               //$operate = '<a href="#" data-bs-toggle="modal" data-bs-target="#modalAdd" onclick=\'addForm('.$row['id'].',"Edit '.ucfirst($this->uri->segment(2)).'","modal-md","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_name'] = $row['page_name'];
            /* $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) {
		$builder = $this->db->table('pages');
		if($builder->insert($data)){
				return 1; 
			 }else{
				return 0;
		}
	}
	public function updateDataProcess($data,$id)
	{
		$builder = $this->db->table('pages');
		$builder->where('id', $id);
		if($builder->update($data)){ return 1;}
		else{return 0;}
	}
	public function editData($id) {
		$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

	}
	
	
	
	/* UPDATE WITH IMAGE */
	public function updateDataProcessImage($data,$id,$oldImage)
	{   
		$builder = $this->db->table('pages');
		$builder->where('id', $id);
		if($builder->update($data)){
				if(!empty($oldImage)){
				unlink('uploads/'.$oldImage);
				}
				return 1; 
			 }else{
				return 0;
		}
	}
	/* UPDATE WITH IMAGE END */
	
	public function deleteDataProcess($id) {
	
	$builder = $this->db->table('pages');
    $row = $builder->select('page_name')->where('id', $id)->get()->getRow();
    $page_name = $row->page_name;

			$page_slug=strtolower(str_replace(" ","",$page_name));
			$builder->where('id', $id);
			if($builder->delete()){
				if($page_slug != ""){
				$this->deleteDirectory("pages/".$page_slug);
				}
				return 1; 
			 }else{
				return 0;
			}
	}
	public function deleteDirectory($dirPath) {
	   if (is_dir($dirPath)) {
		  $files = scandir($dirPath);
		  foreach ($files as $file) {
			 if ($file !== '.' && $file !== '..') {
				$filePath = $dirPath . '/' . $file;
				if (is_dir($filePath)) {
				   $this->deleteDirectory($filePath);
				} else {
				   unlink($filePath);
				}
			 }
		  }
		  rmdir($dirPath);
	   }
	}
	
	/* DELETE WITH IMAGE */
	 public function deleteDataProcessImage($id) {
			 $this->db->select('image');
			 $this->db->from('pages');
			 $this->db->where('id', $id);
			 $image=$this->db->get()->row('image');
			 /* DATA UPDATE ONLY-- NOT DELETE */
			 //$data['isDelete'] = 1;
			 //if($this->db->update('pages', $data, array('id' => $id))){
			 
			 /* DATA UPDATE ONLY --NOT DELETE END */
			 if($this->db->delete('pages',array('id' => $id))){
				//if($image != "no-user-image.jpg"){
				unlink('uploads/'.$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('pages')){
			 }else{
				return 0;
			}
		}
		return 1; 
	}

	
	public function checkDuplicatePagename($name) {
		$builder = $this->db->table('pages'); // Get builder for a specific table
        $builder->select('*');
		$builder->where('page_name', $name);
        $query = $builder->get(); // Run the query to fetch results
    
		return $query->getNumRows(); // Get the number of rows from the result object
	}
	public function checkDuplicatePagenameEdit($id,$name) {
		$builder = $this->db->table('pages'); // Get builder for a specific table
        $builder->select('*');
		$builder->where('page_name', $name);
		$builder->where('id !=', $id);
        $query = $builder->get(); // Run the query to fetch results
    
		return $query->getNumRows(); // Get the number of rows from the result object
	}
	

}