<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class cache_model_admin extends CI_Model {

    public function activate_cache($ids = array()) {
        $this->db->
                where_in('id_resource_type_page', $ids)->
                update('resource_type_page', array('cache' => TRUE));
        
        $rs = ($this->db->affected_rows() > 0);
        
        // Clear cache if exists
        $this->clear_cache($ids);

        return $rs;
    }

    public function deactivate_cache($ids = array()) {
        $this->db->
                where_in('id_resource_type_page', $ids)->
                update('resource_type_page', array('cache' => FALSE));

        return ($this->db->affected_rows() > 0);
    }

    public function clear_cache($ids = array()) {
        $data = $this->db->
                        select('alias')->
                        where_in('id_resource_type_page', $ids)->
                        get('resource_type_page')->result_array();
        
        if (empty($data)) {
            
            return FALSE;
        }

        $dir = ($this->config->item('cache_path')) ? : APPPATH . 'cache';
        $files = scandir($dir);
        foreach ($data as $alias) {
            foreach ($files as $item) {
                if (preg_match('/' . $alias['alias'] . '_.*/', $item)) {
                    @unlink($dir . DIRECTORY_SEPARATOR . $item);
                }
            }
        }
        
        return TRUE;
    }

}
