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

/**
 * NCS Billing System - License Verification Hook
 *
 * This hook verifies the license on every request.
 * It uses caching to minimize performance impact.
 */
class License_hook {

    private $CI;
    private $cache_duration = 3600; // Cache license check for 1 hour
    private $excluded_controllers = [
        'cron',        // Allow cron jobs
        'api',         // Allow API endpoints (they may have their own auth)
        'login',       // Allow access to login page
        'license',     // Allow license reactivation page when expired
    ];
    
    /**
     * Read license.lock and return true if license is expired (non-lifetime with past/missing expiry).
     */
    private function is_license_expired_from_lock() {
        $license_file = FCPATH . 'license.lock';
        if (!file_exists($license_file)) {
            return false;
        }
        if (!defined('NCS_BILLING')) {
            define('NCS_BILLING', true);
        }
        $data = @include($license_file);
        if (!$data || !is_array($data)) {
            return false;
        }
        if (!empty($data['is_lifetime']) && ($data['is_lifetime'] === true || $data['is_lifetime'] === 1)) {
            return false;
        }
        $expiry = isset($data['expiry_date']) ? trim((string)$data['expiry_date']) : '';
        if ($expiry === '') {
            return true;
        }
        $ts = strtotime($expiry);
        return ($ts === false || time() > $ts);
    }

    // Check if we're in installation/setup mode
    private function is_installation_mode() {
        // Check if setup directory is being accessed
        $uri = $this->CI->uri->uri_string();
        if (strpos($uri, 'setup/') !== false || strpos($uri, 'install') !== false) {
            return true;
        }
        
        // Check if install.lock doesn't exist (first time installation)
        $install_lock = FCPATH . 'install.lock';
        if (!file_exists($install_lock)) {
            return true;
        }
        
        return false;
    }
    private $excluded_methods = [];

    public function verify_license() {
        $this->CI =& get_instance();

        // Skip license check during installation
        if ($this->is_installation_mode()) {
            return;
        }

        // Get current controller and method
        $controller = $this->CI->router->class;
        $method = $this->CI->router->method;
        $uri = $this->CI->uri->uri_string();

        // Skip license check for excluded controllers (and by URI so license/reactivate and license/do_reactivate always work)
        if (in_array(strtolower($controller), $this->excluded_controllers)) {
            return;
        }
        if (strpos(strtolower($uri), 'license/') === 0 || strpos(strtolower($uri), 'license') === 0) {
            return;
        }

        // Skip for excluded methods
        if (in_array(strtolower($controller . '/' . $method), $this->excluded_methods)) {
            return;
        }
        
        // Skip if license file doesn't exist (installation not complete)
        $license_file = FCPATH . 'license.lock';
        if (!file_exists($license_file)) {
            return; // Allow access if license file doesn't exist yet
        }

        // Check cache first (but never trust cache for expiry - always re-check lock file for non-lifetime)
        $cache_file = FCPATH . '.license_valid_cache';
        if (file_exists($cache_file)) {
            $cache_data = json_decode(file_get_contents($cache_file), true);
            if ($cache_data && isset($cache_data['timestamp']) && isset($cache_data['valid'])) {
                $cache_age = time() - $cache_data['timestamp'];
                if ($cache_age < $this->cache_duration) {
                    if ($cache_data['valid']) {
                        // Always re-check expiry from lock file (cache can be stale; never trust cache for expiry)
                        if ($this->is_license_expired_from_lock()) {
                            @unlink($cache_file);
                            $this->show_license_error('License has expired. Consider renewing.');
                            return;
                        }
                        if (isset($cache_data['info'])) {
                            $this->CI->license_info = $cache_data['info'];
                        }
                        if (isset($cache_data['warning']) && $cache_data['warning']) {
                            $this->CI->license_warning = $cache_data['message'] ?? 'License expiring soon.';
                        }
                        return;
                    } else {
                        error_log('License cache shows invalid - clearing cache and re-checking');
                        @unlink($cache_file);
                    }
                }
            }
        }

        // Load license checker library
        $this->CI->load->library('License_checker');

        // Perform license check
        $result = $this->CI->license_checker->check_license();

        // Cache the result (do not cache valid=true when license is expired)
        $cache_data = [
            'timestamp' => time(),
            'valid' => $result['valid'],
            'message' => $result['message'] ?? '',
            'warning' => $result['warning'] ?? false,
            'info' => $this->CI->license_checker->get_license_info()
        ];
        if ($result['valid'] || (isset($result['code']) && $result['code'] !== 'LICENSE_EXPIRED')) {
            file_put_contents($cache_file, json_encode($cache_data));
        } else {
            @unlink($cache_file);
        }

        // Block access when license has expired (monthly/annual) - application non-usable until renewal
        if (!$result['valid'] && isset($result['code']) && $result['code'] === 'LICENSE_EXPIRED') {
            $this->show_license_error($result['message'] ?? 'License has expired. Consider renewing.');
            return;
        }

        if (!$result['valid']) {
            error_log('License check warning: ' . ($result['message'] ?? 'Unknown error') . ' (Code: ' . ($result['code'] ?? 'UNKNOWN') . ')');
            if (isset($result['code']) && $result['code'] === 'INTEGRITY_WARNING') {
                $this->CI->license_warning = $result['message'] ?? 'License integrity check warning';
            }
        }

        $this->CI->license_info = $cache_data['info'];
        if (isset($result['warning']) && $result['warning']) {
            $this->CI->license_warning = $result['message'];
        }
    }

