<?php
/**
 * Created by PhpStorm.
 * User: tatu
 * Date: 6/23/20
 * Time: 12:10 AM
 */

use App\Models\AppSession;
use App\Models\Client;
use App\Models\Pro;
use App\Models\Bill;
//require_once './class.Diff.php';
use Illuminate\Support\Facades\Http;
use Soundasleep\Html2Text as Html2Text;


if(!function_exists('chargeForCPT')) {
    function chargeForCPT($cpt) {
        switch($cpt) {
            case "99202": return '$' . 172;
            case "99203": return '$' . 262;
            case "99204": return '$' . 387;
            case "99205": return '$' . 512;
            case "99211": return '$' . 56;
            case "99212": return '$' . 133;
            case "99213": return '$' . 212;
            case "99214": return '$' . 297;
            case "99215": return '$' . 418;
            case "99354": return '$' . 289;
            case "G0506": return '$' . 144;
            case "99441": return '$' . 132;
            case "99442": return '$' . 211;
            case "99443": return '$' . 297;
            case "99454": return '$' . 138;
            case "99457": return '$' . 117;
            case "99458": return '$' . 93;
            case "90791": return '$' . 394;
            case "90792": return '$' . 444;
            case "90832": return '$' . 171;
            case "90834": return '$' . 226;
            case "90837": return '$' . 332;
            case "90833": return '$' . 158;
            case "90836": return '$' . 199;
            case "90838": return '$' . 261;
            case "99355": return '$' . 130;
            case "97802": return '$' . 60;
            case "97803": return '$' . 50;
            case "99495": return '$' . 275;
            case "99406": return '$' . 35.56;
            case "99091": return '$' . 75;
            case "99453": return '$' . 40;
        }

        return '-';
    }
}

if(!function_exists('currentSortForKey')) {
    function currentSortForKey($current, $key) {
        $found = false;
        $current = $current ? $current : [];
        for ($i = 0; $i < count($current); $i++) {
            if($current[$i]['key'] === $key) { // if exists, reverse
                return ["index" => ($i + 1), "order" => $current[$i]['order']];
            }
        }
        return FALSE;
    }
}

if(!function_exists('includeOrReverseInMultiSort')) {
    function includeOrReverseInMultiSort($current, $key) {
        $found = false;
        $current = $current ? $current : [];
        for ($i = 0; $i < count($current); $i++) {
            if($current[$i]['key'] === $key) { // if exists, reverse
                $current[$i]['order'] = ($current[$i]['order'] === 'DESC' ? 'ASC' : 'DESC');
                $found = true;
                break;
            }
        }
        if (!$found) { // if not exists, include
            $current[] = ["key" => $key, "order" => 'ASC'];
        }
        return $current;
    }
}

if(!function_exists('removeFromMultiSort')) {
    function removeFromMultiSort($current, $key) {
        $found = false;
        $current = $current ? $current : [];
        $current = array_filter($current, function($_x) use ($key) {
            return $_x['key'] !== $key;
        });
        return array_values($current);
    }
}

if(!function_exists('toFeetAndInches')) {
    function toFeetAndInches($value, $ftLabel = ' ft.', $inLabel = ' in.') {
        if(!$value) return '-';
        $value = round($value);
        $ft = round(floor($value / 12));
        $in = $value % 12;
        return "$ft$ftLabel $in$inLabel";
    }
}

if(!function_exists('callJava')) {
    function callJava($endPoint, $data, $sessionKey) {
        $url = config('stag.backendUrl') . $endPoint;
        $response = Http::asForm()
            ->withHeaders([
                'sessionKey' => $sessionKey
            ])
            ->post($url, $data)
            ->body();
        return $response;
    }
}

if(!function_exists('feetFromInches')) {
    function feetFromInches($value) {
        if(!$value) return 0;
        $value = round($value);
        return round(floor($value / 12));
    }
}

if(!function_exists('inchesAfterFeetFromInches')) {
    function inchesAfterFeetFromInches($value) {
        if(!$value) return 0;
        $value = round($value);
        return round($value % 12);
    }
}

