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

/* ==========================================================================
 * BLOOM IRIS AGENCY — BLOOM HELPER
 * Brand-wide template helper functions.
 * ======================================================================= */

if ( ! function_exists('asset_url'))
{
	/** Build a URL to a file inside the /assets directory. */
	function asset_url($path = '')
	{
		return base_url('assets/'.ltrim($path, '/'));
	}
}

if ( ! function_exists('upload_url'))
{
	/**
	 * Build a URL to an uploaded media file. Falls back to a placeholder
	 * when the file is empty or missing on disk.
	 */
	function upload_url($path = '', $placeholder = 'img/placeholder.jpg')
	{
		$base = 'assets/uploads/';
		if (empty($path))
		{
			return base_url('assets/'.$placeholder);
		}
		$full = FCPATH.$base.$path;
		if ( ! is_file($full))
		{
			return base_url('assets/'.$placeholder);
		}
		return base_url($base.$path);
	}
}

if ( ! function_exists('setting'))
{
	/** Fetch a global setting value from the loaded settings map. */
	function setting($key, $default = '')
	{
		$CI =& get_instance();
		
		// First check if settings are loaded in controller
		if (isset($CI->settings) && is_array($CI->settings) && isset($CI->settings[$key]) && $CI->settings[$key] !== '')
		{
			return $CI->settings[$key];
		}
		
		// If not found in controller settings, try direct database query
		static $direct_settings = null;
		if ($direct_settings === null) {
			if (isset($CI->db) && isset($CI->setting_model)) {
				$direct_settings = array();
				$query = $CI->db->get('settings');
				foreach ($query->result_array() as $row) {
					$direct_settings[$row['key']] = $row['value'];
				}
			}
		}
		
		if ($direct_settings !== null && isset($direct_settings[$key]) && $direct_settings[$key] !== '') {
			return $direct_settings[$key];
		}
		
		return $default;
	}
}

if ( ! function_exists('whatsapp_link'))
{
	/**
	 * Build a wa.me deep-link using the configured WhatsApp number, with an
	 * optional message appended to the global pre-filled text.
	 */
	function whatsapp_link($extra = '')
	{
		$number  = preg_replace('/[^0-9]/', '', setting('whatsapp', '233593854493'));
		$message = trim(setting('whatsapp_message', 'Hello Bloom Iris').' '.$extra);
		return 'https://wa.me/'.$number.'?text='.rawurlencode($message);
	}
}

if ( ! function_exists('excerpt'))
{
	/** Trim HTML/text to a clean word-bounded excerpt. */
	function excerpt($text, $words = 24)
	{
		$text = trim(strip_tags((string) $text));
		if ($text === '') return '';
		$parts = preg_split('/\s+/', $text);
		if (count($parts) <= $words) return $text;
		return implode(' ', array_slice($parts, 0, $words)).'…';
	}
}

if ( ! function_exists('money'))
{
	/** Format a number as GHS currency. */
	function money($amount)
	{
		$CI =& get_instance();
		$symbol = $CI->config->item('currency_symbol') ?: 'GHS ';
		return $symbol.number_format((float) $amount, 2);
	}
}

if ( ! function_exists('youtube_thumb'))
{
	/** Build a YouTube thumbnail URL from a video ID. */
	function youtube_thumb($id, $quality = 'hqdefault')
	{
		return 'https://img.youtube.com/vi/'.$id.'/'.$quality.'.jpg';
	}
}

if ( ! function_exists('youtube_id'))
{
	/** Extract a YouTube video ID from a full URL or return the ID as-is. */
	function youtube_id($url)
	{
		if (empty($url)) return '';
		if (preg_match('/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{6,})/', $url, $m))
		{
			return $m[1];
		}
		return preg_replace('/[^A-Za-z0-9_-]/', '', $url);
	}
}

if ( ! function_exists('decode_json'))
{
	/** Safely decode a JSON column to an array. */
	function decode_json($value, $default = array())
	{
		if (is_array($value)) return $value;
		if (empty($value)) return $default;
		$out = json_decode($value, TRUE);
		return is_array($out) ? $out : $default;
	}
}

if ( ! function_exists('active_link'))
{
	/** Return a CSS class when the first URI segment matches. */
	function active_link($segment, $class = 'is-active')
	{
		$CI =& get_instance();
		return ($CI->uri->segment(1) === $segment) ? $class : '';
	}
}

if ( ! function_exists('read_time'))
{
	/** Estimate reading time in minutes for a body of text. */
	function read_time($text)
	{
		$count = str_word_count(strip_tags((string) $text));
		return max(1, (int) ceil($count / 200));
	}
}

if ( ! function_exists('nice_date'))
{
	/** Format a date string for display, gracefully handling empties. */
	function nice_date($date, $format = 'd M Y')
	{
		if (empty($date) || $date === '0000-00-00' || $date === '0000-00-00 00:00:00')
		{
			return '';
		}
		$ts = strtotime($date);
		return $ts ? date($format, $ts) : '';
	}
}