    /**
     * Display license error page and stop execution
     */
    private function show_license_error($message) {
        // Check if this is an AJAX request
        if ($this->CI->input->is_ajax_request()) {
            header('Content-Type: application/json');
            echo json_encode([
                'status' => 'error',
                'message' => 'License Error: ' . $message,
                'code' => 'LICENSE_ERROR'
            ]);
            exit;
        }

        // Show HTML error page - Professional and attractive design
        $is_expired = (strpos($message, 'expired') !== false || strpos($message, 'renew') !== false);
        $page_title = $is_expired ? 'License Expired - NCS Billing System' : 'License Error - NCS Billing System';
        $index_page = $this->CI->config->item('index_page');
        $base = rtrim($this->CI->config->base_url(), '/');
        $reactivate_url = $base . ($index_page ? '/' . $index_page : '') . '/license/reactivate';
        $html = '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>' . htmlspecialchars($page_title) . '</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f5f5;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .error-container {
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.15);
            max-width: 550px;
            width: 100%;
            overflow: hidden;
            animation: slideUp 0.4s ease-out;
        }
        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        .error-header {
            background: #e74c3c;
            color: white;
            padding: 30px;
            text-align: center;
        }
        .error-icon {
            font-size: 64px;
            margin-bottom: 15px;
            animation: pulse 2s infinite;
        }
        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.05); }
        }
        .error-header h1 {
            font-size: 28px;
            font-weight: 600;
            margin-bottom: 8px;
        }
        .error-header p {
            font-size: 15px;
            opacity: 0.95;
        }
        .error-body {
            padding: 30px;
        }
        .message-box {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 18px 20px;
            margin-bottom: 25px;
            border-radius: 8px;
        }
        .message-box i {
            color: #f39c12;
            margin-right: 10px;
            font-size: 18px;
        }
        .message-box p {
            color: #856404;
            margin: 0;
            font-size: 15px;
            line-height: 1.6;
            font-weight: 500;
        }
        .info-text {
            color: #555;
            font-size: 14px;
            line-height: 1.7;
            margin-bottom: 25px;
            text-align: center;
        }
        .action-buttons {
            display: flex;
            gap: 12px;
            margin-bottom: 25px;
            justify-content: center;
        }
        .btn {
            flex: 1;
            padding: 14px 20px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        .btn-primary {
            background: #3498db;
            color: white;
        }
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(52, 152, 219, 0.4);
        }
        .btn-secondary {
            background: #ecf0f1;
            color: #2c3e50;
            border: 2px solid #bdc3c7;
        }
        .btn-secondary:hover {
            background: #d5dbdb;
            border-color: #95a5a6;
        }
        .contact-section {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-top: 25px;
            border-top: 3px solid #e9ecef;
        }
        .contact-section h3 {
            color: #2c3e50;
            font-size: 16px;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .contact-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 10px 0;
            color: #555;
            font-size: 14px;
        }
        .contact-item i {
            color: #3498db;
            font-size: 16px;
            width: 20px;
        }
        .contact-item a {
            color: #2980b9;
            text-decoration: none;
            font-weight: 500;
            transition: color 0.3s;
        }
        .contact-item a:hover {
            color: #1abc9c;
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="error-container">
        <div class="error-header">
            <div class="error-icon">
                <i class="fas fa-exclamation-triangle"></i>
            </div>
            <h1>' . ($is_expired ? 'License Expired' : 'License Error') . '</h1>
            <p>' . ($is_expired ? 'Your Jasiri Dynamics System license has expired. Please renew to continue.' : 'Your Jasiri Dynamics System license has encountered an issue') . '</p>
        </div>
        <div class="error-body">
            <div class="message-box">
                <p><i class="fas fa-info-circle"></i> ' . htmlspecialchars($message) . '</p>
            </div>
            <p class="info-text">Please enter your valid license below to continue using the system.</p>
            <div class="action-buttons">
                <a href="' . htmlspecialchars($reactivate_url) . '" class="btn btn-primary"><i class="fas fa-key"></i> Enter new license</a>
            </div>
           <p class="info-text" style="margin-top: 15px;">
            If you believe this is an error, kindly reach out to support via call or WhatsApp at +254 799-075-857 or +254 707-733-580 with your license details for quick assistance.
            </p>
        </div>
    </div>
</body>
</html>';

        echo $html;
        exit;
    }
}