if(!function_exists('genericBills')) {
    function genericBills(Pro $performerPro, $patient,$careMonth, $entityType, $entityUid) {
        $genericBills = Bill::where('bill_service_type', 'GENERIC');
        if($performerPro->pro_type !== 'ADMIN') {
            $genericBills = $genericBills->where('generic_pro_id', $performerPro->id);
        }
        if($patient) {
            $genericBills = $genericBills->where('client_id', $patient->id);
        }


        if($careMonth){
            $genericBills = $genericBills->where('care_month_id', $careMonth->id);
        }

        if($entityType && $entityUid) {

            $genericBills = $genericBills
                ->where('generic_target_entity_type', $entityType)
                ->where('generic_target_entity_uid', $entityUid);


        }
        return $genericBills->orderBy('created_at', 'DESC')->get();
    }
}

if(!function_exists('hasActiveGenericBill')) {
    function hasActiveGenericBill(Pro $performerPro, $patient, $entityType, $entityUid) {
        $genericBills = Bill::where('bill_service_type', 'GENERIC')->where('is_cancelled', false);
        if($performerPro->pro_type !== 'ADMIN') {
            $genericBills = $genericBills->where('generic_pro_id', $performerPro->id);
        }
        if($patient) {
            $genericBills = $genericBills->where('client_id', $patient->id);
        }
        if($entityType && $entityUid) {
            $genericBills = $genericBills
                ->where('generic_target_entity_type', $entityType)
                ->where('generic_target_entity_uid', $entityUid);
        }
        return $genericBills->count() > 0;
    }
}

if(!function_exists('queryLineExcept')) {
    function queryLineExcept($except = []) {
        $params = request()->all();
        $final = [];
        foreach ($params as $k => $v) {
            if(in_array($k, $except) === FALSE) {
                if(is_array($v)) $v = implode(',', $v);
                $final[] = "$k=" . urlencode($v);
            }
        }
        return implode('&', $final);
    }
}

if(!function_exists('sortColumnHead')) {
    function sortColumnHead($url, $label, $sortKey, $defaultDirection = 'ASC') {
        $currentSortKey = request()->input('sort');
        $currentDir = request()->input('dir');
        $targetDir = $currentDir ? ($currentDir === 'ASC' ? 'DESC' : 'ASC') : $defaultDirection;
        echo '<a href="' . $url . '?sort=' . $sortKey . '&dir=' . $targetDir . '&' . queryLineExcept(['sort', 'dir']) . '">' . $label . '</a>';
        if($currentSortKey === $sortKey) {
            if($currentDir === 'ASC') {
                echo "&nbsp;&nbsp;↑";
            }
            elseif($currentDir === 'DESC') {
                echo "&nbsp;&nbsp;↓";
            }
        }
    }
}

if(!function_exists('html2Text')) {
    function html2Text($old, $new){

    }
}

if(!function_exists('diff')) {
    function diff($old, $new){
  //      return Diff::toHTML(Diff::compare($old, $new));
    }
}

if(!function_exists('get_current_session')) {
    function get_current_session(){
        return AppSession::where('session_key', request()->cookie('sessionKey'))->first();
    }
}

if(!function_exists('get_current_date')) {
    function get_current_date($timezone = null){
        if(!$timezone){
            $timezone = 'US\Eastern';
        }
        $date = new DateTime("now", new DateTimeZone('US/Eastern') );
        return $date->format('Y-m-d');
    }
}


if(!function_exists('friendly_date_est')) {
    function friendly_date_est($value, $default = '-') {

        if(!$value || empty($value)) return $default;
        try {

            $realTimezone = resolve_timezone('EASTERN');
            $date = new DateTime($value);
            $date->setTimezone(new DateTimeZone($realTimezone));

            return $date->format("m/d/y");

        }
        catch (Exception $e) {
            return $e->getMessage();
        }
    }
}

if(!function_exists('friendly_date_est_compact')) {
    function friendly_date_est_compact($value, $default = '-') {

        if(!$value || empty($value)) return $default;
        try {

            $realTimezone = resolve_timezone('EASTERN');
            $date = new DateTime($value);
            $date->setTimezone(new DateTimeZone($realTimezone));

            return $date->format('y') === date('y') ? $date->format("m/d") : $date->format("m/d/y");

        }
        catch (Exception $e) {
            return $e->getMessage();
        }
    }
}

