<?php

use App\Models\GeneralSetting;
use Carbon\Carbon;

function general()
{
    $setting = GeneralSetting::first();

    if ($setting) {
        return $setting;
    }

    // Return a lightweight fallback object so callers like
    // `general()->logo` won't trigger "property on null" errors.
    return (object) [
        'sitename' => config('app.name', 'Digitizing Academy'),
        'logo' => 'assets/img/mfm-logo.png',
        'favicon' => 'assets/img/favicon/favicon.png',
    ];
}

function menuActive($routeName, $type = null)
{
    if ($type == 3) {
        $class = 'side-menu-open';
    } elseif ($type == 2) {
        $class = 'active open';
    } else {
        $class = 'active';
    }
    if (is_array($routeName)) {
        foreach ($routeName as $key => $value) {
            if (request()->routeIs($value)) {
                return $class;
            }
        }
    } elseif (request()->routeIs($routeName)) {
        return $class;
    }
}

function uploadImage($file, $directory, $old_file = '')
{
    if (!$file || !$directory) {
        return '';
    }

    deleteImage($old_file);

    $directory = $directory . date('Y') . '/' . date('m') . '/';

    $filename = uniqid() . '.' . $file->getClientOriginalExtension();
    $path = $file->move($directory, $filename);
    return $directory . $filename;
}

function deleteImage($file)
{
    if (!empty($file) && file_exists(public_path($file))) {
        unlink(public_path($file));
    }
}

function getTrx($length = 9)
{
    $characters = 'ABCDEFGHJKMNOPQRSTUVWXYZ1234567890123456789';
    $characters = str_shuffle($characters);
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

function getAmount($amount, $length = null)
{
    if (!is_numeric($length)) {
        $length = 2;
    }

    $amount = number_format($amount, $length, '.', ',');
    return $amount;
}

function showDate($date, $format = 'd/m/Y')
{
    $lang = session()->get('lang');
    Carbon::setlocale($lang);
    return Carbon::parse($date)->translatedFormat($format);
}

function showTime($date, $format = 'h:i A')
{
    $lang = session()->get('lang');
    Carbon::setlocale($lang);
    return Carbon::parse($date)->translatedFormat($format);
}

function showDateTime($date, $format = 'd/m/Y h:i A')
{
    $lang = session()->get('lang');
    Carbon::setlocale($lang);
    return Carbon::parse($date)->translatedFormat($format);
}
