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

if (!function_exists('app_font_cache_path')) {
    function app_font_cache_path()
    {
        return APPPATH . 'cache/ui_font_family.txt';
    }
}

if (!function_exists('app_font_write_cache')) {
    function app_font_write_cache($key)
    {
        $key = preg_replace('/[^a-z0-9_]/', '', strtolower((string) $key));
        if ($key === '') {
            return false;
        }
        $dir = APPPATH . 'cache';
        if (!is_dir($dir)) {
            @mkdir($dir, 0755, true);
        }
        return (bool) @file_put_contents(app_font_cache_path(), $key);
    }
}

if (!function_exists('app_font_read_cache')) {
    function app_font_read_cache()
    {
        $path = app_font_cache_path();
        if (!is_file($path) || !is_readable($path)) {
            return null;
        }
        $key = trim((string) @file_get_contents($path));
        return $key !== '' ? $key : null;
    }
}

if (!function_exists('app_font_config')) {
    /**
     * Active font configuration for UI / PDF / Office exports.
     * Priority: DB → cache file → session → default.
     * @return array{key:string,label:string,css:string,google:string,pdf:string,office:string}
     */
    function app_font_config()
    {
        static $cached = null;
        if ($cached !== null) {
            return $cached;
        }

        $CI =& get_instance();
        $CI->load->model('settings_m');

        $key = null;

        // 1) Database (preferred)
        try {
            if ($CI->settings_m->table_ready()) {
                $db_key = $CI->settings_m->get('ui_font_family', null);
                if ($db_key) {
                    $key = $db_key;
                }
            }
        } catch (Exception $e) {
            $key = null;
        }

        // 2) Cache file (survives session issues / partial deploys)
        if (!$key) {
            $key = app_font_read_cache();
        }

        // 3) Session
        if (!$key && $CI->session) {
            $key = $CI->session->userdata('ui_font_family');
        }

        if (!$key) {
            $key = 'ibm_plex';
        }

        $cached = $CI->settings_m->resolve_font($key);

        // Keep session + cache aligned
        if ($CI->session && $CI->session->userdata('ui_font_family') !== $cached['key']) {
            $CI->session->set_userdata('ui_font_family', $cached['key']);
        }
        if (app_font_read_cache() !== $cached['key']) {
            app_font_write_cache($cached['key']);
        }

        return $cached;
    }
}

if (!function_exists('app_font_css')) {
    function app_font_css()
    {
        $cfg = app_font_config();
        return isset($cfg['css']) ? $cfg['css'] : '"IBM Plex Sans", "Segoe UI", system-ui, sans-serif';
    }
}

if (!function_exists('app_font_css_raw')) {
    /**
     * Font stack safe for embedding in <style> / style="" (no HTML entity encoding).
     */
    function app_font_css_raw()
    {
        return preg_replace('/[<>{;]/', '', app_font_css());
    }
}

if (!function_exists('app_font_pdf')) {
    function app_font_pdf()
    {
        $cfg = app_font_config();
        return isset($cfg['pdf']) ? $cfg['pdf'] : 'DejaVu Sans';
    }
}

if (!function_exists('app_font_office')) {
    function app_font_office()
    {
        $cfg = app_font_config();
        return isset($cfg['office']) ? $cfg['office'] : 'Calibri, Arial, sans-serif';
    }
}

if (!function_exists('app_font_google_href')) {
    function app_font_google_href()
    {
        $cfg = app_font_config();
        if (empty($cfg['google'])) {
            return '';
        }
        return 'https://fonts.googleapis.com/css2?family=' . $cfg['google'] . '&display=swap';
    }
}

if (!function_exists('app_font_label')) {
    function app_font_label()
    {
        $cfg = app_font_config();
        return isset($cfg['label']) ? $cfg['label'] : 'IBM Plex Sans';
    }
}