if(!function_exists('friendly_date_compact')) {
    function friendly_date_compact($value, $default = '-') {

        if(!$value || empty($value)) return $default;
        try {

            $date = new DateTime($value);

            return $date->format('y') === date('y') ? $date->format("m/d") : $date->format("m/d/y");

        }
        catch (Exception $e) {
            return $e->getMessage();
        }
    }
}


if(!function_exists('friendly_date_time')) {
    function friendly_date_time($value, $includeTime = true, $default = '-', $long_year=false) {
        if(!$value || empty($value)) return $default;
        try {
            if($includeTime) {
                $realTimezone = 'US/Eastern';
                $date = new DateTime($value);
                $date->setTimezone(new DateTimeZone($realTimezone));
                return $date->format("m/d/y" . ($includeTime ? ", h:ia" : "")) . ($includeTime ? ' EST' : '');
            }
            else {
                $result = strtotime($value);
                if($long_year){
                    $result = date("m/d/Y" . ($includeTime ? ", h:ia" : ""), $result);
                }else{
                    $result = date("m/d/y" . ($includeTime ? ", h:ia" : ""), $result);
                }
                return $result;
            }
        }
        catch (Exception $e) {
            return $value;
        }
    }
}

if(!function_exists('friendly_date_time_with_seconds')) {
    function friendly_date_time_with_seconds($value, $includeTime = true, $default = '-', $long_year=false) {
        if(!$value || empty($value)) return $default;
        try {
            if($includeTime) {
                $realTimezone = 'US/Eastern';
                $date = new DateTime($value);
                $date->setTimezone(new DateTimeZone($realTimezone));
                return $date->format("m/d/y" . ($includeTime ? ", h:i:sa" : "")) . ($includeTime ? ' EST' : '');
            }
            else {
                $result = strtotime($value);
                if($long_year){
                    $result = date("m/d/Y" . ($includeTime ? ", h:i:sa" : ""), $result);
                }else{
                    $result = date("m/d/y" . ($includeTime ? ", h:i:sa" : ""), $result);
                }
                return $result;
            }
        }
        catch (Exception $e) {
            return $value;
        }
    }
}

if(!function_exists('friendly_date_month_year')) {
    function friendly_date_month_year($value, $default = '-', $long_year=true) {
        if(!$value || empty($value)) return $default;
        try {
            $result = strtotime($value);
                if($long_year){
                    $result = date("m/Y", $result);
                }else{
                    $result = date("m/y", $result);
                }
                return $result;
        }
        catch (Exception $e) {
            return $value;
        }
    }
}


if(!function_exists('friendlier_date_time')) {
    function friendlier_date_time($value, $includeTime = true, $default = '-') {
        return friendly_date_time($value, $includeTime, $default);
    }
}

if(!function_exists('friendly_date_time_short')) {
    function friendly_date_time_short($value, $includeTime = true, $default = '-') {
        if(!$value || empty($value)) return $default;
        try {
            $result = strtotime($value);
            $result = date("m/d/y" . ($includeTime ? ", h:ia" : ""), $result);
            return $result;
        }
        catch (Exception $e) {
            return $value;
        }
    }
}

if(!function_exists('friendly_date_time_short_with_tz')) {
    function friendly_date_time_short_with_tz($value, $includeTime = true, $tz='UTC', $default = '-') {

        if(!$value || empty($value)) return $default;
        try {

            $realTimezone = resolve_timezone($tz);
            $date = new DateTime($value);
            $date->setTimezone(new DateTimeZone($realTimezone));

            return $date->format("m/d/y" . ($includeTime ? ", h:iA" : ""));

        }
        catch (Exception $e) {
            return $e->getMessage();
        }
    }
}

if(!function_exists('friendly_date_time_short_with_tz_from_timestamp')) {
    function friendly_date_time_short_with_tz_from_timestamp($value, $tz='UTC', $default = '-', $format = "m/d/y, h:iA") {

        if(!$value || empty($value)) return $default;
        try {

            $realTimezone = resolve_timezone($tz);
            $date = new DateTime("@$value");
            $date->setTimezone(new DateTimeZone($realTimezone));

            return $date->format($format);

        }
        catch (Exception $e) {
            return $e->getMessage();
        }
    }
}

