<?php

namespace App\CustomClass;

use App\Models\ClientRole;
use App\Models\Leave;
use App\Models\UserWiseExchange;
use App\Models\UserWiseLeave;
use Illuminate\Support\Facades\Auth;
use App\User;
use Carbon\Carbon;
use DateTime;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\URL;
use Route;
use App\Models\Role;

class Helper
{
    public static function dateFormat($date)
    {
        return date("Y-m-d h:i:s A", strtotime($date));
    }

    public static function onlyDMY($date)
    {
        return date("d-m-Y", strtotime($date));
    }

    public static function onlyMY($date)
    {
        return date("F Y", strtotime($date));
    }

    public static function onlyMonth($date)
    {
        return date("F", strtotime($date));
    }

    public static function formatYmd($date)
    {
        $convert = str_replace('/', '-', $date);
        return date('Y-m-d', strtotime($convert));
    }

    public static function sqlYMD($date)
    {
        return date('Y-m-d', strtotime($date));
    }

    public static function carbonFormat($date)
    {
        //$convert = str_replace('/', '-', $date);
        $convertToCarbon = date('Y-m-d', strtotime($date));
        return Carbon::CreateFromFormat('Y-m-d', $convertToCarbon);
    }

    public static function stringDate($date)
    {
        return date("d M Y", strtotime($date));
    }

    //only time
    public static function onlyTime($date)
    {
        return date("h:i A", strtotime($date));
    }

    public static function dateTime()
    {
        return date('Y-m-d H:i:s');
    }

    /**
     * @param $date
     * @param $number : number of sequence of week
     * @return date
     */
    public static function getFirstWeekDay($date, $number)
    {
// parse about any English textual datetime description into a Unix timestamp
        $ts = strtotime($date);
// find the year (ISO-8601 year number) and the current week
        $year = date('o', $ts);
        $week = date('W', $ts);
// print week for the current date
        $ts = strtotime($year . 'W' . $week . $number);
        return date("Y-m-d", $ts);
    }

    public static function convertNumericArray($obj, $key)
    {
        $newArray = [];
        foreach ($obj as $value) {
            $value = $value->$key;
            $newArray[] = $value;
        }
        return $newArray;

    }

    public static function getClientIp()
    {
        $ipaddress = '';
        if (getenv('HTTP_CLIENT_IP'))
            $ipaddress = getenv('HTTP_CLIENT_IP');
        else if (getenv('HTTP_X_FORWARDED_FOR'))
            $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
        else if (getenv('HTTP_X_FORWARDED'))
            $ipaddress = getenv('HTTP_X_FORWARDED');
        else if (getenv('HTTP_FORWARDED_FOR'))
            $ipaddress = getenv('HTTP_FORWARDED_FOR');
        else if (getenv('HTTP_FORWARDED'))
            $ipaddress = getenv('HTTP_FORWARDED');
        else if (getenv('REMOTE_ADDR'))
            $ipaddress = getenv('REMOTE_ADDR');
        else
            $ipaddress = 'UNKNOWN';
        return $ipaddress;
    }

    public static function createDateRangeArray($strDateFrom, $strDateTo)
    {
        // takes two dates formatted as YYYY-MM-DD and creates an
        // inclusive array of the dates between the from and to dates.

        // could test validity of dates here but I'm already doing
        // that in the main script

        $aryRange = array();

        $iDateFrom = mktime(1, 0, 0, substr($strDateFrom, 5, 2), substr($strDateFrom, 8, 2), substr($strDateFrom, 0, 4));
        $iDateTo = mktime(1, 0, 0, substr($strDateTo, 5, 2), substr($strDateTo, 8, 2), substr($strDateTo, 0, 4));

        if ($iDateTo >= $iDateFrom) {
            array_push($aryRange, date('Y-m-d', $iDateFrom)); // first entry
            while ($iDateFrom < $iDateTo) {
                $iDateFrom += 86400; // add 24 hours
                array_push($aryRange, date('Y-m-d', $iDateFrom));
            }
        }
        return $aryRange;
    }

    public static function timeSummation($times)
    {
        $seconds = 0;

        foreach ($times as $time) {
            list($g, $i, $s) = explode(':', $time);
            $seconds += $g * 3600;
            $seconds += $i * 60;
            $seconds += $s;
        }

        $hours = floor($seconds / 3600);
        $seconds -= $hours * 3600;
        $minutes = floor($seconds / 60);
        $seconds -= $minutes * 60;
        if ($hours < 10) {
            $hours = '0' . $hours;
        }
        if ($minutes < 10) {
            $minutes = '0' . $minutes;
        }
        if ($seconds < 10) {
            $seconds = '0' . $seconds;
        }
        return "{$hours}:{$minutes}:{$seconds}";
    }

    public static function timezoneCheck($timezoneId)
    { #$timezoneId= Asia/Dhaka
        $zoneList = timezone_identifiers_list(); # list of (all) valid timezones
        return in_array($timezoneId, $zoneList); # set result
    }

