<?php

namespace App\View\Helper;

use App\Common\PDFLetters;
use App\Common\Permission;
use App\Utility\Common;
use Cake\View\Helper;
use Cake\View\StringTemplateTrait;

class CommonHelper extends Helper {

    function get_url($url) {
        return $url;
    }

    function humanTiming($time) {
        $time = time() - $time; // to get the time since that moment
        $tokens = array(
            31536000 => 'year',
            2592000 => 'month',
            604800 => 'week',
            86400 => 'day',
            3600 => 'hour',
            60 => 'minute',
            1 => 'second'
        );

        foreach ($tokens as $unit => $text) {
            if ($time < $unit)
                continue;
            $numberOfUnits = floor($time / $unit);
            return $numberOfUnits . ' ' . $text . (($numberOfUnits > 1) ? 's' : '');
        }
    }

    // function to get file preview url based on file type
    function getPreviewUrl($file_type) {
        echo $file_type;
    }

    function getConvertedDate($datetime) {
        if (!empty($datetime)) {
            $datetime = date('Y-m-d H:i:s', strtotime($datetime) - 60 * 60 * 4);
        }
        return $datetime;
    }
    
    
    function splitString($string,$limit = 100){
        $small = "";
        if(!empty($string)){
            $small = substr($string, 0, $limit);
            if(!empty($small) && strlen($string) > $limit){
                $small .= "...";
            }
        }
        return $small;
    }
    
    public function setdateFormat($date, $format = "F d,Y"){
        $result = "";
        if(!empty($date)){
            $result = date($format,strtotime($date));
        }
       
        return $result;
    }
    
    
    public function rtglettersFormatedPersonalinfo($personal_info_decode){
        return PDFLetters::preparePersonalInfo($personal_info_decode);
    }
    
    
    public function isReminderModificationAllow($reminders) {
        $result = false;
        $aribitary_reminders = json_decode(json_encode($reminders),true);
        //user_type = 1 = member, 2 = Affiliate, 3 = employee, 4 = employee affiliate
        $user_type = $aribitary_reminders['user_type'];
        $created_by = $aribitary_reminders['created_by'];

        if($_SESSION['userType'] == CMS_USER_INDICATOR){
            $result = true;
        }else if(
                (
                $user_type == 3
                && $_SESSION['userType'] == CRM_USER_INDICATOR
                && $_SESSION['Auth']['User']['type'] == 1
                && $_SESSION['Auth']['User']['user_id'] == $created_by
                )
                || $_SESSION['Auth']['User']['is_show_all_clients'] == 1
            )
        {
            $result = true;
        }

        return $result;
    }
    
    
    public function reminderDateFormate($date){
        $format = "h:i A m/d/Y";
        return $this->golbal_date_format($date,$format);
    }
    
    
    public function golbal_date_format($date,$format){ // 
        $result = "";
        if(!empty($date)){
           $result = date($format, strtotime($date));
        }
        return $result;
    }

    public function getDFInfo() {
        
       $df_content = file_get_contents(WWW_ROOT."df.json");
       $df_content = json_decode($df_content,true);
        usort($df_content, function($a, $b){
            $a = $a['name'];
            $b = $b['name'];

            if ($a == $b) return 0;
            return ($a < $b) ? -1 : 1;
        });
        return $df_content;
    }
    
    
    public function employeeHasPermission($array, $key, $val) {
        foreach($array as $item)
        if (isset($item[$key]) && $item[$key] == $val)
            return true;
        return false;
    }

    public function getCurrentUserType(){
        $common = new \App\Utility\Common;
        return $common->getCurrentUserInfo();
    }
    
    public function getCurrentUserInfo(){
        $user_type_name = $this->getCurrentUserType();
        
        $result['type'] = $user_type_name;
        $result['name'] = $_SESSION['Auth']['User']['email'];
        $result['member_email'] = $_SESSION['Auth']['User']['member_email'];
        
//        if($user_type_name == "MEMBER"){
//            $result['name'] = $_SESSION['Auth']['User']['email'];
//        }
        
        return $result;
    }
    
    public function setMeByUserType($user_type_info,$user_type,$employee_list,$created_by_id){
        $result = "";
        if($user_type_info['type'] == "MEMBER"){
            if($user_type == 1){
                $result = $user_type_info['name']." (Me)";
            }else {
                $result = $employee_list[$created_by_id];
            }
        }else if($user_type_info['type'] == "EMPLOYEE"){
            if($user_type == 1){
                $result = $user_type_info['member_email'];
            }else {
                $result = $user_type_info['name']." (Me)";
            }   
        }
        
       
        return $result;
    }


public function get_time_ago($current_time, $created_time,$extra_string = "")
{
    $date = date_create($created_time);
    $created_time  = date_format($date,"Y-m-d H:i:s");
    $time_difference = strtotime($current_time) - strtotime($created_time);

    if( $time_difference < 1 ) { return 'just now'; }
    $condition = array( 12 * 30 * 24 * 60 * 60 =>  'year',
                30 * 24 * 60 * 60       =>  'month',
                24 * 60 * 60            =>  'day',
                60 * 60                 =>  'hour',
                60                      =>  'minute',
                1                       =>  'second'
    );

    foreach( $condition as $secs => $str )
    {
        if( $secs == 1 ){
            return 'just now';
        }
        $d = $time_difference / $secs;

        if( $d >= 1 )
        {
            $t = round( $d );
            return  $t . ' ' . $str . ( $t > 1 ? 's' : '' ) . ' ago';
        }
    }
}

public function getDateByTimeZone($date_time, $time_zone, $format = ''){
    
    $date = new \DateTime($date_time, new \DateTimeZone('UTC'));
    if(!empty($time_zone)){
        $date->setTimezone(new \DateTimeZone($time_zone));
    }
    
    if(empty($format)){
        $format = 'Y-m-d H:i A';
    }
    return  $date->format($format);
}


public function setBackLink(){
    $result = "";
    $first_part = strtolower(APP_SERVER_HOST_URL."client/");
    $referer_part = strtolower($_SERVER['HTTP_REFERER']);
    if(!empty($first_part) && !empty($referer_part)){
        $exploded = explode("/",str_replace($first_part,"",$referer_part));
        if(is_array($exploded) && current($exploded) == "clientdashboard"){
            $result = $referer_part;
        }
    }
    
    return $result;
}

    public function isPermitted($controller_id = 0){
            return Permission::isPermitted($controller_id);
    }

    public function isEmployeeSidebarMaxWidth(){
        $result = false;
        if($_SESSION['crm_has_velocity'] == 1
            || $_SESSION['has_super_rtg_user'] == 1
            || $_SESSION['Auth']['User']['has_analysis_analyzer'] == 1
            || $_SESSION['hasEpicVelocity']
        ){
            $result = true;
        }
        return $result;
    }

    public function isEmployeeAsAdmin(){
        return Permission::isEmployeeAsAdmin();
    }


    public function daysBetweenDate($from_date, $to_date){
        return Common::daysBetweenDate($from_date, $to_date);
    }

    public function getRowClassForPdfLetters($from_date, $to_date, $download_count){
        if($download_count > 0){
            return "#3386FF";
        }
        return PDFLetters::getRowsClass($from_date, $to_date);
    }

}


?>