if(!function_exists('postgres_date_time_short_with_tz')) {
    function postgres_date_time_short_with_tz($value, $includeTime = true, $tz='UTC', $default = '-') {

        if(!$value || empty($value)) return $default;
        try {

            $realTimezone = resolve_timezone($tz);
            $date = new DateTime($value);
            $date->setTimezone(new DateTimeZone($realTimezone));

            return $date->format("Y-m-d" . ($includeTime ? " h:i:s" : ""));

        }
        catch (Exception $e) {
            return $e->getMessage();
        }
    }
}

if(!function_exists('postgres_date_time_short_with_tz_from_timestamp')) {
    function postgres_date_time_short_with_tz_from_timestamp($value, $tz='UTC', $default = '-') {

        if(!$value || empty($value)) return $default;
        try {

            $realTimezone = resolve_timezone($tz);
            $date = new DateTime("@$value");
            $date->setTimezone(new DateTimeZone($realTimezone));

            return $date->format("Y-m-d h:i:s");

        }
        catch (Exception $e) {
            return $e->getMessage();
        }
    }
}

if(!function_exists('friendly_date_time_short_with_tz_from_timestamp_divide1000')) {
    function friendly_date_time_short_with_tz_from_timestamp_divide1000($value, $tz='UTC', $default = '-') {

        if(!$value || empty($value)) return $default;
        try {
            $value = (floor($value / 1000));
            $realTimezone = resolve_timezone($tz);
            $date = new DateTime("@$value");
            $date->setTimezone(new DateTimeZone($realTimezone));

            return $date->format("m/d/y, h:iA");

        }
        catch (Exception $e) {
            return $e->getMessage();
        }
    }
}

if(!function_exists('friendly_date_short_with_tz_from_timestamp_divide1000')) {
    function friendly_date_short_with_tz_from_timestamp_divide1000($value, $tz='EASTERN', $default = '-') {

        if(!$value || empty($value)) return $default;
        try {
            $value = (floor($value / 1000));
            $realTimezone = resolve_timezone($tz);
            $date = new DateTime("@$value");
            $date->setTimezone(new DateTimeZone($realTimezone));

            return $date->format("m/d/y");

        }
        catch (Exception $e) {
            return $e->getMessage();
        }
    }
}

if(!function_exists('date_short_with_tz_from_timestamp_divide1000')) {
    function date_short_with_tz_from_timestamp_divide1000($value, $tz='EASTERN', $default = '-') {

        if(!$value || empty($value)) return $default;
        try {
            $value = (floor($value / 1000));
            $realTimezone = resolve_timezone($tz);
            $date = new DateTime("@$value");
            $date->setTimezone(new DateTimeZone($realTimezone));

            return $date->format("Y-m-d");

        }
        catch (Exception $e) {
            return $e->getMessage();
        }
    }
}

if(!function_exists('friendly_date')) {
    function friendly_date($value) {
        if(!$value || empty($value)) return '';
        try {
            $result = strtotime($value);
            $result = date("m/d/Y", $result);
            return $result;
        }
        catch (Exception $e) {
            return $value;
        }
    }
}

if(!function_exists('friendly_date_short')) {
    function friendly_date_short($value) {
        if(!$value || empty($value)) return '';
        try {
            $result = strtotime($value);
            $result = date("m/d/y", $result);
            return $result;
        }
        catch (Exception $e) {
            return $value;
        }
    }
}

if(!function_exists('friendly_date_month_year')) {
    function friendly_date_month_year($value) {
        if(!$value || empty($value)) return '';
        try {
            $result = strtotime($value);
            $result = date("M Y", $result);
            return $result;
        }
        catch (Exception $e) {
            return $value;
        }
    }
}

if(!function_exists('friendlier_date')) {
    function friendlier_date($value) {
        if(!$value || empty($value)) return '';
        try {
            $result = strtotime($value);
            $result = date("m/d/Y", $result);
            return $result;
        }
        catch (Exception $e) {
            return $value;
        }
    }
}