if (!function_exists('app_document_signatory')) {
    /**
     * SO / CRV signatory text from Settings. Empty string means omit from documents.
     * First use seeds the legacy default so existing PDFs keep working until cleared.
     * @return string
     */
    function app_document_signatory()
    {
        static $cached = null;
        if ($cached !== null) {
            return $cached;
        }

        $CI =& get_instance();
        $CI->load->model('settings_m');
        $value = '';
        try {
            $CI->settings_m->ensure_table();
            $row = $CI->db->where('setting_key', 'document_signatory')->get('app_settings')->row();
            if (!$row) {
                $legacy = "G Chandrashekhar, Sc-F,\nWing Head, KRC";
                $CI->settings_m->set('document_signatory', $legacy);
                $value = $legacy;
            } else {
                $value = (string) $row->setting_value;
            }
        } catch (Exception $e) {
            $value = '';
        }
        $cached = trim($value);
        return $cached;
    }
}

if (!function_exists('app_document_signatory_html')) {
    /**
     * Signatory HTML for PDF (escaped, newlines → &lt;br&gt;). Empty if not configured.
     * @return string
     */
    function app_document_signatory_html()
    {
        $text = app_document_signatory();
        if ($text === '') {
            return '';
        }
        return nl2br(htmlspecialchars($text, ENT_QUOTES, 'UTF-8'), false);
    }
}

if (!function_exists('app_document_signatory_attn')) {
    /**
     * Single-line Kind Attn text (newlines collapsed). Empty if not configured.
     * @return string
     */
    function app_document_signatory_attn()
    {
        $text = app_document_signatory();
        if ($text === '') {
            return '';
        }
        return preg_replace('/\s+/u', ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $text));
    }
}

if (!function_exists('app_setting_text')) {
    /**
     * Read a text setting from app_settings (trimmed). Empty if missing.
     * @param string $key
     * @return string
     */
    function app_setting_text($key)
    {
        $CI =& get_instance();
        $CI->load->model('settings_m');
        try {
            $CI->settings_m->ensure_table();
            $value = $CI->settings_m->get($key, '');
            return trim((string) $value);
        } catch (Exception $e) {
            return '';
        }
    }
}

if (!function_exists('app_setting_text_html')) {
    /**
     * Escaped HTML for multiline settings (newlines → br).
     * @param string $key
     * @return string
     */
    function app_setting_text_html($key)
    {
        $text = app_setting_text($key);
        if ($text === '') {
            return '';
        }
        return nl2br(htmlspecialchars($text, ENT_QUOTES, 'UTF-8'), false);
    }
}

if (!function_exists('app_lac_signatory_left')) {
    function app_lac_signatory_left()
    {
        return app_setting_text('lac_signatory_left');
    }
}

if (!function_exists('app_lac_signatory_right')) {
    function app_lac_signatory_right()
    {
        return app_setting_text('lac_signatory_right');
    }
}

if (!function_exists('app_lac_signatory_left_html')) {
    function app_lac_signatory_left_html()
    {
        return app_setting_text_html('lac_signatory_left');
    }
}

if (!function_exists('app_lac_signatory_right_html')) {
    function app_lac_signatory_right_html()
    {
        return app_setting_text_html('lac_signatory_right');
    }
}

if (!function_exists('app_weed_out_signatory_left')) {
    function app_weed_out_signatory_left()
    {
        return app_setting_text('weed_out_signatory_left');
    }
}

if (!function_exists('app_weed_out_signatory_right')) {
    function app_weed_out_signatory_right()
    {
        return app_setting_text('weed_out_signatory_right');
    }
}

if (!function_exists('app_weed_out_signatory_left_html')) {
    function app_weed_out_signatory_left_html()
    {
        return app_setting_text_html('weed_out_signatory_left');
    }
}

if (!function_exists('app_weed_out_signatory_right_html')) {
    function app_weed_out_signatory_right_html()
    {
        return app_setting_text_html('weed_out_signatory_right');
    }
}

if (!function_exists('app_crv_number')) {
    /**
     * Manual CRV number from Settings (no auto-increment).
     * @return string
     */
    function app_crv_number()
    {
        return app_setting_text('crv_number');
    }
}
