<?php

class pageModel extends baseModel {
    function get($args) {
        if (isset($args['id'])) {    
            $this->db->where('id=?', $args['id']);
        }
        
        if (isset($args['slug'])) {
            $this->db->where('slug=?', $args['slug']);
        }           
                
        return $this->db->select_one('pages');
    }
    
    function getList($cond = []) {
        $this->db->order_by('name ASC');
        
        if (isset($cond['search'])) {
            $this->db->where("(
                name like '%{$cond['search']}%' 
                OR content like '%{$cond['search']}%'
                OR meta_description like '%{$cond['search']}%'
                OR meta_keywords like '%{$cond['search']}%')");
        }
        
        if  (isset($cond['user_id'])) {
            $this->db->where('user_id=?', $cond['user_id']);
            $this->db->order_by('date_created DESC');
            $this->db->limit(10);
        }

        $pages = $this->db->select('pages');
        foreach ($pages as $index => $page) {
            $page['author'] = $this->db->where('id=?', $page['user_id'])->select_one('users');
            $pages[$index] = $page;
        }
        return $pages;
    }
    
    private function upsertPrepareData($data) {
        $columns = ['name', 'content', 'sidebar_content', 'meta_keywords', 'meta_description', 'widgets', 'recent_posts_filter_type', 'recent_posts_filter_id', 'image', 'hide_title', 'styleone', 'styletwo', 'slug','subtitle'];
        
        if ($data['recent_posts_filter_type'] == 'user') {
            $data['recent_posts_filter_id'] = $data['user_filter'];
        }
        
        if ($data['recent_posts_filter_type'] == 'category') {
            $data['recent_posts_filter_id'] = $data['category_filter'];
        }
                
        if (!$data['show_sidebar']) {
            $data['sidebar_content'] = '';
        }
        
        foreach ($data as $index => $column) {
            if (!in_array($index, $columns)) {
                unset($data[$index]);
            }
        }
        
        $data['widgets'] = (!empty($data['widgets']) && is_array($data['widgets']))? json_encode($data['widgets']) : false;
        
        return $data;
    }

    function update($id, $data) {
        
        $data = $this->upsertPrepareData($data);
                
        $data['date_edited'] = date("Y-m-d H:i:s");
        $data['hide_title'] = !empty($data['hide_title']) ? 1 : 0;
        $data['styleone'] = !empty($data['styleone']) ? 1 : 0;
        $data['styletwo'] = !empty($data['styletwo']) ? 1 : 0;       
        
        $this->db->where('id=?', $id)->update('pages', $data);
        
        // UPLOAD AN IMAGE IF THERE IS ONE ATTACHED         
        if (isset($_FILES['image']) && !$_FILES['image']['error']) {
            $file = $_FILES['image'];
            
            $this->db->where('id=?', $id);  
            $cur_image = $this->db->select_one("pages", ['image']);         
                
                if(!empty($cur_image['image']) && isset($_FILES['image']) && !$_FILES['image']['error']) {
                    @unlink($cur_image['image']);               
                    
                    $file = $_FILES['image'];
                    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
                    if ($ext == 'jpg' || $ext == 'png' || $ext = 'jpeg' || $ext = 'gif' ) {
                        $imgname = basename($_FILES["image"]["name"]);
                        $movefile = $_FILES['image']['tmp_name'];
                        $destination = "static/uploads/pages/$imgname";
                        move_uploaded_file($movefile, $destination);
                        $this->db->where('id=?', $id);
                        $this->db->update('pages', ['image' => $destination]);          
                    }
                } else {
                    $imgname = strtolower(basename($_FILES["image"]["name"]));
                    if ($ext == 'jpg' || $ext == 'png' || $ext = 'jpeg' || $ext = 'gif') {              
                        $destination = "static/uploads/pages/$imgname";
                        move_uploaded_file($file['tmp_name'], $destination);
                        //$data['image'] = $destination;
                        $this->db->where('id=?', $id);
                        $this->db->update('pages', ['image' => $destination]);                          
                    }                                       
                } 
        }
    }
    
    function insert($data) {
        $data = $this->upsertPrepareData($data);
        
        $data['widgets'] = (!empty($data['widgets']) && is_array($data['widgets']))? json_encode($data['widgets']) : false;
        
        $data['date_created'] = date("Y-m-d H:i:s");
        $data['date_edited'] = date("Y-m-d H:i:s");
        $data['user_id'] = $_SESSION['user_id'];
        $data['slug'] = slug($data['name']);
        
        // Upload a new image
        if (isset($_FILES['image']) && !$_FILES['image']['error']) {
            
            $file = $_FILES['image'];
             
            $imgname = strtolower(basename($_FILES["image"]["name"]));
            if ($ext == 'jpg' || $ext == 'png' || $ext = 'jpeg' || $ext = 'gif') {              
                $destination = "static/uploads/pages/$imgname";
                move_uploaded_file($file['tmp_name'], $destination);
                $data['image'] = $destination;
            }
        }       
        
        $this->db->insert('pages', $data);
    }
    
    function duplicate($page)
    {
        $duplicate = $page;
        $base_id   = $page['id'];

        unset($duplicate['id']);
        unset($duplicate['date_created']);
        unset($duplicate['date_edited']);
        unset($duplicate['user_id']);
       // unset($duplicate['author']);

        $duplicate['user_id'] = $_SESSION['user_id'];
        $duplicate['image']    = $duplicate['image'];
        $duplicate['hide_title']    = $duplicate['hide_title'];
        $duplicate['styleone']    = $duplicate['styleone'];
        $duplicate['styletwo']    = $duplicate['styletwo'];
        $duplicate['name']    = $duplicate['name'] . " Copy";
        $duplicate['slug']    = $duplicate['slug'] . "-copy";
        //$duplicate['subtitle']    = $duplicate['subtitle'];
        $this->db->insert("pages", $duplicate);

        $duplicate['id'] = $this->db->insert_id();

        return $duplicate['id'];
    }           
    
    function delete($args) {
        if (empty($args)) {
            return;
        }
        
        if (isset($args['id'])) {
            $this->db->where('id=?', $args['id'])->delete('pages');
        }
    }
    
    function getOrders(){
    	if(!$_SESSION['user_id']){
    		return;	
    	}
    	
    	$this->db->where('customer_id=?',  $_SESSION['user_id']);  
    	$this->db->order_by('datetime DESC');
    	$orders = $this->db->select('aatest');
    	//return $orders;
    	
        foreach ($orders as &$order) {      
            $order['items'] = json_decode($order['cart_contents']);
            unset($order);
        }    	
        
        return $orders;
    }
}