if(!function_exists('relative_friendly_date')) {
    function relative_friendly_date($value) {
        if(!$value || empty($value)) return '';
        try {
            $result = date_diff(date_create($value), date_create('now'))->days;
            if ($result > 30) $result = date('F Y', strtotime($value));
            else if ($result > 1) $result .= ' days ago';
            else if ($result === 1) $result = 'Yesterday';
            else if ($result === 0) $result = 'Today';
            return $result;
        }
        catch (Exception $e) {
            return $value;
        }
    }
}

if(!function_exists('unfriendly_date')) {
    function unfriendly_date($value) {
        if(!$value || empty($value)) return '';
        try {
            $result = strtotime($value);
            $result = date("Y-m-d", $result);
            return $result;
        }
        catch (Exception $e) {
            return $value;
        }
    }
}

if(!function_exists('friendly_time')) {
    function friendly_time($value, $default = '-') {
        if(!$value || empty($value)) return $default;
        try {
            $result = strtotime($value);
            $result = date("h:i a", $result);
            return $result;
        }
        catch (Exception $e) {
            return $value;
        }
    }
}

if(!function_exists('military_time')) {
    function military_time($value,  $tz='UTC', $default = '-') {

        if(!$value || empty($value)) return $default;
        try {
            $realTimezone = resolve_timezone($tz);
            $date = new DateTime($value);
            $date->setTimezone(new DateTimeZone($realTimezone));
            return $date->format("H:i");
        }
        catch (Exception $e) {
            return $value;
        }
    }
}

if(!function_exists('resolve_timezone')) {
    function resolve_timezone($value) {
        try {
            switch ($value) {
                case 'ALASKA': {
                    return 'US/Alaska';
                }
                case 'CENTRAL': {
                    return 'US/Central';
                }
                case 'EASTERN': {
                    return 'US/Eastern';
                }
                case 'HAWAII': {
                    return 'US/Hawaii';
                }
                case 'MOUNTAIN': {
                    return 'US/Mountain';
                }
                case 'PACIFIC': {
                    return 'US/Pacific';
                }
                case 'PUERTO_RICO': {
                    return 'America/Puerto_Rico';
                }
                case 'UTC': {
                    return 'UTC';
                }
                }
        }
        catch (Exception $e) {
            return $value;
        }
    }
}

// $date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
// echo $date->format('Y-m-d H:i:sP') . "\n";

if(!function_exists('friendly_month')) {
    function friendly_month($value) {
        if(!$value || empty($value)) return "-";
        try {
            $result = strtotime($value);
            $result = date("F o", $result);
            return $result;
        }
        catch (Exception $e) {
            return $value;
        }
    }
}

if(!function_exists('friendly_month_short')) {
    function friendly_month_short($value) {
        if(!$value || empty($value)) return "-";
        try {
            $result = strtotime($value);
            $result = date("M y", $result);
            return $result;
        }
        catch (Exception $e) {
            return $value;
        }
    }
}

if(!function_exists('day_part_from_date')) {
    function day_part_from_date($value) {
        if(!$value || empty($value)) return "-";
        try {
            $result = strtotime($value);
            $result = date("d", $result);
            return $result;
        }
        catch (Exception $e) {
            return $value;
        }
    }
}

if(!function_exists('month_part_from_date')) {
    function month_part_from_date($value) {
        if(!$value || empty($value)) return "-";
        try {
            $result = strtotime($value);
            $result = date("m", $result);
            return $result;
        }
        catch (Exception $e) {
            return $value;
        }
    }
}

if(!function_exists('year_part_from_date')) {
    function year_part_from_date($value) {
        if(!$value || empty($value)) return "-";
        try {
            $result = strtotime($value);
            $result = date("Y", $result);
            return $result;
        }
        catch (Exception $e) {
            return $value;
        }
    }
}

if(!function_exists('friendly_money')){
    function friendly_money($value, $decimals = 2) {
        // if($decimals === 0) return intval($value);
        return number_format((float)$value, $decimals, '.', '');
    }
}

if(!function_exists('time_in_hrminsec')) {
    function time_in_hrminsec($value, $default = '-') {
        if(!$value || empty($value)) return $default;
        $value = intval($value);
        $minutes = intval($value / 60);
        $seconds = $value % 60;
        $hours = 0;
        if($minutes >= 60) {
            $hours = intval($minutes / 60);
            $minutes = $minutes % 60;
        }
        $output = [];
        if($hours > 0) {
            $output[] = "{$hours}h";
        }
        if($minutes > 0) {
            $output[] = "{$minutes}m";
        }
        if($seconds > 0) {
            $output[] = "{$seconds}s";
        }
        return implode(" ", $output);
    }
}

