<?php

 use Illuminate\Database\Eloquent\Model;
 use App\Models\Permission;
 use App\Models\Admin;
 use App\Models\User;
 use App\Models\MailSetting;
 use App\Models\EmailSetting;
 use App\Models\EmailSent;
 use App\Models\tbl_sms_settings;
 use App\Models\tbl_sms_api;
 use App\Models\Role;
 use App\Models\SmsSent;
 use App\Models\EmailTemplate;
 use App\Models\EventType;
 use App\Models\Recharge;
 use Pusher\Pusher;
 use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

//  use Mail;
 use App\Mail\InvoiceEmailManager;
    // define( TIMEBEFORE_NOW,         'now' );
    // define( TIMEBEFORE_MINUTE,      '{num} minute ago' );
    // define( TIMEBEFORE_MINUTES,     '{num} minutes ago' );
    // define( TIMEBEFORE_HOUR,        '{num} hour ago' );
    // define( TIMEBEFORE_HOURS,       '{num} hours ago' );
    // define( TIMEBEFORE_YESTERDAY,   'yesterday' );
    // define( TIMEBEFORE_FORMAT,      '%e %b' );
    // define( TIMEBEFORE_FORMAT_YEAR, '%e %b, %Y' );

    //  use DateTime;
    /**
     * Returns a test function
     *
     * */
    if (!function_exists('sayHello')) {
    
        function sayHello()
        {
            // var_dump(session()->get('cbc_crm_data'));
            echo 'say hello';
    
        }
    }

    // function time_ago( $time )
    // {
    //     $out    = ''; // what we will print out
    //     $now    = time(); // current time
    //     $diff   = $now - $time; // difference between the current and the provided dates

    //     if( $diff < 60 ) // it happened now
    //         return TIMEBEFORE_NOW;

    //     elseif( $diff < 3600 ) // it happened X minutes ago
    //         return str_replace( '{num}', ( $out = round( $diff / 60 ) ), $out == 1 ? TIMEBEFORE_MINUTE : TIMEBEFORE_MINUTES );

    //     elseif( $diff < 3600 * 24 ) // it happened X hours ago
    //         return str_replace( '{num}', ( $out = round( $diff / 3600 ) ), $out == 1 ? TIMEBEFORE_HOUR : TIMEBEFORE_HOURS );

    //     elseif( $diff < 3600 * 24 * 2 ) // it happened yesterday
    //         return TIMEBEFORE_YESTERDAY;

    //     else // falling back on a usual date format as it happened later than yesterday
    //         return strftime( date( 'Y', $time ) == date( 'Y' ) ? TIMEBEFORE_FORMAT : TIMEBEFORE_FORMAT_YEAR, $time );
    // }

    /**
     * PUSHER NOTIFICATION
     */
    function notification($message)
    {
        $options = array(
            'cluster' => env('PUSHER_APP_CLUSTER'),
            'encrypted' => true
            );
        $pusher = new Pusher(
            env('PUSHER_APP_KEY'),
            env('PUSHER_APP_SECRET'),
            env('PUSHER_APP_ID'), 
            $options
            );
 
        $data['message'] = $message;
        $pusher->trigger('notify-channel', 'App\\Events\\Notify', $data);
 
    }

    /**
     * Is user logged in
     * @return boolean
     */
    function is_logged_in()
    {
        return (is_client_logged_in() || is_staff_logged_in());
    }

    function is_logged_in_admin()
    {
        return (is_client_logged_in_admin() || is_staff_logged_in_admin());
    }

    /**
     * Is client logged in
     * @return boolean
     */
    function is_client_logged_in()
    {
        return session()->has('ojasexchange_session');
    }
    function is_client_logged_in_admin()
    {
        return session()->has('ojasexchange_session_admin');
    }
    /**
     * Is staff logged in
     * @return boolean
     */
    function is_staff_logged_in()
    {
        return session()->has('ojasexchange_session');
    }
    function is_staff_logged_in_admin()
    {
        return session()->has('ojasexchange_session_admin');
    }

    /**
     * get auth data
     * @return boolean
     */
    function auth_data()
    {
        return Admin::where('staffid',session()->get('ojasexchange_session_admin')['id'])->first();
    }

    /**
     * Return logged staff User ID from session
     * @return mixed
     */
    function get_staff_user_id()
    {

        if (!is_staff_logged_in()) {
            return false;
        }

        return session()->get('ojasexchange_session')['id'];
    }

    function get_admin_user_id()
    {

        if (!is_staff_logged_in_admin()) {
            return false;
        }

        return session()->get('ojasexchange_session_admin')['id'];
    }

    /**
     * Return logged client User ID from session
     * @return mixed
     */
    function get_client_user_id()
    {
        if (!is_client_logged_in()) {
            return false;
        }

        return session()->get('ojasexchange_session')['id'];
    }

 

    function secondsToTime($seconds_time)
        {
            if ($seconds_time < 24 * 60 * 60) {
                return gmdate('H:i:s', $seconds_time);
            } else {
                $hours = floor($seconds_time / 3600);
                $minutes = floor(($seconds_time - $hours * 3600) / 60);
                $seconds = floor($seconds_time - ($hours * 3600) - ($minutes * 60));
                return "$hours h :$minutes m :$seconds s";
            }
        }


    /**
     * @since  2.3.3
     * Helper function for checking staff capabilities, this function should be used instead of has_permission
     * Can be used e.q. staff_can('view', 'invoices');
     *
     * @param  string $capability         e.q. view | create | edit | delete | view_own | can_delete
     * @param  string $feature            the feature name e.q. invoices | estimates | contracts | my_module_name
     *
     *    NOTE: The $feature parameter is available as optional, but it's highly recommended always to be passed
     *    because of the uniqueness of the capability names.
     *    For example, if there is a capability "view" for feature "estimates" and also for "invoices" a capability "view" exists too
     *    In this case, if you don't pass the feature name, there may be inaccurate results
     *    If you are certain that your capability name is unique e.q. my_prefixed_capability_can_create , you don't need to pass the $feature
     *    and you can use this function as e.q. staff_can('my_prefixed_capability_can_create')
     *
     * @param  mixed $staff_id            staff id | if not passed, the logged in staff will be checked
     *
     * @return boolean
     */

 
    function staff_can($capability, $feature = null, $staff_id = '')
    {
        if (!is_staff_logged_in()) {
            return false;
        }

        $role_id = session()->get('bulk_marketing')['role'];

        $staff_id = empty($staff_id) ? get_staff_user_id() : $staff_id;

        /**
         * If user is admin return true
         * Admins have all permissions
         */
        // if (is_admin($staff_id)) {
        //     return true;
        // }
        $permissions = null;

        // check role permission
        $permissionlist = Permission::where(['role_id'=>$role_id, 'feature'=> $feature , 'capability'=>$capability ])->first();
        return $permissionlist ? true : false ;
         /**
     * Stop making query if we are doing checking for current user
     * Current user is stored in $GLOBALS including the permissions
     */
        // if ((string) $staff_id === (string) get_staff_user_id() && isset($GLOBALS['current_user'])) {
        //      $permissions = $GLOBALS['current_user']->permissions;
        // }

           /**
     * Not current user?
     * Get permissions for this staff
     * Permissions will be cached in object cache upon first request
     */
    // if (!$permissions) {
    //     if (!class_exists('staff_model', false)) {
    //         $CI->load->model('staff_model');
    //     }

    //     $permissions = $CI->staff_model->get_staff_permissions($staff_id);
    // }

    // if (!$feature) {
    //     $retVal = in_array_multidimensional($permissions, 'capability', $capability);

    //     return hooks()->apply_filters('staff_can', $retVal, $capability, $feature, $staff_id);
    // }

    // foreach ($permissions as $permission) {
    //     if ($feature == $permission['feature']
    //         && $capability == $permission['capability']) {
    //         return hooks()->apply_filters('staff_can', true, $capability, $feature, $staff_id);
    //     }
    // }
    }


    /**
     * @since  2.3.3
     * Check whether a role has specific permission applied
     * @param  mixed  $role_id    role id
     * @param  string  $capability e.q. view|create|read
     * @param  string  $feature    the feature, e.q. invoices|estimates etc...
     * @return boolean
     */
    function has_role_permission($role_id, $capability, $feature)
    {
        // $CI          = &get_instance();
        // $permissions = $CI->roles_model->get($role_id)->permissions;

        // foreach ($permissions as $appliedFeature => $capabilities) {
        //     if ($feature == $appliedFeature && in_array($capability, $capabilities)) {
        //         return true;
        //     }
        // }

        return false;
    }

    /**
     * @since 1.0.0
     * NOTE: This function will be deprecated in future updates, use staff_can($do, $feature = null, $staff_id = '') instead
     *
     * Check if staff user has permission
     * @param  string  $permission permission shortname
     * @param  mixed  $staffid if you want to check for particular staff
     * @return boolean
     */
    function has_permission($permission, $staffid = '', $can = '')
    {
        return staff_can($can, $permission, $staffid);
    }




    if (!function_exists('generate_numbers')) {
    
        function generate_numbers($start, $count, $digits) {
            $result = array();
            for ($n = $start; $n < $start + $count; $n++) {
                $n = $n+1;
            $result[] = str_pad($n, $digits, "0", STR_PAD_LEFT);
        
            }
            return $result;
        }
    }

    function random_referal_code($length_of_string) 
    { 
        $str_result = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
        return substr(str_shuffle($str_result), 0, $length_of_string); 
    } 


    if (!function_exists('encryptor')) {

        function encryptor($string) {
            $output = false;
    
            $encrypt_method = "AES-256-CBC";
            //pls set your unique hashing key
            $secret_key = 'e@c@l@i@c@k';
            $secret_iv = 'S3cur3';
            // hash
            $key = hash('sha512', $secret_key);
            // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
            $iv = substr(hash('sha512', $secret_iv), 0, 16);
            //do the encyption given text/string/number
            $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
            $output = base64_encode($output);
    
    
    
            return $output;
        }
    
    }
    
    if (!function_exists('decryptor')) {
    
        function decryptor($string) {
            $output = false;
    
            $encrypt_method = "AES-256-CBC";
            //pls set your unique hashing key
            $secret_key = 'e@c@l@i@c@k';
            $secret_iv = 'S3cur3';
    
            // hash
            $key = hash('sha512', $secret_key);
    
            // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
            $iv = substr(hash('sha512', $secret_iv), 0, 16);
            $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
    
    
            return $output;
        }
    
    }


    if (! function_exists('sendMail')) {
        function sendMail($email, $data)
        {
            $purpose = $data['purpose'];
            $mailsetting = MailSetting::where('id',1)->first();
          
            $MAIL_FROM_ADDRESS = MailSetting::where('id',1)->first()->MAIL_FROM_ADDRESS;
            $MAIL_FROM_NAME = MailSetting::where('id',1)->first()->MAIL_FROM_NAME;
            $array['view'] = 'emails.invoice';
            $array['subject'] = $data['subject'];
            $array['from'] = $MAIL_FROM_ADDRESS;
            $array['name'] = $MAIL_FROM_NAME;
            $emailcredential = EmailSetting::where(array('name'=>$purpose,'active'=>1))->get();
           
            if($emailcredential){
                foreach ($emailcredential as $key => $value) {
                    if($value){
                        $email_template_id =  $value->email_template_id;
                        if(!empty($email_template_id)){
                            $templatedata = EmailTemplate::where('id',$email_template_id)->first();
                          
                            $message = ""; 
                            if($templatedata){
                                $message = $templatedata->content;
                            }
                          
                            $message = str_replace("{otp}",@$data['otp'],$message);
                            $message = str_replace("{password}",@$data['password'],$message);
                            $message = str_replace("{mobilenumber}",@$to,$message);
                            $message = str_replace("{username}",@$data['username'],$message);

                            
                            $array['content'] = $message;
                           
                            // print_r($array); die;
                            DB::enableQueryLog(); // Enable query log
                            
                           //dd(DB::getQueryLog()); // Show results of log
                           // die;
                           
                            
                                // $smsresponse= Mail::to('rk3161282@gmail.com')->queue(new InvoiceEmailManager($array));
                                require base_path("vendor/autoload.php");
                                $mail = new PHPMailer(true);     // Passing `true` enables exceptions

                                try {

                                    // Email server settings
                                    $mail->SMTPDebug = 0;
                                    $mail->isSMTP();
                                    $mail->CharSet = "utf-8";
                                    $mail->Host = $mailsetting->MAIL_HOST;             //  smtp host
                                    $mail->SMTPAuth = true;
                                    $mail->Username = $mailsetting->MAIL_USERNAME;   //  sender username
                                    $mail->Password = $mailsetting->MAIL_PASSWORD;       // sender password
                                    $mail->SMTPSecure = $mailsetting->MAIL_ENCRYPTION;                  // encryption - ssl/tls
                                    $mail->Port = $mailsetting->MAIL_PORT;                          // port - 587/465

                                    $mail->setFrom($mailsetting->MAIL_FROM_ADDRESS, $mailsetting->MAIL_FROM_NAME);
                                    $mail->addAddress($email);
                                    // $mail->addCC($request->emailCc);
                                    // $mail->addBCC($request->emailBcc);

                                    $mail->addReplyTo($email, '');

                                    // if(isset($_FILES['emailAttachments'])) {
                                    //     for ($i=0; $i < count($_FILES['emailAttachments']['tmp_name']); $i++) {
                                    //         $mail->addAttachment($_FILES['emailAttachments']['tmp_name'][$i], $_FILES['emailAttachments']['name'][$i]);
                                    //     }
                                    // }


                                    $mail->isHTML(true);                // Set email content format to HTML
                                    // $email_template = 'mail_tempalte.html';
                                    // $message = file_get_contents($email_template);
                                    // $message = str_replace('%username%', $username, $message);
                                    $message = str_replace('%user_id%', encryptor($data['member_id']), $message);
                                        
                                    $mail->MsgHTML($message);
                                    $mail->Subject = $data['subject'];
                                    // $mail->Body    = $message;

                                    // $mail->AltBody = plain text version of email body;

                                    if( !$mail->send() ) {
                                        //echo $mail->ErrorInfo;
                                        $emailsent = new EmailSent();
                                        $emailsent->from_email = $MAIL_FROM_ADDRESS;
                                        $emailsent->to_email = $email;
                                        $emailsent->member_id = $data['member_id'];
                                        $emailsent->subject = $data['subject'];
                                        $emailsent->content = $message;
                                        $emailsent->purpose = $purpose;
                                        $emailsent->attachment = "";
                                        $emailsent->is_automatic = $data['is_automatic'];
                                        $emailsent->error_Message = $mail->ErrorInfo;
                                        $emailsent->save();
                                    }
                                    
                                    else {
                                        $emailsent = new EmailSent();
                                        $emailsent->from_email = $MAIL_FROM_ADDRESS;
                                        $emailsent->to_email = $email;
                                        $emailsent->member_id = $data['member_id'];
                                        $emailsent->subject = $data['subject'];
                                        $emailsent->content = $message;
                                        $emailsent->purpose = $purpose;
                                        $emailsent->attachment = "";
                                        $emailsent->is_automatic = $data['is_automatic'];
                                        $emailsent->error_Message = "";
                                        $emailsent->save();
                                        //echo 'Message sent.';
                                        return true;
                                    // return back()->with("success", "Email has been sent.");
                                    }

                                } catch (Exception $e) {
                                    echo 'Message could not be sent.';
                                    //return back()->with('error','Message could not be sent.');
                                }
                                  
                                
                            
                        }
                    }
                }
            }   
                
                
                
               
        }
    }

    if (! function_exists('replaceMessage')) {
        function replaceMessage($event_type,$data)
        {
            $sms_url_array = [];
            $otp = $password = $mobilenumber = $username = $transid = $apitransid = $apiname = $openingbal = $closingbal = $debit_credit = $amount =
            $complainumber =  $status = $date = $time = "";
            $event_data = EventType::where('name',$event_type)->first();
            if($event_data){
                $smscredential = tbl_sms_settings::where(array('title'=>$event_data->id,'active'=>1))->get();
                if(!empty($smscredential)){
                    foreach ($smscredential as $key => $value) {
                        $message = $smscredential->message;
                        $message = strip_tags(html_entity_decode($message));
                        if($event_type == 'Recharge'){
                           $rechargedata =  Recharge::where('id',$data->id)->first();
                           $otp = ""; $password = "";
                           $mobilenumber = $rechargedata->recharge_number;
                           $username = User::where('id',$rechargedata->user_id)->first()->user_name;
                           $transid = $rechargedata->txn_id;
                           $apitransid = $rechargedata->txn_id;
                           $apiname = "";
                           $openingbal = $rechargedata->opening_balance;
                           $closingbal = $rechargedata->opening_balance != null ? ($rechargedata->opening_balance - $rechargedata->amount) : 0;
                           $debit_credit = "debit";
                           $amount = $rechargedata->amount;
                           $complainumber =  ""; 
                           $status = $rechargedata->last_status; 
                           $date = date("Y-m-d", strtotime($rechargedata->created_at)); 
                           $time = date("H:i:s", strtotime($rechargedata->created_at)); 
                        }
                        $message = str_replace("{otp}",@$otp,$message);
                        $message = str_replace("{password}",@$password,$message);
                        $message = str_replace("{mobilenumber}",@$mobilenumber,$message);
                        $message = str_replace("{username}",@$username,$message);
                        $message = str_replace("{transid}",@$transid,$message);
                        $message = str_replace("{apitransid}",@$apitransid,$message);
                        $message = str_replace("{apiname}",@$apiname,$message);
                        $message = str_replace("{openingbal}",@$openingbal,$message);
                        $message = str_replace("{closingbal}",@$closingbal,$message);
                        $message = str_replace("{debit_credit}",@$debit_credit,$message);
                        $message = str_replace("{amount}",@$amount,$message);
                        $message = str_replace("{complainumber}",@$complainumber,$message);
                        $message = str_replace("{status}",@$status,$message);
                        $message = str_replace("{date}",@$date,$message);
                        $message = str_replace("{time}",@$time,$message);


                        $sms_api = $smscredential->sms_api;
                        $tbl_sms_api = tbl_sms_api::where(array('id'=>$sms_api))->first();
                        $sms_url = "";
                        if($tbl_sms_api){
                            $sms_url =  $tbl_sms_api->sms_url;
                            $sms_url = strip_tags(html_entity_decode($sms_url));
                            $sms_url = str_replace("{mobilenumber}",@$data['mobilenumber'],$sms_url);
                            $sms_url = str_replace("{message}",urlencode(trim($message)),$sms_url); 
                            $sms_url = str_replace("+","%20",$sms_url); 
                            array_push($sms_url_array,$sms_url);
                        }

                    }
                }

            }

            return $sms_url_array;
           
        }
    }


    if (! function_exists('sendSMS')) {
        function sendSMS($to, $data)
        {
           
            $purpose = $data['purpose'];
          if (!empty($purpose) || !empty($to)) {
    
                if(strpos($to, '+91') !== false){
                    $to = substr($to, 3);
                }

                // $auth_key = env('AUTH_KEY');
                $smscredential = tbl_sms_settings::where(array('title'=>$purpose,'active'=>1))->first();
               
                if($smscredential){
                    $message = $smscredential->message;
                    $sms_api = $smscredential->sms_api;
                    $tbl_sms_api = tbl_sms_api::where(array('id'=>$sms_api))->first();
                    if($tbl_sms_api){
                        $sms_url =  $tbl_sms_api->sms_url;
                        $sms_url = strip_tags(html_entity_decode($sms_url));
                       
                        $message = strip_tags(html_entity_decode($message));
                        $message = str_replace("{otp}",@$data['otp'],$message);
                        $message = str_replace("{password}",@$data['password'],$message);
                        $message = str_replace("{mobilenumber}",@$to,$message);
                        $message = str_replace("{username}",@$data['username'],$message);
                        $message = str_replace("{transid}",@$data['transid'],$message);
                        $message = str_replace("{apitransid}",@$data['apitransid'],$message);
                        $message = str_replace("{apiname}",@$data['apiname'],$message);
                        $message = str_replace("{openingbal}",@$data['openingbal'],$message);
                        $message = str_replace("{closingbal}",@$data['closingbal'],$message);
                        $message = str_replace("{debit_credit}",@$data['debit_credit'],$message);
                        $message = str_replace("{amount}",@$data['amount'],$message);
                        $message = str_replace("{complainumber}",@$data['complainumber'],$message);
                        $message = str_replace("{status}",@$data['status'],$message);
                        $message = str_replace("{date}",@$data['date'],$message);
                        $message = str_replace("{time}",@$data['time'],$message);
                        if(!empty($data['member_id'])){
                            $members = User::where('id',$data['member_id'])->first();
                            $message = replaceContent($message,$members);
                            $sms_url = str_replace("{mobilenumber}",$to,$sms_url);
                            $sms_url = str_replace("{message}",urlencode(trim($message)),$sms_url); 
                            // $sms_url = str_replace("{username}",$to,$sms_url);
                            $sms_url = str_replace("+","%20",$sms_url); 
                            // $sms_url = str_replace("%40","@",$sms_url); 
                            // $sms_url = str_replace("{{template_id}}",@$template_id,$sms_url); 
                            // echo ($sms_url); die;
                            $crl = curl_init();
                            curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, FALSE);
                            curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, 2);
                            curl_setopt($crl, CURLOPT_URL, $sms_url);
                            curl_setopt($crl, CURLOPT_HEADER, 0);
                            curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
                            $response = curl_exec($crl);
//                             $curl = curl_init();
// //http://sms.akashtodarka.com/app/smsapi/index.php?key=461D55FE064C11&campaign=0&routeid=9&type=text&contacts=7481963055&%20senderid=MVCLUB&msg=You%20have%20successfully%20password%20change.You%20can%20also%20visit%20our%20website%20myvictoryclub.com%20-MyVictory%20Club&template_id=1207164094330988529
//                             curl_setopt_array($curl, array(
//                             CURLOPT_URL => $sms_url,
//                             CURLOPT_RETURNTRANSFER => true,
//                             CURLOPT_ENCODING => "",
//                             CURLOPT_MAXREDIRS => 10,
//                             CURLOPT_TIMEOUT => 30,
//                             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//                             CURLOPT_CUSTOMREQUEST => "GET",
//                             CURLOPT_HTTPHEADER => array(
//                                 "cache-control: no-cache",
//                                 "postman-token: b66388ef-93f2-105a-bc78-9c1b72ab7788"
//                             ),
//                             ));

//                             $response = curl_exec($curl);
//                             $err = curl_error($curl);

//                             curl_close($curl);

//                             if ($err) {
//                             // echo "cURL Error #:" . $err;
//                             } else {
//                             // echo $response;
//                             }
                            // $curl = curl_init();
    
                            //     curl_setopt_array($curl, array(
                            //     CURLOPT_URL => ($sms_url),
                            //     CURLOPT_RETURNTRANSFER => true,
                            //     CURLOPT_ENCODING => "",
                            //     CURLOPT_MAXREDIRS => 10,
                            //     CURLOPT_TIMEOUT => 30,
                            //     CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                            //     CURLOPT_CUSTOMREQUEST => "GET",
                            //     CURLOPT_HTTPHEADER => array(
                            //         "cache-control: no-cache"
                            //     ),
                            //     ));
            
                            //     $response = curl_exec($curl);
                            //     var_dump($response);die;
                            //     $err = curl_error($curl);
            
                            //     curl_close($curl);

                                $smssent = new SmsSent();
                                $smssent->to_number = $to;
                                $smssent->member_id = $data['member_id'];
                                $smssent->content = $message;
                                $smssent->url = $sms_url;
                                $smssent->response = $response;
                                $smssent->sms_template_id = @$sms_template_id;
                                $smssent->purpose = $purpose;
                                $smssent->save();


                        }
                    }

                 
                    
                }
            }
        }
    }
    
    if (! function_exists('replaceContent')) {
        function replaceContent($content, $members)
        {
            
            // if (!empty($members->name)) {
                        
            //     $content = str_replace("{name}",$members->name,$content); 
            //  }
          
           
             return $content;
            
        }
    }


   



  
  