<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class LicenseGuard
{
    public function run()
    {
        $ci =& get_instance();
        $ci->config->load('license', TRUE);
        $cfg = (array) $ci->config->item('license');
        if (empty($cfg['license_enabled']) || is_cli()) return;
        $controller = strtolower((string) $ci->router->fetch_class());
        if (in_array($controller, array_map('strtolower', $cfg['license_whitelist_controllers']), TRUE)) return;
        $ci->load->library('LicenseManager', NULL, 'license_manager');
        $status = $ci->license_manager->status(FALSE);
        if (!empty($status['success'])) return;
        $accept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : '';
        if ($ci->input->is_ajax_request() || strpos($accept, 'application/json') !== FALSE) {
            $ci->output->set_status_header(423)->set_content_type('application/json')->set_output(json_encode(array('success'=>FALSE,'code'=>$status['code'],'message'=>$status['message'])))->_display();
            exit;
        }
        $ci->output->set_status_header(423)->set_output($ci->load->view('license/restricted', array('status'=>$status), TRUE))->_display();
        exit;
    }
}

