<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Author: Remy Sharp (http://remysharp.com)
 *
 * Based on CodeIgniter 1.6.1
 * 
 * Description: Main controller for our app - it manages the header and footer
 * and log in logic.  All controllers should extend this controller.
 * 
 * 
 * VERSION: 1.0 (2008-03-25)
 * 
 **/
class MY_Controller extends Controller {
    var $logged_in      = false;
    var $debug_sql      = false;
    var $login_required = false; // can be overrided in controller
    var $ajax           = false;
    var $page_title     = ''; // should be set in extended controller

    function MY_Controller() {
        parent::Controller();
        
        $this->ajax = ($this->input->server('HTTP_X_REQUESTED_WITH') || $this->input->post('ajax') ? true : false);
        
        if (preg_match('/display_sql/', @$_SERVER['HTTP_USER_AGENT'])) {
            $this->debug_sql = true;
        }
    }
    
    // helper
    protected function requires_login($req = true) {
        $this->login_required = $req;
    }
    
    protected function debug_sql($ok = true) {
        $this->debug_sql = $ok;
    }
    
    protected function header() {
        // log in logic
        if ($this->login_required && !$this->logged_in) {
            // redirect to login
            $this->load->helper('url');
            redirect('/login');
        } else if (!$this->ajax && $this->logged_in) {
            // logged in header
            $this->load->view('header_logged_in', array('page_title' => $this->page_title));
        } else if (!$this->ajax) {
            // default header
            $this->load->view('header_logged_out', array('page_title' => $this->page_title));
        }
        
        // by default ajax doesn't have a header or footer
    }
    
    // simple page
    protected function view($view, $data = array()) {
        $this->header();
        
        if ($this->debug_sql && $this->db->queries) {
            $this->load->view('debug_sql', array('queries' => $this->db->queries, 'query_times' => $this->db->query_times));
        }
        
        $this->load->view($view, $data);
        $this->footer();
    }
    
    protected function footer() {
        if (!$this->ajax) {
            $this->load->view('footer');
        }
    }
}
?>