<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Defuse\Crypto\Crypto;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use App\Models\User;
use Mail;
use QrCode;
use PDFCREATOR;

define( 'API_ACCESS_SEND', 'AAAA6YBXh1k:APA91bFL0q7QAXQGohXMpTwHco79f13C8PFk1Oo8kKhg1JerOulT9-37dxyP8X5ibABI0NuQ4ZsVxKQKCt7HuR7lUdJJuB-hTVnBmOUIBYfBlHb-Lcp6aGkj4erfF7J__A5hufXjF8Vt' );

class SendMail extends Controller
{
    protected static $pass = 'S1v3pY0uB3e';
    protected static function enkrip($string){
        return Crypto::encryptWithPassword($string,self::$pass);
    }
    public static function dekrip($enc){
        try{
	        return Crypto::decryptWithPassword($enc,self::$pass);
		}catch (\Exception $e){
            return false;
		}
    }
    public static function kirim($to_name,$to_email,$forget=false){
        $date=date('YmdHis');
        $cekdata = User::where('email', $to_email)->orderBy('id', 'DESC')->first();
        if (isset($cekdata->id)){
            if($forget){
                $string_enc     = $to_email.'|'.$date.'|FOR';
                $url            = url('/verifikasiemail').'?key='.self::enkrip($string_enc);
                $subject        = 'Ubah Password ('.$cekdata->fakpanjang.')';
                $subjectmail    = 'Ubah Password';
                $note           = 'Anda telah melakukan permohonan ubah password. Silahkan klik link berikut untuk melanjutkan proses.';
                DB::table('password_resets')->insert([
                    'email'     => $to_email,
                    'token'     => self::enkrip($string_enc),
                    'created_at'=> date("Y-m-d H:i:s")
                ]);
            }else{
                $string_enc     = $to_email.'|'.$date.'|VER';
                $url            = url('/verifikasiemail').'?key='.self::enkrip($string_enc);
                $subject        = 'Verifikasi Email ('.$cekdata->fakpanjang.')';
                $subjectmail    = 'Verifikasi Email';
                $note           = 'Email anda telah terdaftar di Aplikasi ('.$cekdata->fakpanjang.') Email ini dapat digunakan jika anda lupa password. Selanjutnya dimohon Bapak/Ibu membuat password untuk login ke aplikasi dengan cara Klik Tombol di bawah ini.';
            }
            $data = array(
                'nama_lengkap'      => $to_name, 
                'fakultas'          => $cekdata->fakpanjang, 
                'url_verifikasi'    => $url,
                'forget'            => $forget,
                'subject'           => $subjectmail, 
                'note'              => $note,
            );
            if ($to_email != 'arsiparis@localhost.com'){
                Mail::send('mail/user', $data, function($message) use ($to_name, $to_email, $subject) {
                    $message->to($to_email, $to_name)->subject($subject);
                    $message->from('swandhana.fp@ub.ac.id','Mail Admin');
                });
            }
        }
    }
    public static function kirimUser($to_name,$to_email,$to_username,$password,$ubahpass=false){
        $date=date('YmdHis');
        $cekdata = User::where('email', $to_email)->first();
        if (isset($cekdata->id)){
            if($ubahpass){
                $subject    = 'Password User Diubah ('.$cekdata->fakpanjang.')';
                $note       = 'Password anda telah diubah oleh admin dengan password berikut:';
            }else{
                $subject    = 'User Didaftarkan ('.$cekdata->fakpanjang.')';
                $note       = 'Email anda telah terdaftar di Aplikasi ('.$cekdata->fakpanjang.'). Email ini dapat digunakan jika anda lupa password. Untuk login silahkan akses dengan user <b>'.$to_username.'</b> atau email ini dan dengan password berikut:';
            }
            $data = array(
                'nama_lengkap'  => $to_name, 
                'password'      => $password,
                'subject'       => $subject,
                'note'          => $note,
            );
            if ($to_email != 'arsiparis@localhost.com'){
                Mail::send('mail/useradmin', $data, function($message) use ($to_name, $to_email, $subject) {
                    $message->to($to_email, $to_name)->subject($subject);
                    $message->from('swandhana.fp@ub.ac.id','Mail Admin');
                });
            }
        }
    }
    public static function notif($to_name,$to_email,$subject,$note){
        $data = array(
            'nama_lengkap'  => $to_name,
            'subject'       => $subject,
            'note'          => $note,
        );
        if ($to_email != 'arsiparis@localhost.com'){
            Mail::send('mail/notif', $data, function($message) use ($to_name, $to_email, $subject) {
                $message->to($to_email, $to_name)->subject($subject);
                $message->from('swandhana.fp@ub.ac.id','Mail Admin');
            });
        }
        $jtokencari 	= User::where('email', $to_email)->whereNotNull('firebaseid')->get();
        if (!empty($jtokencari)){
            foreach ( $jtokencari as $rtokencari ){
                $firebaseid = $rtokencari->firebase;
                $msg = array (
                    'message' 	=> $subject,
                    'title'		=> Session('namaapps01'),
                    'subtitle'	=> Session('fakpanjang'),
                    'tickerText'=> 'Notification Centre',
                    'image'		=> '',
                    'vibrate'	=> 1,
                    'sound'		=> 1,
                    'largeIcon'	=> 'large_icon',
                    'smallIcon'	=> 'small_icon'
                );
                $fields = array
                (
                    'to' 			=> $firebaseid,
                    'priority'		=> 'high',
                    'notification' 	=> [
                        "title" => Session('namaapps01'),
                        "sound" => "default",
                        "body" 	=> $subject
                    ],
                    'data'			=> $msg
                    
                );
                $headers = array
                (
                    'Authorization: key=' . API_ACCESS_SEND,
                    'Content-Type: application/json'
                );
                $url = 'https://fcm.googleapis.com/fcm/send';
                $ch = curl_init();
            
                // Set the url, number of POST vars, POST data
                curl_setopt($ch, CURLOPT_URL, $url);
            
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            
                // Disabling SSL Certificate support temporarly
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  0);
                curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );		
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
            
                // Execute post
                $result = curl_exec($ch);
                curl_close($ch);
            }
        }
    }
    public static function mobilenotif($to_name,$to_email,$subject,$note){
        $pesan      = '';
        $tuliskirim = $note;
        if ($to_name == 'all'){
            $getppds    = User::where('previlage', $to_email)->whereNotNull('firebase')->get();
            if (!empty($getppds)){
                
                foreach($getppds as $rowsppds){
                    $firebaseid = $rowsppds->firebase;
                    $msg = array (
                        'message' 	=> $tuliskirim,
                        'title'		=> 'LIS',
                        'subtitle'	=> 'Laboratory Information System',
                        'tickerText'=> 'Pasien Terkirim ke PACS',
                        'image'		=> '',
                        'vibrate'	=> 1,
                        'sound'		=> 1,
                        'largeIcon'	=> 'large_icon',
                        'smallIcon'	=> 'small_icon'
                    );
                    $fields = array
                    (
                        'to' 			=> $firebaseid,
                        'priority'		=> 'high',
                        'notification' 	=> [
                            "title" => 'LIS-RSSA Notification Control',
                            "sound" => "default",
                            "body" 	=> $tuliskirim
                        ],
                        'data'			=> $msg
                    );
                    $headers = array
                    (
                        'Authorization: key=' . API_ACCESS_KEY,
                        'Content-Type: application/json'
                    );
                    $url = 'https://fcm.googleapis.com/fcm/send';
                    $ch = curl_init();
                    // Set the url, number of POST vars, POST data
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    // Disabling SSL Certificate support temporarly
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  0);
                    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
                    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
                    // Execute post
                    $result = curl_exec($ch);
                    curl_close($ch);
                    $pesan  = $pesan.'<br />Notif To : '.$rowsppds->nama;
                }
            }
        } else {
            $msg 		= array (
                'message' 	=> $tuliskirim,
                'title'		=> 'LIS',
                'subtitle'	=> 'Laboratory Information System',
                'tickerText'=> 'Adendum Saved',
                'image'		=> '',
                'vibrate'	=> 1,
                'sound'		=> 1,
                'largeIcon'	=> 'large_icon',
                'smallIcon'	=> 'small_icon'
            );
            $fields = array
            (
                'to' 			=> $to_email,
                'priority'		=> 'high',
                'notification' 	=> [
                    "title" => 'LIS-RSSA Notification Control',
                    "sound" => "default",
                    "body" 	=> $tuliskirim
                ],
                'data'			=> $msg
                
            );
            $headers = array
            (
                'Authorization: key=' . API_ACCESS_KEY,
                'Content-Type: application/json'
            );
            $url = 'https://fcm.googleapis.com/fcm/send';
            $ch = curl_init();
        
            // Set the url, number of POST vars, POST data
            curl_setopt($ch, CURLOPT_URL, $url);
        
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
            // Disabling SSL Certificate support temporarly
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  0);
            curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );		
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        
            // Execute post
            $result = curl_exec($ch);
            curl_close($ch);
        }
        return $pesan;
    }
}
