<?php
require_once(ROOT . DS . 'app' . DS . 'lib' . DS . 'helpers' . DS . 'helpers.php');

/* ── Input validation ───────────────────────────────────────── */

function checkMTInputsPost($data) {
    foreach ($data as $v) {
        if (strlen(trim($v)) == 0) return false;
    }
    return true;
}

function checkLenPostVals($arr_post_vals) {
    $submit_form = 0;
    $fb_msg = "";
    foreach ($arr_post_vals as $key => $label) {
        if (strlen(trim($_POST[$key] ?? '')) == 0) {
            $submit_form++;
            $fb_msg .= "Please fill in <strong>{$label}</strong>.<br/>";
        }
    }
    return ["submit_form" => $submit_form, "fb_msg" => $fb_msg];
}

function checkLenArrVals($arr_vals, $arr) {
    $submit_form = 0;
    $fb_msg = "";
    foreach ($arr_vals as $key => $label) {
        if (strlen(trim($arr[$key] ?? '')) == 0) {
            $submit_form++;
            $fb_msg .= "{$submit_form}. Please fill in <strong>{$label}</strong>.<br/>";
        }
    }
    return ["submit_form" => $submit_form, "fb_msg" => $fb_msg];
}

/* ── Date helpers ───────────────────────────────────────────── */

function addDays($date, $days) {
    return date("Y-m-d", strtotime($date . " + {$days} days"));
}

function subDays($date, $days) {
    return date("Y-m-d", strtotime($date . " - {$days} days"));
}

function humanDate($date) {
    return $date ? date("d M Y", strtotime($date)) : '-';
}

function humanDateTime($dt) {
    return $dt ? date("d M Y, H:i", strtotime($dt)) : '-';
}

/* ── String helpers ─────────────────────────────────────────── */

function makeSlug($text) {
    $text = strtolower(trim($text));
    $text = preg_replace('/[^a-z0-9\s\-]/', '', $text);
    $text = preg_replace('/[\s\-]+/', '-', $text);
    return trim($text, '-');
}

function truncate($text, $length = 120, $suffix = '...') {
    if (strlen($text) <= $length) return $text;
    return rtrim(substr($text, 0, $length)) . $suffix;
}

function e($str) {
    return htmlspecialchars((string)$str, ENT_QUOTES, 'UTF-8');
}

/* ── Return-URL helpers (cross-module navigation) ───────────────
 * When a link in one module points at a shared Directory entity,
 * tag it with the origin so the destination can render a "← Back to X"
 * pill and the user's context is preserved.
 *
 * Usage:
 *   In a Shop PO detail view (linking to supplier):
 *     <a href="<?= retLink('ShopSuppliers/view/'.$supId, 'PO '.$po['po_number']); ?>">Keko Pharma</a>
 *
 *   In the supplier view template, top of page:
 *     <?= retBadge(); ?>
 *
 * The label is optional — if omitted the pill reads "← Back".
 */
function retLink(string $path, ?string $label = null): string {
    $current = $_SERVER['REQUEST_URI'] ?? '';
    // Strip PROOT prefix so ret= is portable
    $proot = defined('PROOT') ? PROOT : '/';
    if (strpos($current, $proot) === 0) {
        $current = substr($current, strlen($proot));
    }
    $query = ['ret' => $current];
    if ($label !== null && $label !== '') $query['ret_label'] = $label;
    $sep = (strpos($path, '?') === false) ? '?' : '&';
    return (defined('PROOT') ? PROOT : '/') . $path . $sep . http_build_query($query);
}

function retBadge(): string {
    $ret   = $_GET['ret']       ?? '';
    $label = $_GET['ret_label'] ?? '';
    if ($ret === '') return '';
    // Only accept relative paths — prevents open-redirect abuse.
    if (preg_match('#^https?://#i', $ret) || strpos($ret, '//') === 0) return '';
    $proot = defined('PROOT') ? PROOT : '/';
    $url   = $proot . ltrim($ret, '/');
    $text  = $label !== '' ? 'Back to ' . e($label) : 'Back';
    return '<a href="' . e($url) . '" class="btn btn-sm btn-outline-secondary mb-3">'
         . '<i class="fas fa-arrow-left me-1"></i>' . $text . '</a>';
}

/* ── File helpers ───────────────────────────────────────────── */

function formatFileSize($bytes) {
    if ($bytes >= 1048576) return round($bytes / 1048576, 2) . ' MB';
    if ($bytes >= 1024)    return round($bytes / 1024, 2)    . ' KB';
    return $bytes . ' B';
}

function isImage($filename) {
    return (bool)preg_match('/\.(jpg|jpeg|png|gif|webp|svg)$/i', $filename);
}

/* ── Number helpers ─────────────────────────────────────────── */

function fmtNumber($n, $decimals = 0) {
    return number_format((float)$n, $decimals, '.', ',');
}

function fmtCurrency($n, $symbol = 'TZS') {
    return $symbol . ' ' . number_format((float)$n, 2, '.', ',');
}

/* ── CSRF token helpers ─────────────────────────────────────── */

/** Emit a hidden input carrying the session CSRF token. Every POST form must include this. */
function csrf_field(): string {
    $k = defined('CSRF_TOKEN_KEY') ? CSRF_TOKEN_KEY : 'csrf_token';
    if (empty($_SESSION[$k])) {
        $_SESSION[$k] = bin2hex(random_bytes(32));
    }
    return '<input type="hidden" name="csrf_token" value="' . htmlspecialchars($_SESSION[$k], ENT_QUOTES, 'UTF-8') . '">';
}

/** Return the raw CSRF token — for AJAX headers, meta tags, JS. */
function csrf_token(): string {
    $k = defined('CSRF_TOKEN_KEY') ? CSRF_TOKEN_KEY : 'csrf_token';
    if (empty($_SESSION[$k])) {
        $_SESSION[$k] = bin2hex(random_bytes(32));
    }
    return $_SESSION[$k];
}

/* ── Flash message HTML helper ──────────────────────────────── */

function flashHtml($realm = null) {
    // Realm resolution: caller override → super if super session → else tenant.
    if ($realm === null) {
        $realm = !empty($_SESSION['super_admin_id']) ? 'super' : 'tenant';
    }
    $mKey = 'flash_' . $realm . '_msg';
    $tKey = 'flash_' . $realm . '_type';
    // Back-compat: consume legacy shared keys if this realm has none of its own.
    if (empty($_SESSION[$mKey]) && !empty($_SESSION['flash_msg'])) {
        $_SESSION[$mKey] = $_SESSION['flash_msg'];
        $_SESSION[$tKey] = $_SESSION['flash_type'] ?? 'info';
        unset($_SESSION['flash_msg'], $_SESSION['flash_type']);
    }
    if (empty($_SESSION[$mKey])) return '';
    $msg  = $_SESSION[$mKey];
    $type = $_SESSION[$tKey] ?? 'info';
    unset($_SESSION[$mKey], $_SESSION[$tKey]);
    $icon = [
        'success' => 'check-circle',
        'danger'  => 'exclamation-circle',
        'warning' => 'exclamation-triangle',
        'info'    => 'info-circle',
    ][$type] ?? 'info-circle';
    return "<div class='alert alert-{$type} alert-dismissible fade show' role='alert'>
        <i class='fas fa-{$icon} me-2'></i>{$msg}
        <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
    </div>";
}
