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

if (!function_exists('finance_sync_model')) {
    function finance_sync_model()
    {
        $CI = &get_instance();
        if (!isset($CI->finance_sync_model)) {
            $CI->load->model('finance_sync_model');
        }
        return $CI->finance_sync_model;
    }
}

if (!function_exists('finance_report_model')) {
    function finance_report_model()
    {
        $CI = &get_instance();
        if (!isset($CI->finance_report_model)) {
            $CI->load->model('finance_report_model');
        }
        return $CI->finance_report_model;
    }
}

if (!function_exists('finance_accounting_period_is_open')) {
    function finance_accounting_period_is_open($date)
    {
        $date = date('Y-m-d', safe_strtotime($date));
        if ($date === '1970-01-01') {
            return true;
        }
        $CI = &get_instance();
        if (!$CI->db->table_exists('tbl_accounting_periods')) {
            return true;
        }
        $row = $CI->db
            ->where('start_date <=', $date)
            ->where('end_date >=', $date)
            ->where('status', 'closed')
            ->order_by('period_id', 'desc')
            ->limit(1)
            ->get('tbl_accounting_periods')
            ->row();
        return empty($row);
    }
}

if (!function_exists('finance_guard_accounting_period')) {
    function finance_guard_accounting_period($date, $label = null)
    {
        if (finance_accounting_period_is_open($date)) {
            return true;
        }
        $message = !empty($label)
            ? sprintf('%s %s', $label, lang('accounting_period_closed'))
            : lang('accounting_period_closed');
        set_message('error', $message);
        return false;
    }
}

if (!function_exists('finance_accounting_period_label')) {
    function finance_accounting_period_label($status)
    {
        $status = strtolower((string) $status);
        if ($status === 'closed') {
            return '<span class="label label-danger">' . lang('closed') . '</span>';
        }
        return '<span class="label label-success">' . lang('open') . '</span>';
    }
}

if (!function_exists('finance_cache_delete')) {
    function finance_cache_delete($key)
    {
        $CI = &get_instance();
        if (isset($CI->cache)) {
            $CI->cache->delete($key);
        }
        return true;
    }
}