if(!function_exists('sanitize_field_name')) {
    function sanitize_field_name($name) {
        $result = strtolower($name);
        return preg_replace("/[^0-9a-z]/i", "_", $result);
    }
}

if(!function_exists('sanitize_state_name')) {
    function sanitize_state_name($name) {
        $result = strtolower($name);
        return ucwords(preg_replace("/_/i", " ", $result));
    }
}

if(!function_exists('renderNoteTemplate')) {
    function renderNoteTemplate($template, $topLevel)
    {
        echo
            '<div class="note-template-item" ' .
            'template="' . (isset($template->template) ? $template->template : $template->text) . '" ' .
            'type="' . (isset($template->type) ? $template->type : "value") . '" ' .
            '>' .
            '<div class="note-template-text d-flex align-items-center">' .
            '<span class="label">' .
            '<input type="checkbox" />' .
            '<span>' . $template->text . '</span>' .
            '</span>';
        if (isset($template->type) && $template->type === 'plus-minus') {
            echo '<div class="ml-auto mr-2 text-nowrap">';
            echo '<a href="#" class="plus-trigger"><i class="fa fa-plus-circle"></i></a>';
            echo '<a href="#" class="minus-trigger ml-1"><i class="fa fa-minus-circle"></i></a>';
            echo '</div>';
        }
        echo '</div>';
        if (isset($template->children) && count($template->children)) {
            echo '<i class="fa fa-chevron-right has-children"></i>';
            echo '<div class="note-template-children">';
            foreach ($template->children as $t) {
                renderNoteTemplate($t, false);
            }
            echo '</div>';
        } else if (isset($template->type) && $template->type !== 'plus-minus') {
            echo '<i class="fa fa-chevron-right has-children"></i>';
            echo '<div class="note-template-children">';
            if ($template->type === 'alpha') {
                echo '<textarea class="form-control form-control-sm"></textarea>';
            } else {
                echo '<input type="' . $template->type . '" class="form-control form-control-sm">';
            }
            echo '</div>';
        }
        echo '</div>';
    }
}

if(!function_exists('renderNoteTemplates')) {
    function renderNoteTemplates($path)
    {
        $templates = json_decode(file_get_contents($path));
        foreach ($templates->templates as $template) {
            renderNoteTemplate($template, true);
        }
    }
}

if(!function_exists('renderNoteExamTemplates')) {
    function renderNoteExamTemplates($parentPath, $childPath)
    {
        $templates = json_decode(file_get_contents($parentPath));
        $templates = $templates->templates;

        // override as needed with what is in template set
        if(file_exists($childPath)) {
            $orTemplates = json_decode(file_get_contents($parentPath));
            $orTemplates = $orTemplates->templates;
            for ($i = 0; $i < count($templates); $i++) {
                for ($j = 0; $j < count($orTemplates); $j++) {
                    if($templates[$i]->text === $orTemplates[$j]->text) {
                        $templates[$i] = $orTemplates[$j];
                    }
                }
            }
        }

        foreach ($templates as $template) {
            renderNoteTemplate($template, true);
        }
    }
}

if(!function_exists('getVal')) {
    function getVal($object, $prop)
    {
        if (isset($object->$prop)) {
            return $object->$prop;
        } else {
            return '';
        }
    }
}

if(!function_exists('appTZtoPHPTZ')) {
    function appTZtoPHPTZ($_timezone)
    {
        switch ($_timezone) {
            case 'ALASKA':
                $timezone = "US/Alaska";
                break;
            case 'CENTRAL':
                $timezone = "US/Central";
                break;
            case 'HAWAII':
                $timezone = "US/Hawaii";
                break;
            case 'MOUNTAIN':
                $timezone = "US/Mountain";
                break;
            case 'PACIFIC':
                $timezone = "US/Pacific";
                break;
            case 'PUERTO_RICO':
                $timezone = "America/Puerto_Rico";
                break;
            default:
                $timezone = "US/Eastern";
                break;
        }
        return $timezone;
    }
}