    public static function get_domain($url)
    {
        $urlobj = parse_url($url);
        $domain = $urlobj['host'];
        if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
            return $regs['domain'];
        }
        return false;
    }

    public static function route($routeName)
    {
        $username = Auth::user()->client->username;
        return URL::route($routeName, $username);
    }

    public static function nav()
    {
        $userId = Auth::id();
        //echo "<pre>";
        $allKeys = [];
        $final = [];
        if (Auth::user()->user_type == '1') {
            $system = DB::table('system_roles')->where('id', 1)->first(); //admin
            $decodedMenu = json_decode($system->menus, true);
            if (!empty($decodedMenu)) {
                foreach ($decodedMenu as $key => $sub) {
                    if (is_array($sub)) {
                        foreach ($sub as $subMenu) {
                            $explode = explode("#", $subMenu);
                            $subMenuName = $explode[0];
                            $subMenuUrl = $explode[1];
                            $final[$key][$subMenuName] = $subMenuUrl;
                        }
                    } else {
                        $final[$key] = null;
                    }
                }
            }
            return $final;
        }

        $user = User::with('roles')->find($userId);
        foreach ($user->roles as $role) {
            $decodedMenu = json_decode($role->menus, true);
            if (!empty($decodedMenu)) {
                foreach (array_keys($decodedMenu) as $keys) {
                    $allKeys[] = $keys;
                }
            }

        }
        $allKeys = array_unique($allKeys);
        foreach ($allKeys as $mainMenu) {
            foreach ($user->roles as $role) {
                $decodedMenu = json_decode($role->menus, true);
                if (!empty($decodedMenu)) {
                    foreach ($decodedMenu as $key => $sub) {
                        if ($mainMenu == $key) {
                            if (is_array($sub)) {
                                foreach ($sub as $subMenu) {
                                    $explode = explode("#", $subMenu);
                                    $subMenuName = $explode[0];
                                    $subMenuUrl = $explode[1];
                                    $final[$mainMenu][$subMenuName] = $subMenuUrl;
                                }
                            } else {
                                $final[$mainMenu] = null;
                            }

                        }

                    }
                }
            }
        }
        return $final;
    }

    public static function hasPermit($route)
    {
        $found = 0;
        $user = User::with('roles')->find(Auth::id());
        foreach ($user->roles as $role) {
            $decodedRoutes = json_decode($role->routes, true);
            if (!empty($decodedRoutes)) {
                foreach ($decodedRoutes as $val) {
                    if ($val == $route) {
                        $found = 1;
                        break;
                    }
                }
            }
        }
        if ($found == 1) {
            return true;
        } else {
            return false;
        }
    }

    public static function notification()
    {
        $notify = [];
        if (self::hasPermit('leave-manage')) {
            $userWIseLeave = UserWiseLeave::where('status', 0)->where('client_id', Auth::user()->client_id)->groupBy('user_id')->count();
            $userWIseExchange = UserWiseExchange::where('status', 0)->where('client_id', Auth::user()->client_id)->groupBy('user_id')->count();
            if ($userWIseLeave > 0) {
                $notify[] = [
                    'text' => "$userWIseLeave Leave approval pending",
                    'url' => url('leave-manage'),
                ];
            }
            if ($userWIseExchange > 0) {
                $notify[] = [
                    'text' => "$userWIseExchange Exchange approval pending",
                    'url' => url('leave-manage'),
                ];
            }
        }
        if (self::hasPermit('user-leave')) {
            $userWIseLeave = UserWiseLeave::where('viewed', 0)->where('status', '!=', 0)->where('client_id', Auth::user()->client_id)->where('user_id', Auth::id())->groupBy('user_id')->count();
            $userWIseExchange = UserWiseExchange::where('viewed', 0)->where('status', '!=', 0)->where('client_id', Auth::user()->client_id)->where('user_id', Auth::id())->groupBy('user_id')->count();
            if ($userWIseLeave > 0) {
                $notify[] = [
                    'text' => "$userWIseLeave Leave approved/denied",
                    'url' => url('user-leave'),
                ];
            }
            if ($userWIseExchange > 0) {
                $notify[] = [
                    'text' => "$userWIseExchange Leave exchange approved/denied",
                    'url' => url('exchange'),
                ];
            }
        }
        if (count($notify) > 0) {
            return $notify;
        } else {
            return [];
        }
    }

    public static function secondsToTime($seconds)
    {
        $hours = floor($seconds / 3600);
        $seconds -= $hours * 3600;
        $minutes = floor($seconds / 60);
        $seconds -= $minutes * 60;

        $hours = ($hours < 9) ? '0' . $hours : $hours;
        $minutes = ($minutes < 9) ? '0' . $minutes : $minutes;
        $seconds = ($seconds < 9) ? '0' . $seconds : $seconds;
        return "$hours:$minutes:$seconds";
    }

    public static function timeToSecond($time)
    {
        $parsed = date_parse($time);
        return $seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];
    }

    public static function testRange($start_time1, $end_time1, $start_time2, $end_time2)
    {
        /*
         * Start/End Time1: your given TIME
         * Start/End Time2: Your comparision time
         * Return false If Overlap found
         * Return True if No overlap
         * Note: If u need exact overlap 7:00 to 7:59 8:00 to 8:59 like this , just remove =(equal) from condition
        */

        if (($end_time1 <= $start_time2)) {
            return true;
        } else if (($start_time1 >= $start_time2) && ($start_time1 >= $end_time2)) {
            return true;
        } else {
            return false;
        }

    }

    public static function pendingLeaveNotify()
    {
        // return Leave::where('status',0)->count();
    }

    public static function empLeaveNotify()
    {
        //return Leave::where('status','!=',0)->where('fk_user_id',Auth::id())->where('viewed',0)->count();
    }

    public static function urlGroupCheck($id, $input)
    {
        $found = 0;
        $length = count($input);
        $mergedRoute = [];
        $role = ClientRole::where('id', $id)->where('client_id', Auth::user()->client_id)->first();
        if ($role) {
            $decodedRoutes = json_decode($role->routes, true);
            if (!empty($decodedRoutes)) {
                foreach ($decodedRoutes as $val) {
                    $mergedRoute[] = $val;
                }
            }

        }
        if (count($mergedRoute) > 0) {
            $mergedRoute = array_unique($mergedRoute);
            foreach ($input as $route) {
                if (in_array($route, $mergedRoute)) {
                    ++$found;
                }
            }
        }
        if ($found == $length) {
            return true;
        } else {
            return false;
        }
    }

}