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

use App\Models\AppSession;

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

if(!function_exists('friendly_date_time')) {
    function friendly_date_time($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')) {
    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 = '-') {

        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, h:iA");

        }
        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')) {
    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('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("M o", $result);
            return $result;
        }
        catch (Exception $e) {
            return $value;
        }
    }
}

if(!function_exists('friendly_money')){
    function friendly_money($value){
        return number_format((float)$value, 2, '.', '');
    }
}

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('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;
    }
}