if(!function_exists('convertToTimezone')) {
    function convertToTimezone($_dateTime, $_targetTimezone, $_sourceTimezone = 'UTC', $_returnRaw = false)
    {
        if (!$_dateTime) return $_dateTime;
        $date = new \DateTime($_dateTime, new \DateTimeZone($_sourceTimezone));
        $date->setTimezone(new \DateTimeZone(appTZtoPHPTZ($_targetTimezone)));
        return $_returnRaw ? $date : $date->format('Y-m-d H:i:s');
    }
}

if(!function_exists('minutes_to_hhmm')) {
    function minutes_to_hhmm($_minutes)
    {
        $h = intval(floor($_minutes / 60));
        $m = $_minutes;
        if($h > 0) {
            $m = $_minutes - $h * 60;
        }
        $h = ($h < 10 ? '0' : '') . $h;
        $m = ($m < 10 ? '0' : '') . $m;
        return $h . ':' . $m;
    }
}
if(!function_exists('vsValue')) {
    function vsValue($_v, $patient = null, $_direct = false)
    {
        if ($_direct) {
            return $_v ? $_v : '<span class="font-weight-normal text-info font-italic">empty</span>';
        }
        return @($patient->{$_v}) ? $patient->{$_v} : '<span class="font-weight-normal text-info font-italic">empty</span>';
    }
}
if(!function_exists('vsElement')) {
    function vsElement($_v, $type, $name, $patient, $class = '')
    {
        return '<input type="' . $type . '" class="form-control form-control-sm min-width-unset rounded-0 ' . $class . '" ' .
            'name="' . $name . '" ' .
            'value="' . (@($patient->{$_v}) ? $patient->{$_v} : '') . '">';
    }
}

if(!function_exists('vsRoElement')) {
    function vsRoElement($_v, $type, $name, $patient, $class = '')
    {
        return '<input type="' . $type . '" readonly class="form-control form-control-sm min-width-unset rounded-0 ' . $class . '" ' .
            'name="' . $name . '" ' .
            'value="' . (@($patient->{$_v}) ? $patient->{$_v} : '') . '">';
    }
}

if(!function_exists('str_compact')) {
    function str_compact($_str)
    {
        return preg_replace("/[^a-zA-Z0-9]/", "", strip_tags($_str));
    }
}

if(!function_exists('noteMethodDisplay')) {
    function noteMethodDisplay($method)
    {
        if($method === 'IN_CLINIC') return 'In-Clinic';
        $method = str_replace('_', ' ', $method);
        return ucwords(strtolower($method));
    }
}

if(!function_exists('friendly_timezone')) {
    function friendly_timezone($tz) {
        $map = [
            'EASTERN' => 'EST',
            'CENTRAL' => 'CST',
            'MOUNTAIN' => 'MST',
            'PACIFIC' => 'PST',
            'ALASKA' => 'AST',
            'HAWAII' => 'HST',
            'PUERTO_RICO' => 'PR'
        ];
        return $map[$tz] ?? str_replace("_", " ", $tz);
    }
}

if(!function_exists('segment_template_summary_value_display')) {
    function segment_template_summary_value_display($value, $default='________', $class = '') {
        if($value && strlen($value)) return '<span class="segment-template-summary-value '.$class.'">' . $value . '</span>';
        return $default;
    }
}
if(!function_exists('starts_with')) {
    function starts_with($haystack, $needle) {
        $length = strlen($needle);
    return substr($haystack, 0, $length) === $needle;
    }
}

