<?php
if (!function_exists('h')) {
    function h($s) { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('omr')) {
    function omr($n) { return number_format((float)$n, 3) . ' ر.ع.'; }
}
if (!function_exists('date_ar')) {
    function date_ar($d) { return $d ? date('Y/m/d', strtotime($d)) : '—'; }
}
if (!function_exists('status_label')) {
    function status_label($s) {
        $map = [
            'DRAFT'    => ['مسودة','secondary'],
            'SUBMITTED'=> ['مرفوعة','warning'],
            'APPROVED' => ['معتمدة','success'],
            'REJECTED' => ['مرفوضة','danger'],
            'ISSUED'   => ['صادرة','primary'],
            'PARTIAL'  => ['مدفوعة جزئياً','warning'],
            'PAID'     => ['مدفوعة','success'],
            'CANCELLED'=> ['ملغاة','danger'],
            'OPEN'     => ['مفتوح','success'],
            'CLOSED'   => ['مغلق','secondary'],
        ];
        $v = $map[$s] ?? [$s,'secondary'];
        return '<span class="badge bg-'.$v[1].'">'.$v[0].'</span>';
    }
}
if (!function_exists('deal_label')) {
    function deal_label($d) {
        $map = ['CONSIGNMENT'=>'أمانة','DIRECT_SALE'=>'بيع مباشر','FREE'=>'مجاني'];
        return $map[$d] ?? $d;
    }
}
if (!function_exists('flash')) {
    function flash($msg, $type='success') {
        $_SESSION['flash'] = ['msg'=>$msg,'type'=>$type];
    }
}
if (!function_exists('get_flash')) {
    function get_flash() {
        if (!empty($_SESSION['flash'])) {
            $f = $_SESSION['flash'];
            unset($_SESSION['flash']);
            return $f;
        }
        return null;
    }
}
if (!function_exists('show_flash')) {
    function show_flash() {
        $f = get_flash();
        if ($f) echo '<div class="alert alert-'.$f['type'].'" role="alert">'.h($f['msg']).'</div>';
    }
}
if (!function_exists('redirect')) {
    function redirect(string $url) {
        if (!headers_sent()) {
            header("Location: $url");
            exit;
        } else {
            echo '<script>window.location.href='.json_encode($url).';</script>';
            exit;
        }
    }
}