if(!function_exists('get_doc_templates')){
    function get_doc_templates(){
        $basePath = 'views/document-templates-generic';
        $dir = opendir(resource_path($basePath));
        $templates = [];
        if($dir) {
            while ( $entry = readdir($dir) ) {
                if($entry !== '.' && $entry !== '..' && is_dir(resource_path($basePath . '/' . $entry))) {
                    $spec = json_decode(file_get_contents(resource_path($basePath . '/' . $entry) . '/spec.json'));
                    if(isset($spec->active) && $spec->active) {

                        $html = file_get_contents(resource_path($basePath . '/' . $entry) . '/content.blade.php');

                        // get fields
                        $proVariables = [];
                        $htmlDisplay = preg_replace_callback(
                            '/{([^}]+)}/',
                            function ($match) use (&$proVariables) {
                                $token = $match[1];
                                $replacement = '';
                                if(strpos($token, '.') === FALSE) {
                                    $adminField = false;
                                    if($token[0] === '@') {
                                        // $token = substr($token, 1);
                                        $adminField = true;
                                    }
                                    switch ($token) {
                                        case 'TODAY':
                                            $replacement = date('m/d/Y');
                                            break;
                                        default:
                                            $replacement = '<span class="text-info document-variable" data-variable="' . $token . '">' .
                                                ($token[0] === '@' ? substr($token, 1) : $token) .
                                                '</span>';
                                            if (!isset($proVariables[$token])) {
                                                $proVariables[$token] = [
                                                    'token' => $token,
                                                    'adminField' => $adminField
                                                ];
                                            }
                                            break;
                                    }
                                }
                                return $replacement;
                            },
                            $html
                        );


                        $templates[] = [
                            "name" => $entry,
                            "title" => $spec->title,
                            "html" => $html,
                            "htmlDisplay" => $htmlDisplay,
                            "proVariables" => $proVariables
                        ];
                    }
                }
            }
        }
        closedir($dir);

        // sort by document name
        $names = array_column($templates, 'title');
        array_multisort($names, SORT_ASC, $templates);

        return $templates;
    }
}
if(!function_exists('format_phone_number')) {
    function format_phone_number($number, $default = '-') {
        if(empty($number)) return $default;
        return preg_replace('~.*(\d{3})[^\d]{0,7}(\d{3})[^\d]{0,7}(\d{4}).*~', '($1) $2-$3', $number). "\n";
    }
}

if(!function_exists('format_number')) {
    function format_number($number, $places = 2) {
        return number_format((float)$number, $places, '.', '');
    }
}

if(!function_exists('toHumanReadable')) {
    function toHumanReadable($name) {
        return ucwords(preg_replace("/[^0-9a-z]/i", " ", $name));
    }
}
if(!function_exists('parseRender')) {
    function parseRender($_data) {
        if($_data) {
            $type = gettype($_data);
            if(is_string($_data) || is_numeric($_data)) {
                echo $_data;
            }
            else {
                echo "<table class='table table-sm border w-100'>";
                foreach($_data as $k => $v) {
                    echo "<tr>";
                    echo "<td><b class='text-secondary'>" . toHumanReadable($k) . "</b></td>";
                    echo "<td>";
                    if(is_object($v)) {
                        parseRender($v);
                    }
                    elseif(is_array($v)) {
                        foreach($v as $k2 => $v2) {
                            parseRender($v2);
                        }
                    }
                    else {
                        echo $v;
                    }
                    echo "</td>";
                    echo "</tr>";
                }
                echo "</table>";
            }
        }
    }
}

if(!function_exists('mask_string')) {
    function mask_string($string, $mask = "*", $lengthFromLastCharacter = null) {
        if(!$lengthFromLastCharacter){
        return str_repeat($mask, strlen($string));
        }
        $firstCharacters = substr($string, ($lengthFromLastCharacter));
        $lastCharacters = substr($string, -$lengthFromLastCharacter);

        $maskedFirstCharacters = str_repeat($mask, strlen($firstCharacters));

        return $maskedFirstCharacters . $lastCharacters;
    }
}

if(!function_exists('limit_string_length')) {
    function limit_string_length($string, $length = 30) {
        return substr($string,0, $length);
    }
}

if(!function_exists('get_custom_problems')) {
    function get_custom_problems() {
        $customProblems = [
            [
                'sub_text' => "G47. 33",
                'text' => "Sleep Apnea"
            ]
        ] ;

        return $customProblems;
    }
}

if(!function_exists('camel_case')) {
    function camel_case($string, $dontStrip = []) {
        return lcfirst(str_replace(' ', '', ucwords(preg_replace('/[^a-z0-9'.implode('',$dontStrip).']+/', ' ',$string))));
    }
}

if(!function_exists('getDefaultCompanyClientUidSession')) {
    function getDefaultCompanyClientUidSession($patientID) {
        return session()->get('DEFAULT_COMPANY_CLIENT_UID_'.$patientID);
    }
}