<?php

namespace App\Http\Controllers;

use App\DataTables\TmpGroupEmailDataTable;
use App\EmailJob;
use App\EmailLog;
use App\PendingSingleSms;
use App\SavedMessage;
use App\SmsImage;
use App\TmpGroupSms;
use App\UserJob;
use App\Log;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Auth;
use App\Tools\SmsTools;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;
use App\Email_templates;

class EmailController extends Controller
{
    public function send_single_email(Request $request) {

        $step=1;
        //reset current session data for sending single sms
        if($request->session()->has('single_email_data')) {
            $request->session()->forget('single_email_data');
        }
        if($request->session()->has('alert')) {
            $request->session()->forget('alert');
        }

        $emailtemplate = Email_templates::query()->where('client_id','=', Auth::user()->id)->select('template_name','template_head','template_foot')->get();
//

        //show view
        return view('email.send_single_email', [
            'step'=>$step,
            'email_temp'=>$emailtemplate
        ]);
    }

    public function get_saved_email() {
        $inputs = request()->all();
        $saved = SavedMessage::findOrFail($inputs['id']);
        return $saved;
    }

    public function post_save_email(Request $request) {
        $this->validate($request, [
            'message' => 'required',
            'type' => 'required',
            'name' => 'required'
        ]);
        $inputs = $request->all();
        SavedMessage::firstOrCreate([
            'message' => $inputs['message'],
            'type' => $inputs['type'],
            'name' => $inputs['name'],
            'user_id' => auth()->id()
        ]);
        return 'success';
    }

    public function send_bulk_email(Request $request) {
        $step=1;
        //reset current session data for sending single sms
        if($request->session()->has('bulk_email_data')) {
            $request->session()->forget('bulk_email_data');
        }
        if($request->session()->has('alert')) {
            $request->session()->forget('alert');
        }

        //get templates
//        $templates = SavedMessage::where('user_id', auth()->id())->get();

        $emailtemplate = Email_templates::query()->where('client_id','=', Auth::user()->id)->select('template_name','template_head','template_foot')->get();

        //show view
        return view('email.send_bulk_email', ['step'=>$step , 'email_temp'=>$emailtemplate]);
    }

    public function send_group_email(Request $request, TmpGroupEmailDataTable $dataTable) {
        if($request->has('draw')) {
            return $dataTable->render('email.send_group_email', ['step' => 2]);
        }

        $step=1;
        //reset current session data for sending group sms
        if($request->session()->has('group_email_data')) {
            $request->session()->forget('group_email_data');
        }
        if($request->session()->has('alert')) {
            $request->session()->forget('alert');
        }

        //fetch user groups
        $groups = $request->user()->groups()->orderBy('name', 'asc')->get(['name', 'id']);

        //get templates
//        $templates = SavedMessage::where('user_id', auth()->id())->get();


        $emailtemplate = Email_templates::query()->where('client_id','=', Auth::user()->id)->select('template_name','template_head','template_foot')->get();


        //show view
        return view('email.send_group_email', [
            'step'=>$step,
            'groups' => $groups,
            'email_temp'=>$emailtemplate
        ]);
    }


    public function send_email_dlr(Request $request) {
        $msgid = $request->input('msgID');
        $msg = $request->input('msg');
        $myid = $request->input('mid');

        $destination = $request->input('destination');
        $smsid = $request->input('smsid');
        $error_code = $request->input('errorCode');
        $error_msg = $request->input('errorDescr');

//        $msglen = $request->input('msglen');
//        $time = $request->input('timestamp');
//        $status = $request->input('status');
//        $smsc = $request->input('smsc');
//        $source = $request->input('source');


        $stri = $msg . ":end";
//        $message = SmsTools::get_string($stri, 'Text:', ':end');
        $status_desc = SmsTools::get_string($msg, 'stat:', 'err:');
        $submit_date = SmsTools::get_string($msg, 'submit date:', 'done date:');
        $deliv_date = SmsTools::get_string($msg, 'done date:', 'stat:');
        $sent = SmsTools::string_date($submit_date);
//        $deli = SmsTools::string_date($deliv_date);

        $log_received = DB::table('log_received')->where('id', $myid)->orderBy('created_at', 'desc')->first();

        $l_status = '';
        $l_msgid = '';
        $l_delivery_date = Carbon::now()->toDateTimeString();
        $l_sent_date = $sent;

        $l_msgid = $kID = !empty($log_received) ? $log_received->msgid : '';
        if ($kID == '') {
            if (substr($msg, 0, 3) == 'id:'||substr($msg, 1, 4) == 'id:') {
                $msg = 'ACK/';
            }
            $l_status = $msg;
            $l_msgid = $msgid;
        } else {
            if ($status_desc == 'ACCEPTD'||$status_desc == 'ENROUTE') {
                $status_desc = 'ACK/';
            }
            if($status_desc == 'Delivered'){
                $status_desc = 'DELIVRD';
            }
            if($status_desc == 'Undeliverable'){
                $status_desc = 'UNDELIV';
            }
            $status_desc = trim($status_desc);
            $l_status = $status_desc;
            $l_delivery_date = Carbon::now()->toDateTimeString();
        }

        //compute delivery time
        $diff = null;
//        if($status_desc=='DELIVRD') {
        if(1) {
            $log = Log::find($myid);
            if(!empty($log)) {
                $submitDate = Carbon::parse($log->submit_date);
                $delivDate = Carbon::parse($l_delivery_date);
                $diff = $delivDate->diffInSeconds($submitDate);
            }
        }

        //update db
        if(empty($log_received)) {
            //insert
            DB::table('log_received')->insert(
                [
                    'id' => $myid,
                    'msgid' => $l_msgid,
                    'status' => $l_status,
                    'delivery_date' => $l_delivery_date,
                    'sent_date' => $l_sent_date,
                    'delivery_time' => $diff,
                    'error_code' => !empty($error_code) ? $error_code : null,
                    'error_msg' => !empty($error_msg) ? $error_msg : null,
                    'created_at' => Carbon::now()->toDateTimeString()
                ]
            );
        } else {
            //update
            DB::table('log_received')
                ->where('id', $myid)
                ->update(
                [
                    'msgid' => $l_msgid,
                    'status' => $l_status,
                    'delivery_date' => $l_delivery_date,
                    'sent_date' => $l_sent_date,
                    'delivery_time' => $diff,
                    'error_code' => !empty($error_code) ? $error_code : null,
                    'error_msg' => !empty($error_msg) ? $error_msg : null,
                    'updated_at' => Carbon::now()->toDateTimeString()
                ]
            );
        }

        return "Updated!";
    }


    public function send_email_api(Request $request) {
        $username = $request['username'];
        $password = $request['password'];
        $from = $request['from'];
        $to = trim($request['to']);
        $cc = trim($request['cc']);
        $bcc = trim($request['bcc']);
        $subject = $request['subject'];
        $text = $request['text'];
        $html = $request['html'];
        $attachment = $request['attachment'];

        if(empty($username)) {
            return [
                'code' => 402,
                'message' => 'The username is required'
            ];
        }
        if(empty($password)) {
            return [
                'code' => 402,
                'message' => 'The password is required'
            ];
        }
        if(empty($from)) {
            return [
                'code' => 402,
                'message' => 'The source is required'
            ];
        }
        if(empty($to)) {
            return [
                'code' => 402,
                'message' => 'The destination is required'
            ];
        }
        if(empty($subject)) {
            return [
                'code' => 402,
                'message' => 'The subject is required'
            ];
        }
        if(empty($html) && empty($text)) {
            return [
                'code' => 402,
                'message' => 'The message is required'
            ];
        }

        if (!Auth::once([
            'username' => $username,
            'password' => $password
        ])) {
            return [
                'code' => 401,
                'message' => 'Invalid Credential'
            ];
        }

        $message = empty($html) ? $text : $html;
        $user = Auth::user();
        $credit = $user->credit;

        //send single sms now
        $destination = explode(',', $to);
        $sender = $from;
        $msgs = $message;


        $price = 0.0;
        foreach ($destination as $single_email) {
            if (!filter_var($single_email, FILTER_VALIDATE_EMAIL)) {
                continue;
            }
            $price += (float)$credit->email_price;
        }

        $cost = $price;
        // cost of sending one msg with this no_pages to one person
        $nummsisdn = count($destination);
        // no of recepients
        $tot_cost = $cost;

        $curr_bal = $credit->new_bal;

        $date = Carbon::now();

        if ($curr_bal >= $tot_cost) {
            $count = 0;
            $no_rej_msisdn = 0;
            while ($count !== $nummsisdn) {
                $email = $destination[$count];
                //put msisdn in proper format
                $email = trim($email);
                if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    $id='';
                    while(1) {
                        $id = uniqid('NE', true);
                        if(empty(EmailLog::find($id)))
                            break;
                    }

                    $user->pending_single_email()->create([
                        'email' => $email,
                        'sender' => $sender,
                        'subject' => $subject,
                        'message' => $msgs,
                        'type' => 'guiuser',
                        'sched_datetime' => $date
                    ]);
                } else {
                    continue;
                }
                $count++;
            }


                $logged = $nummsisdn - $no_rej_msisdn;

                //update audit trails
                $user->audit_trails()->create([
                    'username' => $user->username,
                    'date' => Carbon::now()->toDateTimeString(),
                    'activity' => $user->username.' sent a single mail to '.$logged.' email address(es)'
                ]);

            if(empty($logged)) {
                if(!empty($errorMsg)) {
                    return [
                        'code' => 404,
                        'message' => $errorMsg
                    ];
                } else {
                    return [
                        'code' => 500,
                        'message' => 'Unable to send email to '.$request['destination']
                    ];
                }
            } else {
                return [
                    'code' => 0,
                    'message' => $logged.' email(s) successfully sent'.(!empty($errorMsg) ? ', '.$errorMsg :'!')
                ];

            }

        } else {
            return [
                'code' => 403,
                'message' => "You don't have enough balance to send this message"
            ];
        }


        return [
            'code' => 0,
            'message' => 'Successful'
        ];
    }

    public function post_send_single_email(Request $request) {
        //get current user
        $user = Auth::user();
        $credit = $user->credit;

        //get current step
        $step = $request->get('step', 1);

        //process for step 1
        if($step == 1)
        {
            //validate the request
            $this->validate($request, [
                'recipient' => 'required',
                'sender' => 'required|email',
                'subject' => 'required',
                'schedule_date' => 'present',
                'message_content' => 'required',
                'image_upload' => 'image'
            ]);

            //get data for step 2
            $destination = explode(',', $request->get('recipient'));

            $price = 0.0;
            foreach ($destination as $single_email) {
                if (!filter_var($single_email, FILTER_VALIDATE_EMAIL)) {
                    return Redirect::back()->withInput()->withErrors(array('recipient' => $single_email.' is not a valid email address'));
                }
                $price += (float)$credit->email_price;
            }
            $cost = $price;
            // cost of sending one msg with this no_pages to one person
            $nummsisdn = count($destination);
            // no of recepients
            $tot_cost = $cost;

            $curr_bal = $credit->new_bal;

//            $price_per_email = $cost;
            $recipients = $nummsisdn;
            $total_price = $tot_cost;
            $credit_available = $curr_bal;
            $imgId = null;

            //update image if image exist
            if(!empty($request['image_upload'])) {
                if ($request->file('image_upload')->isValid()) {
                    $current_filename = $request->file('image_upload')->getClientOriginalName();
                    $fileMimeType = $request->file('image_upload')->getMimeType();

                    $destinationPath = storage_path() . DIRECTORY_SEPARATOR. 'uploads' . DIRECTORY_SEPARATOR;
                    $fileName = $user->username. '_' . $current_filename;
                    $request->file('image_upload')->move($destinationPath, $fileName);
                    $full_path = $destinationPath . $fileName;
                    while(1) {
                        $imgId = uniqid();
                        if(empty(SmsImage::find($imgId))) {
                           break;
                        }
                    }
                    $user->sms_images()->create([
                        'path' => $full_path,
                        'file_name' => $current_filename,
                        'mime_type' => $fileMimeType,
                        'id' => $imgId
                    ]);
                } else {
                    return Redirect::back()->withInput()->withErrors(array('image_upload' => 'Sorry, The file upload failed!'));
                }
            }

            $new_msg_text = $request->get('message_content', '');
            $msg = $new_msg_text;
            if(!empty($imgId)) {
                $sms_msg_url = route('sms_image', ['id'=>$imgId]);
                $msg = $new_msg_text."\n".$sms_msg_url;
            }

            //store user input in the new session data
            session(['single_email_data'=>[
                'recipient' => $request->get('recipient'),
                'sender' => $request->get('sender'),
                'subject' => $request->get('subject'),
                'message_content' => $msg,
                'recipients' => $recipients,
                'total_price' => $total_price,
                'credit_available' => $credit_available,
                'schedule_date' => Carbon::parse($request->get('schedule_date')),
            ]]);
            $step=2;
        }
        else if($step==2)
        {
            //check if next button was pressed
            if($request->has('submit'))
            {
                session(['alert', []]);
                //send single sms now
                $destination = explode(',', session('single_email_data')['recipient']);
                $no_chars = strlen(session('single_email_data')['message_content']);
                $sender = session('single_email_data')['sender'];
                $subject = session('single_email_data')['subject'];
                $msgs = session('single_email_data')['message_content'];
                $submitdt = Carbon::now()->toDateTimeString();
                $created_by = $user->username;

//                $price = $credit->price;
                $cost = session('single_email_data')['total_price'];
                // cost of sending one msg with this no_pages to one person
                $nummsisdn = count($destination);
                // no of recepients
                $tot_cost = $cost;

                $curr_bal = $credit->new_bal;

                $rejected_arr = [];
                $user_sess = $user->username;

                if(isset(session('single_email_data')['schedule_date']) && !empty(session('single_email_data')['schedule_date'])) {
                    $sch_date = Carbon::parse(session('single_email_data')['schedule_date']);
                    $now = Carbon::now();
                    $date = $now->lte($sch_date) ? $sch_date : $now;
                } else {
                    $date = Carbon::now();
                }

                $oneMinuteLater = Carbon::now()->addMinutes(1);
                $sentItNow = $date->lte($oneMinuteLater);
                $data = [];

                if ($curr_bal >= $tot_cost) {
                    $count = 0;
                    $job_id = $user->username .'_'. date('YmdHis');
                    $no_rej_msisdn = 0;
                    while ($count !== $nummsisdn) {
                        $email = $destination[$count];
                        //put msisdn in proper format
                        $email = trim($email);
                        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
                            $id='';
                            while(1) {
                                $id = uniqid('NE', true);
                                if(empty(EmailLog::find($id)))
                                    break;
                            }

                            if($sentItNow==false) {
                                $data[] = $email;
                            } else {
                                $user->pending_single_email()->create([
                                    'email' => $email,
                                    'sender' => $sender,
                                    'subject' => $subject,
                                    'message' => $msgs,
                                    'sched_datetime' => $date
                                ]);
                                //SmsTools::send_single_email($id, $job_id, $msisdn, $sender, $sms_count, $network, $msgs, $submitdt, $created_by, $user);
                            }
                        } else {
                            abort(500, 'Invalid Email');
                        }
                        $count++;
                    }

                    if($sentItNow==false) {
                        foreach ($data as $dat) {
                            $user->pending_single_email()->create([
                                'email' => $dat,
                                'sender' => $sender,
                                'subject' => $subject,
                                'message' => $msgs,
                                'sched_datetime' => $date
                            ]);
                        }

                        //update audit trails
                        $user->audit_trails()->create([
                            'username' => $user->username,
                            'date' => Carbon::now()->toDateTimeString(),
                            'activity' => $user->username.' sent a single mail to '.count($data).' email address(es)'
                        ]);

                        $logged = count($data);

                        if ($no_rej_msisdn == 0) {
                            $request->session()->flash('success', $logged . ' message(s) successfully scheduled!');
                        } else {
                            $request->session()->flash('success', $logged . ' messages successfully scheduled, ' . $no_rej_msisdn . ' rejected');
                        }
                    } else {
                        $logged = $nummsisdn - $no_rej_msisdn;

                        //update audit trails
                        $user->audit_trails()->create([
                            'username' => $user->username,
                            'date' => Carbon::now()->toDateTimeString(),
                            'activity' => $user->username.' sent a single mail to '.$logged.' email address(es)'
                        ]);

                        if ($no_rej_msisdn == 0) {
                            $request->session()->flash('success', $logged . ' message(s) successfully sent!');
                        } else {
                            $request->session()->flash('success', $logged . ' message(s) successfully sent!, ' . $no_rej_msisdn . ' rejected');
                        }
                    }
                } else {
                    return Redirect::back()->withInput()->withErrors(array('error' => 'Sorry, you don\'t have enough credit to proceed!'));
                }

                //reset session
                $step=0;
                $request->session()->forget('single_email_data');
                if(!$request->session()->has('success') || empty(session('success')))
                    $request->session()->flash('success', 'Your SMS Message has been successfully sent!');
            }
            //in case back button was pressed
            else
            {
                //go back to step 1
                $step=1;

            }
        }
        $emailtemplate = Email_templates::query()->select('template_name','template_head','template_foot')->get();
        return view('email.send_single_email', ['step'=>$step ,'email_temp'=> $emailtemplate]);
    }

    public function send_personalised_bulk_email() {
        $step=1;
        //reset current session data for sending single sms
        if(session()->has('bulk_email_personalised_data')) {
            session()->forget('bulk_email_personalised_data');
        }
        if(session()->has('alert')) {
            session()->forget('alert');
        }

        $emailtemplate = Email_templates::query()->select('template_name','template_head','template_foot')->get();
        //show view
        return view('email.send_bulk_personalised_email', ['step'=>$step , 'email_temp'=>$emailtemplate]);
    }

    public function send_personalised_group_email(Request $request, TmpGroupEmailDataTable $dataTable) {
        if($request->has('draw')) {
            return $dataTable->render('email.send_personalised_group_email', ['step' => 3]);
        }

        $step=1;
        //reset current session data for sending group sms
        if($request->session()->has('group_email_personalised_data')) {
            $request->session()->forget('group_email_personalised_data');
        }
        if($request->session()->has('alert')) {
            $request->session()->forget('alert');
        }

        //fetch user groups
        $groups = $request->user()->groups()->orderBy('name', 'asc')->get(['name', 'id']);

        $emailtemplate = Email_templates::query()->select('template_name','template_head','template_foot')->get();
//
        //show view
        return view('email.send_personalised_group_email', [
            'step'=>$step,
            'groups' => $groups,
            'email_temp'=>$emailtemplate
        ]);
    }

    public function post_send_personalised_bulk_email(Request $request) {
        //get current user
        $user = Auth::user();
        $credit = $user->credit;

        //get current step
        $step = $request->get('step', 1);

        //process for step 1
        if($step == 1)
        {
            //validate the request
            $this->validate($request, [
                'file_upload'       => 'required|mimes:csv,txt,xlsx,xls',
                'sender'            => 'required|email',
                'subject'           => 'required',
                'schedule_date'     => 'present',
                'name'              => 'required',
                'image_upload'      => 'image'
            ]);

            $current_filename = $request->file('file_upload')->getClientOriginalName();
            $filename_splitted = explode(".", $current_filename);
            $extension = end($filename_splitted);

            $destinationPath = storage_path() . DIRECTORY_SEPARATOR. 'bulk_email' . DIRECTORY_SEPARATOR;
            $fileName = $user->username. '_'. date('YmdHis') . '.' . $extension;
            $full_filename = $destinationPath . $fileName;

            if ($request->file('file_upload')->isValid()) {
                $request->file('file_upload')->move($destinationPath, $fileName);
            } else {
                return Redirect::back()->withInput()->withErrors(array('file_upload' => 'Sorry, The file upload failed!'));
            }

            $highestRow = 0;
            $headers = [];
            $processed_email = [];
            $dupplicated_email = [];
            $price = 0.0;

            try {
                Excel::load($full_filename, function ($reader)
                use (&$highestRow, &$headers, &$processed_email, &$dupplicated_email, &$price, &$user) {
                    $objExcel = $reader->getExcel();
                    $sheet = $objExcel->getSheet(0);
                    $highestRow = $sheet->getHighestRow();
                    $highestColumn = $sheet->getHighestColumn();
                    //  Read a row of data into an array
                    $rowData = $sheet->rangeToArray('A' . 1 . ':' . $highestColumn . 1, NULL, TRUE, FALSE);
                    $row = $rowData[0];
                    foreach ($row as $header)
                        $headers[] = $header;

                    //check for duplicated
                    for ($row = 2; $row <= $highestRow; $row++)
                    {
                        try {
                            //  Read a row of data into an array
                            $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
                                NULL, TRUE, FALSE);
                            $email = $rowData[0][0];
                            $email = trim($email);
//                            if(in_array($msisdn, $processed_msisdn)) {
//                                array_push($dupplicated_msisdn, $msisdn);
//                                continue;
//                            }
                            $price += (float)$user->credit->email_price;
                            array_push($processed_email, $email);
                        } catch (\Exception $e) {

                        }
                    }
                });
            } catch (\Exception $e) {
                return Redirect::back()->withInput()->withErrors(array('file_upload' => 'Error! Your excel file is invalid!'));
            }

            // cost of sending one msg with this no_pages to one person
            $num_email = count($processed_email);

            $recipients = $num_email;

            $imgId = null;

            //update image if image exist
            if(!empty($request['image_upload'])) {
                if ($request->file('image_upload')->isValid()) {
                    $current_filename = $request->file('image_upload')->getClientOriginalName();
                    $fileMimeType = $request->file('image_upload')->getMimeType();

                    $destinationPath = storage_path() . DIRECTORY_SEPARATOR. 'uploads' . DIRECTORY_SEPARATOR;
                    $fileName = $user->username. '_' . $current_filename;
                    $request->file('image_upload')->move($destinationPath, $fileName);
                    $full_path = $destinationPath . $fileName;
                    while(1) {
                        $imgId = uniqid();
                        if(empty(SmsImage::find($imgId))) {
                            break;
                        }
                    }
                    $user->sms_images()->create([
                        'path' => $full_path,
                        'file_name' => $current_filename,
                        'mime_type' => $fileMimeType,
                        'id' => $imgId
                    ]);
                } else {
                    return Redirect::back()->withInput()->withErrors(array('image_upload' => 'Sorry, The file upload failed!'));
                }
            }

            $msg = $request->get('message_content', '');
            if(!empty($imgId)) {
                $sms_msg_url = route('sms_image', ['id'=>$imgId]);
                $msg = $msg."\n".$sms_msg_url;
            }

            //store user input in the new session data
            session(['bulk_email_personalised_data'=>[
                'phone_numbers' => $current_filename,
                'sender' => $request->get('sender'),
                'subject' => $request->get('subject'),
                'recipients' => $recipients,
                'path' => $full_filename,
                'total_price' => $price,
                'schedule_date' => Carbon::parse($request->get('schedule_date')),
                'headers' => $headers,
                'name' => $request->get('name'),
                'msg' => $msg,
                'duplicated' => count($dupplicated_email)
            ]]);
            $step=2;
        }
        //process for step 2
        else if($step==2)
        {
            //check if next button was pressed
            if($request->has('next'))
            {
                $new_msg_text = $request->get('message_content', '');
                $message = $new_msg_text.session('bulk_email_personalised_data')['msg'];
                if(empty($message)) {
                    $step=2;
                    $request->session()->flash('error_msg', 'Kindly enter the text message!');
                } else {
                    //get data for step 2
                    $price = session('bulk_email_personalised_data')['total_price'];
                    $tot_cost = $price ;

                    $num_email = session('bulk_email_personalised_data')['recipients'];

                    $curr_bal = $credit->new_bal;

                    $recipients = $num_email;
                    $total_price = $tot_cost;
                    $credit_available = $curr_bal;

                    //store user input in the new session data
                    session(['bulk_email_personalised_data'=>[
                        'phone_numbers' => session('bulk_email_personalised_data')['phone_numbers'],
                        'sender' => session('bulk_email_personalised_data')['sender'],
                        'subject' => session('bulk_email_personalised_data')['subject'],
                        'message_content' => $message,
                        'recipients' => $recipients,
                        'total_price' => $total_price,
                        'credit_available' => $credit_available,
                        'path' => session('bulk_email_personalised_data')['path'],
                        'schedule_date' => session('bulk_email_personalised_data')['schedule_date'],
                        'headers' => session('bulk_email_personalised_data')['headers'],
                        'name' => session('bulk_email_personalised_data')['name'],
                        'duplicated' => session('bulk_email_personalised_data')['duplicated'],
                    ]]);
                    $step = 3;
                }
            }
            //in case back button was pressed
            else
            {
                //go back to step 1
                $step=1;
            }
        }

        else if($step==3)
        {
            //check if next button was pressed
            if($request->has('submit'))
            {
                $sender = session('bulk_email_personalised_data')['sender'];
                $subject = session('bulk_email_personalised_data')['subject'];
                $num_email = session('bulk_email_personalised_data')['recipients'];
                $msgs = session('bulk_email_personalised_data')['message_content'];
                $path = session('bulk_email_personalised_data')['path'];
                $name = session('bulk_email_personalised_data')['name'];
                $tot_cost = session('bulk_email_personalised_data')['total_price'];

                $curr_bal = $credit->new_bal;

                if(isset(session('bulk_email_personalised_data')['schedule_date']) && !empty(session('bulk_email_personalised_data')['schedule_date'])) {
                    $sch_date = Carbon::parse(session('bulk_email_personalised_data')['schedule_date']);
                    $now = Carbon::now()->addMinutes(1);
                    $date = $now->lte($sch_date) ? $sch_date : $now;
                } else {
                    $date = Carbon::now()->addMinutes(1);
                }

                if ($curr_bal >= $tot_cost) {
                    //Create a job
                    $job = new EmailJob([
                        'username' => $user->username,
                        'sender' => $sender,
                        'message' => $msgs,
                        'subject' => $subject,
                        'type' => 'p_bulk',
                        'sched_datetime' => $date,
                        'status' => 'pending',
                        'created_by' => $user->username,
                        'file_path' => $path,
                        'name' =>$name,
                        'total_traffic' => $num_email
                    ]);

                    $user->jobs()->save($job);

                    //update audit trails
                    $user->audit_trails()->create([
                        'username' => $user->username,
                        'date' => Carbon::now()->toDateTimeString(),
                        'activity' => $user->username.' sent a personalised bulk mail to '.$num_email.' email(s)'
                    ]);

                    //send blast alert
                    $alertThreshold = intval(env('BLAST_ALERT', 1000));
                    if(intval($num_email) >= $alertThreshold) {
                        SmsTools::sendBlastAlert($user, $num_email, 'email');
                    }

                    $request->session()->flash('success', 'Your messages was successfully sent!');
                } else {
                    return Redirect::back()->withInput()->withErrors(array('error' => 'Sorry, you don\'t have enough credit to proceed!'));
                }

                //reset session
                $step=0;
                $request->session()->forget('bulk_email_personalised_data');
                if(!$request->session()->has('success') || empty(session('success')))
                    $request->session()->flash('success', 'Your contacts was successfully uploaded!');
            }
            //in case back button was pressed
            else
            {
                //go back to step 1
                $step=2;
            }
        }
        $emailtemplate = Email_templates::query()->select('template_name','template_head','template_foot')->get();

        return view('email.send_bulk_personalised_email', ['step'=>$step , 'email_temp'=>$emailtemplate]);
    }

    public function post_send_bulk_email(Request $request) {
        //get current user
        $user = Auth::user();
        $credit = $user->credit;

        //get current step
        $step = $request->get('step', 1);

        //process for step 1
        if($step == 1)
        {
            //validate the request
            $this->validate($request, [
                'file_upload' => 'required|mimes:csv,txt,xlsx,xls',
                'sender' => 'required|email',
                'subject' => 'required',
                'schedule_date' => 'present',
                'message_content' => 'required',
                'name' => 'required',
                'image_upload' => 'image'
            ]);

            $current_filename = $request->file('file_upload')->getClientOriginalName();
            $filename_splitted = explode(".", $current_filename);
            $extension = end($filename_splitted);

            $destinationPath = storage_path() . DIRECTORY_SEPARATOR. 'bulk_email' . DIRECTORY_SEPARATOR;
            $fileName = $user->username. '_'. date('YmdHis') . '.' . $extension;
            $full_filename = $destinationPath . $fileName;

            if ($request->file('file_upload')->isValid()) {
                $request->file('file_upload')->move($destinationPath, $fileName);
            } else {
                return Redirect::back()->withInput()->withErrors(array('file_upload' => 'Sorry, The file upload failed!'));
            }

            $highestRow = 0;
            $processed_email = [];
            $dupplicated_msisdn = [];
            $price = 0.0;

            try {
                Excel::load($full_filename, function ($reader)
                use (&$highestRow, &$processed_email, &$dupplicated_msisdn, &$price, &$user) {
                    $objExcel = $reader->getExcel();
                    $sheet = $objExcel->getSheet(0);
                    $highestRow = $sheet->getHighestRow();
                    $highestColumn = $sheet->getHighestColumn();

                    //check for duplicated
                    for ($row = 1; $row <= $highestRow; $row++)
                    {
                        try {
                            //  Read a row of data into an array
                            $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
                                NULL, TRUE, FALSE);
                            $email = $rowData[0][0];
                            $email = trim($email);
                            if(in_array($email, $processed_email)) {
                                array_push($dupplicated_msisdn, $email);
                                continue;
                            }
                            $price += $user->credit->email_price;
                            array_push($processed_email, $email);
                        } catch (\Exception $e) {
                            $this->error($e->getMessage());
                        }

                    }
                });
            } catch (\Exception $e) {
                throw $e;
                return Redirect::back()->withInput()->withErrors(array('file_upload' => 'Error! Your excel file is invalid!'));
            }

            //get data for step 2
            $new_msg_text = $request->get('message_content', '');

            $cost = $price;

            // cost of sending one msg with this no_pages to one person
            $nummsisdn = count($processed_email);
            // no of recepients
            $tot_cost = $cost;
            $curr_bal = $credit->new_bal;
            $recipients = $nummsisdn;
            $total_price = $tot_cost;
            $credit_available = $curr_bal;

            $imgId = null;

            //update image if image exist
            if(!empty($request['image_upload'])) {
                if ($request->file('image_upload')->isValid()) {
                    $current_filename = $request->file('image_upload')->getClientOriginalName();
                    $fileMimeType = $request->file('image_upload')->getMimeType();

                    $destinationPath = storage_path() . DIRECTORY_SEPARATOR. 'uploads' . DIRECTORY_SEPARATOR;
                    $fileName = $user->username. '_' . $current_filename;
                    $request->file('image_upload')->move($destinationPath, $fileName);
                    $full_path = $destinationPath . $fileName;
                    while(1) {
                        $imgId = uniqid();
                        if(empty(SmsImage::find($imgId))) {
                            break;
                        }
                    }
                    $user->sms_images()->create([
                        'path' => $full_path,
                        'file_name' => $current_filename,
                        'mime_type' => $fileMimeType,
                        'id' => $imgId
                    ]);
                } else {
                    return Redirect::back()->withInput()->withErrors(array('image_upload' => 'Sorry, The file upload failed!'));
                }
            }

            $msg = $new_msg_text;
            if(!empty($imgId)) {
                $sms_msg_url = route('sms_image', ['id'=>$imgId]);
                $msg = $new_msg_text." ".$sms_msg_url;
            }

            //store user input in the new session data
            session(['bulk_email_data'=>[
                'emails' => $current_filename,
                'sender' => $request->get('sender'),
                'message_content' => $msg,
                'subject' => $request->get('subject'),
                'recipients' => $recipients,
                'total_price' => $total_price,
                'credit_available' => $credit_available,
                'path' => $full_filename,
                'schedule_date' => Carbon::parse($request->get('schedule_date')),
                'name' => $request->get('name'),
                'duplicated' => count($dupplicated_msisdn)
            ]]);
            $step=2;
        }
        //process for step 2
        else if($step==2)
        {
            //check if next button was pressed
            if($request->has('submit'))
            {
                $sender = session('bulk_email_data')['sender'];
                $subject = session('bulk_email_data')['subject'];
                $nummsisdn = session('bulk_email_data')['recipients'];
                $msgs = session('bulk_email_data')['message_content'];
                $path = session('bulk_email_data')['path'];
                $name = session('bulk_email_data')['name'];
                $cost = session('bulk_email_data')['total_price'];

                $tot_cost = $cost;

                $curr_bal = $credit->new_bal;

                //remaining sms user can send

                if(isset(session('bulk_email_data')['schedule_date']) && !empty(session('bulk_email_data')['schedule_date'])) {
                    $sch_date = Carbon::parse(session('bulk_email_data')['schedule_date']);
                    $now = Carbon::now()->addMinutes(1);
                    $date = $now->lte($sch_date) ? $sch_date : $now;
                } else {
                    $date = Carbon::now()->addMinutes(1);
                }

                if ($curr_bal >= $tot_cost) {
                    //TODO: Create a job
                    $job = new EmailJob([
                        'username' => $user->username,
                        'sender' => $sender,
                        'message' => $msgs,
                        'subject' => $subject,
                        'type' => 'bulk',
                        'sched_datetime' => $date,
                        'status' => 'pending',
                        'created_by' => $user->username,
                        'file_path' => $path,
                        'name' => $name,
                        'total_traffic' => $nummsisdn
                    ]);

                    $user->jobs()->save($job);

                    //update audit trails
                    $user->audit_trails()->create([
                        'username' => $user->username,
                        'date' => Carbon::now()->toDateTimeString(),
                        'activity' => $user->username.' sent a bulk mail to '.$nummsisdn.' email address(es)'
                    ]);

                    //send blast alert
                    $alertThreshold = intval(env('BLAST_ALERT', 1000));
                    if(intval($nummsisdn) >= $alertThreshold) {
                        SmsTools::sendBlastAlert($user, $nummsisdn, 'email');
                    }

                    $request->session()->flash('success', 'Your messages was successfully sent!');
                } else {
                    return Redirect::back()->withInput()->withErrors(array('error' => 'Sorry, you don\'t have enough credit to proceed!'));
                }

                //reset session
                $step=0;
                $request->session()->forget('bulk_email_data');
                if(!$request->session()->has('success') || empty(session('success')))
                    $request->session()->flash('success', 'Your contacts was successfully uploaded!');
            }
            //in case back button was pressed
            else
            {
                //go back to step 1
                $step=1;
            }
        }
        $emailtemplate = Email_templates::query()->select('template_name','template_head','template_foot')->get();
        return view('email.send_bulk_email', ['step'=>$step , 'email_temp'=> $emailtemplate]);
    }

    public function delete_contact_from_email_group($msisdn) {

    }

    public function post_send_group_email(Request $request, TmpGroupEmailDataTable $dataTable) {
        //get current user
        $user = Auth::user();
        $credit = $user->credit;

        //get current step
        $step = $request->get('step', 1);

        //process for step 1
        if($step == 1)
        {
            //validate the request
            $this->validate($request, [
                'selected_group' => 'required',
                'sender' => 'required|email',
                'subject' => 'required',
                'schedule_date' => 'present',
                'message_content' => 'required',
                'name' => 'required',
                'image_upload' => 'image'
            ]);

            $highestRow = 0;
            $selected_groups = $request->get('selected_group');
            $group_name = '';
            $data = [];

            DB::beginTransaction();
            $user->tmp_group_emails()->delete();

            if(!empty($selected_groups))
                foreach ($selected_groups as $group_id) {
                    $group = $user->groups()->find($group_id);
                    if(!empty($group)) {
                        $group_name .= ($group->name.', ');
                        $highestRow += $group->contacts()->count();
                        $group->contacts()->chunk(5000, function($contacts)
                        use(&$user){
                            foreach ($contacts as $contact) {
                                if(empty($contact->email))
                                    continue;
                                $existing = DB::table('tmp_group_emails')->where([
                                    ['user_id', '=', $user->id],
                                    ['email', '=', $contact->email]
                                ])->first();

                                if(empty($existing) && !empty($contact->email)) {
                                    DB::table('tmp_group_emails')->insert([
                                        'user_id' => $user->id,
                                        'name' => $contact->name,
                                        'email' => $contact->email
                                    ]);
                                }
                            }
                        });
                    }
                }
            DB::commit();

            $imgId = null;

            //update image if image exist
            if(!empty($request['image_upload'])) {
                if ($request->file('image_upload')->isValid()) {
                    $current_filename = $request->file('image_upload')->getClientOriginalName();
                    $fileMimeType = $request->file('image_upload')->getMimeType();

                    $destinationPath = storage_path() . DIRECTORY_SEPARATOR. 'uploads' . DIRECTORY_SEPARATOR;
                    $fileName = $user->username. '_' . $current_filename;
                    $request->file('image_upload')->move($destinationPath, $fileName);
                    $full_path = $destinationPath . $fileName;
                    while(1) {
                        $imgId = uniqid();
                        if(empty(SmsImage::find($imgId))) {
                            break;
                        }
                    }
                    $user->sms_images()->create([
                        'path' => $full_path,
                        'file_name' => $current_filename,
                        'mime_type' => $fileMimeType,
                        'id' => $imgId
                    ]);
                } else {
                    return Redirect::back()->withInput()->withErrors(array('image_upload' => 'Sorry, The file upload failed!'));
                }
            }

            $new_msg_text = $request->get('message_content', '');
            $msg = $new_msg_text;
            if(!empty($imgId)) {
                $sms_msg_url = route('sms_image', ['id'=>$imgId]);
                $msg = $new_msg_text."\n".$sms_msg_url;
            }

            //store user input in the new session data
            session(['group_email_data'=>[
                'group_name' => $group_name,
                'sender' => $request->get('sender'),
                'subject' => $request->get('subject'),
                'message_content' => $msg,
                'groups' => $selected_groups,
                'schedule_date' => Carbon::parse($request->get('schedule_date')),
                'name' => $request->get('name'),
                'selected_group' => $request->get('selected_group')
            ]]);
            $step=2;
        }
        //process for step 2
        else if($step==2)
        {
            //check if next button was pressed
            if($request->has('next'))
            {
                $highestRow = $user->tmp_group_emails()->count();
                //check if user can send sms
                if ($highestRow>0) {
                    //do the calculation and move to step 3
                    //get data for step 2
                    $price = 0.0;
                    foreach ($user->tmp_group_emails as $tempp) {
                        $price += (float)$user->credit->email_price;
                    }
                    $cost = $price;
                    // cost of sending one msg with this no_pages to one person
                    $num_email = $highestRow;
                    $tot_cost = $cost;
                    $curr_bal = $credit->new_bal;


                    $recipients = $num_email;
                    $total_price = $tot_cost;
                    $credit_available = $curr_bal;

                    session(['group_email_data'=>[
                        'group_name' => session('group_email_data')['group_name'],
                        'sender' => session('group_email_data')['sender'],
                        'subject' => session('group_email_data')['subject'],
                        'message_content' => session('group_email_data')['message_content'],
                        'groups' => session('group_email_data')['groups'],
                        'recipients' => $recipients,
                        'total_price' => $total_price,
                        'credit_available' => $credit_available,
                        'schedule_date' => session('group_email_data')['schedule_date'],
                        'name' =>session('group_email_data')['name'],
                        'selected_group' => session('group_email_data')['selected_group'],
                    ]]);

                    //move to step 3
                    $step = 3;
                } else {
                    //prevent user from access step3
                    $request->session()->flash('error_msg', 'Kindly add some email(s)');
                    $step = 2;
                }
            }
            else if($request->has('add_msisdn_btn')) {
                $input = $request->get('add_msisdn_input');
                if(empty(trim($input))) {
                    $request->session()->flash('error_msg', 'Kindly enter the email to be added');
                }

                //validate email
                $validator = Validator::make($request->all(), [
                    'add_msisdn_input' => 'required|email',
                ]);
                if ($validator->fails()) {
                    $request->session()->flash('error_msg', 'The email address is not valid!');
                } else {

                    $tmp_email_list = explode(',', $input);
                    $added = 0;
                    if (!empty($tmp_email_list))
                        foreach ($tmp_email_list as $temp) {
                            $temp = trim($temp);
                            if (!empty($temp)) {
                                if (!empty($user->tmp_group_emails()->where('email', $temp)->first())) {
                                    $request->session()->flash('error_msg', $temp . ' already exists in the list!');
                                    break;
                                }
                                $user->tmp_group_emails()->create(['email' => $temp]);
                                $added++;
                            }
                        }
                    if ($added > 0)
                        $request->session()->flash('success_msg', $added . ' email(s) added to the list!');
                }
                $step = 2;
            }
            else if($request->has('delete_item')) {
                $input = $request->get('delete_item');
                $contact = $user->tmp_group_emails()->where('email', $input)->first();
                if(!empty($contact)) {
                    $contact->delete();
                    $request->session()->flash('success_msg', $input.' was deleted from the list!');
                } else {
                    $request->session()->flash('error_msg', $input.' not found in the list!');
                }
                $step=2;
            }
            else if($request->has('delete_selection')) {
                $selection = $request->get('selection');
                $deleted = 0;
                if(!empty($selection))
                    foreach ($selection as $email) {
                        $contact = $user->tmp_group_emails()->where('email', $email)->first();
                        if(!empty($contact)) {
                            $contact->delete();
                            $deleted++;
                        } else {
                            $request->session()->flash('error_msg', $email.' not found in the list!');
                        }
                    }
                if($deleted>0)
                    $request->session()->flash('success_msg', $deleted.' email(s) deleted from the list!');
                $step = 2;
            }
            //in case back button was pressed
            else if($request->has('back'))
            {
                //go back to step 1
                $step=1;
            }
        }
        else if($step==3)
        {
            //check if next button was pressed
            if($request->has('submit'))
            {
                $no_chars = strlen(session('group_email_data')['message_content']);
                $sender = session('group_email_data')['sender'];
                $subject = session('group_email_data')['subject'];
                $num_email = session('group_email_data')['recipients'];
                $msgs = session('group_email_data')['message_content'];
                $name = session('group_email_data')['name'];
                $group_ids = implode(",", session('group_email_data')['selected_group']);
                $cost = session('group_email_data')['total_price'];
                $tot_cost = $cost;

                $curr_bal = $credit->new_bal;

                //remaining sms user can send

                if(isset(session('group_email_data')['schedule_date']) && !empty(session('group_email_data')['schedule_date'])) {
                    $sch_date = Carbon::parse(session('group_email_data')['schedule_date']);
                    $now = Carbon::now()->addMinutes(1);
                    $date = $now->lte($sch_date) ? $sch_date : $now;
                } else {
                    $date = Carbon::now()->addMinutes(1);
                }

                if ($curr_bal >= $tot_cost) {
                    //copy msisdn to excel file and add it to the pending job list
                    $destinationPath = storage_path('bulk_email');
                    $fileName = $user->username. '_'. date('YmdHis');

                    try {
                        $res = Excel::create($fileName, function($excel) use (&$user) {
                            // Set the title
                            $excel->setTitle('GROUP SMS Details');
                            // Chain the setters
                            $excel->setCreator('Alphonse')->setCompany('Npontu');
                            $excel->setDescription('Send Group SMS Details');

                            $excel->sheet('Msisdn', function ($sheet) use (&$user) {
                                $sheet->setOrientation('landscape');
                                $i = 0;
                                DB::beginTransaction();
                                $data = $user->tmp_group_emails()->get();
                                foreach ($data as $dat) {
                                    $i++;
                                    $sheet->appendRow($i, [$dat->email]);
                                }
                                $user->tmp_group_emails()->delete();
                                DB::commit();
                            });
                        })->store('xls', $destinationPath, true);

                    } catch (\Exception $e) {
                        $request->session()->flash('error_msg', 'Sorry, an error occurred while scheduling the blast!');
                        Log::error($e->getMessage());
                        $step = 3;
                        return view('email.send_group_email', ['step' => $step]);
                    }
                    //Create a job
                    $job = new EmailJob([
                        'username' => $user->username,
                        'sender' => $sender,
                        'subject' => $subject,
                        'message' => $msgs,
                        'sched_datetime' => $date,
                        'type' => 'group',
                        'status' => 'pending',
                        'created_by' => $user->username,
                        'file_path' => $res['full'],
                        'name' => $name,
                        'total_traffic' => $num_email,
                        'group_ids' => $group_ids
                    ]);

                    $user->jobs()->save($job);

                    //update audit trails
                    $user->audit_trails()->create([
                        'username' => $user->username,
                        'date' => Carbon::now()->toDateTimeString(),
                        'activity' => $user->username.' sent a group email to '.$num_email.' email(s)'
                    ]);

                    //send blast alert
                    $alertThreshold = intval(env('BLAST_ALERT', 1000));
                    if(intval($num_email) >= $alertThreshold) {
                        SmsTools::sendBlastAlert($user, $num_email, 'email');
                    }

                    $request->session()->flash('success', 'Your messages was successfully sent!');
                } else {
                    $request->session()->flash('error_msg', 'Sorry, you don\'t have enough credit to proceed!');
                }

                //reset session
                $step=0;
                $request->session()->forget('group_email_data');
                if(!$request->session()->has('success') || empty(session('success')))
                    $request->session()->flash('success', 'Your contacts was successfully uploaded!');
            }
            //in case back button was pressed
            else
            {
                //go back to step 1
                $step=2;
            }
        }


        if($step==1) {
            //fetch user groups
            $groups = $request->user()->groups()->orderBy('name', 'asc')->get(['name', 'id']);
            return view('email.send_group_email', ['step' => $step, 'groups'=>$groups]);
        }
        else if($step==2) {
            return $dataTable->render('email.send_group_email', ['step'=>$step]);
        } else {
            $emailtemplate = Email_templates::query()->select('template_name','template_head','template_foot')->get();
            return view('email.send_group_email', ['step' => $step , 'email_temp'=> $emailtemplate]);
        }
    }

    public function post_send_personalised_group_email(Request $request, TmpGroupEmailDataTable $dataTable) {
        //get current user
        $user = Auth::user();
        $credit = $user->credit;

        //get current step
        $step = $request->get('step', 1);

        //process for step 1
        if($step == 1)
        {
            //validate the request
            $this->validate($request, [
                'selected_group' => 'required',
                'sender' => 'required|email',
                'subject' => 'required',
                'schedule_date' => 'present',
                'name' => 'required',
                'image_upload' => 'image'
            ]);

            $highestRow = 0;
            $selected_groups = $request->get('selected_group');
            $group_name = '';
            $counter = 0;

            DB::beginTransaction();
            $user->tmp_group_emails()->delete();

            if(!empty($selected_groups))
            foreach ($selected_groups as $group_id) {
                $group = $user->groups()->find($group_id);
                if(!empty($group)) {
                    $group_name .= ($group->name.', ');
                    $highestRow += $group->contacts()->count();
                    $group->contacts()->chunk(5000, function($contacts)
                            use(&$user, &$counter){
                        foreach ($contacts as $contact) {
                            if(empty($contact->email))
                                continue;
                            $existing = DB::table('tmp_group_emails')->where([
                                ['user_id', '=', $user->id],
                                ['email', '=', $contact->email]
                            ])->first();

                            if(empty($existing)) {
                                $counter++;
                                DB::table('tmp_group_emails')->insert([
                                    'user_id' => $user->id,
                                    'name' => $contact->name,
                                    'email' => $contact->email
                                ]);
                            }
                        }
                    });
                }
            }
            DB::commit();

            $imgId = null;

            //update image if image exist
            if(!empty($request['image_upload'])) {
                if ($request->file('image_upload')->isValid()) {
                    $current_filename = $request->file('image_upload')->getClientOriginalName();
                    $fileMimeType = $request->file('image_upload')->getMimeType();

                    $destinationPath = storage_path() . DIRECTORY_SEPARATOR. 'uploads' . DIRECTORY_SEPARATOR;
                    $fileName = $user->username. '_' . $current_filename;
                    $request->file('image_upload')->move($destinationPath, $fileName);
                    $full_path = $destinationPath . $fileName;
                    while(1) {
                        $imgId = uniqid();
                        if(empty(SmsImage::find($imgId))) {
                            break;
                        }
                    }
                    $user->sms_images()->create([
                        'path' => $full_path,
                        'file_name' => $current_filename,
                        'mime_type' => $fileMimeType,
                        'id' => $imgId
                    ]);
                } else {
                    return Redirect::back()->withInput()->withErrors(array('image_upload' => 'Sorry, The file upload failed!'));
                }
            }

            $new_msg_text = $request->get('message_content', '');
            $msg = $new_msg_text;
            if(!empty($imgId)) {
                $sms_msg_url = route('sms_image', ['id'=>$imgId]);
                $msg = $new_msg_text."\n".$sms_msg_url;
            }

            //store user input in the new session data
            session(['group_email_personalised_data' => [
                'group_name' => $group_name,
                'sender' => $request->get('sender'),
                'subject' => $request->get('subject'),
                'groups' => $selected_groups,
                'schedule_date' => Carbon::parse($request->get('schedule_date')),
                'name' => $request->get('name'),
                'msg' => $msg,
                'recipients' => $counter,
                'selected_group' => $request->get('selected_group')
            ]]);
            $step=2;
        }
        //process for step 2
        else if($step==2)
        {
            //check if next button was pressed
            if($request->has('next'))
            {
                $new_msg_text = $request->get('message_content', '');
                $message = $new_msg_text.session('group_email_personalised_data')['msg'];
                if(empty($message)) {
                    $step=2;
                    $request->session()->flash('error_msg', 'Kindly enter the text message!');
                } else {
                    //get data for step 2
                    // cost of sending one msg with this no_pages to one person
                    $num_email = session('group_email_personalised_data')['recipients'];
                    // no of recepients


                    $curr_bal = $credit->new_bal;

                    $recipients = $num_email;

                    $credit_available = $curr_bal;

                    //store user input in the new session data
                    session(['group_email_personalised_data'=>[
                        'group_name' => session('group_email_personalised_data')['group_name'],
                        'sender' => session('group_email_personalised_data')['sender'],
                        'subject' => session('group_email_personalised_data')['subject'],
                        'message_content' => $message,
//                        'price_per_email' => $price_per_email,
                        'recipients' => $recipients,
                        'total_price' => 0,
                        'credit_available' => $credit_available,
                        'groups' => session('group_email_personalised_data')['groups'],
                        'schedule_date' => session('group_email_personalised_data')['schedule_date'],
                        'name' => session('group_email_personalised_data')['name'],
                        'selected_group' => session('group_email_personalised_data')['selected_group'],
                    ]]);
                    $step = 3;
                }
            }
            //in case back button was pressed
            else
            {
                //go back to step 1
                $step=1;
            }
        }

        //process for step 2
        else if($step==3)
        {
            //check if next button was pressed
            if($request->has('next'))
            {
                $highestRow = $user->tmp_group_emails()->count();
                //check if user can send sms
                if ($highestRow>0) {
                    //do the calculation and move to step 3
                    //get data for step 2
                    $total_price = 1;
                    $price = 0.0;
                    foreach ($user->tmp_group_emails as $tempp) {
                        $price += (float)$user->credit->email_price;
                    }

                    // cost of sending one msg with this no_pages to one person
                    $num_email = $highestRow;
                    // no of recepients
                    $tot_cost = $total_price * $price;

                    $curr_bal = $credit->new_bal;

                    $recipients = $num_email;
                    $credit_available = $curr_bal;

                    session(['group_email_personalised_data'=>[
                        'group_name' => session('group_email_personalised_data')['group_name'],
                        'sender' => session('group_email_personalised_data')['sender'],
                        'subject' => session('group_email_personalised_data')['subject'],
                        'message_content' => session('group_email_personalised_data')['message_content'],
                        'groups' => session('group_email_personalised_data')['groups'],
                        'recipients' => $recipients,
                        'total_price' => $tot_cost,
                        'credit_available' => $credit_available,
                        'schedule_date' => session('group_email_personalised_data')['schedule_date'],
                        'name' => session('group_email_personalised_data')['name'],
                        'selected_group' => session('group_email_personalised_data')['selected_group'],
                    ]]);

                    //move to step 3
                    $step = 4;
                } else {
                    //prevent user from access step3
                    $request->session()->flash('error_msg', 'Kindly add some email(s)');
                    $step = 3;
                }
            }
            else if($request->has('add_msisdn_btn')) {
                $input = $request->get('add_msisdn_input');
                if(empty(trim($input))) {
                    $request->session()->flash('error_msg', 'Kindly enter the email to be added');
                }

                //validate email
                $validator = Validator::make($request->all(), [
                    'add_msisdn_input' => 'required|email',
                ]);
                if ($validator->fails()) {
                    $request->session()->flash('error_msg', 'The email address is not valid!');
                } else {

                    $tmp_email_list = explode(',', $input);
                    $added = 0;
                    if (!empty($tmp_email_list))
                        foreach ($tmp_email_list as $temp) {
                            $temp = trim($temp);
                            if (!empty($temp)) {
                                if (!empty($user->tmp_group_emails()->where('email', $temp)->first())) {
                                    $request->session()->flash('error_msg', $temp . ' already exists in the list!');
                                    break;
                                }
                                $user->tmp_group_emails()->create(['email' => $temp]);
                                $added++;
                            }
                        }
                    if ($added > 0)
                        $request->session()->flash('success_msg', $added . ' email added to the list!');
                }
                $step=3;
            }
            else if($request->has('delete_item')) {
                $input = $request->get('delete_item');
                $contact = $user->tmp_group_emails()->where('email', $input)->first();
                if(!empty($contact)) {
                    $contact->delete();
                    $request->session()->flash('success_msg', $input.' was deleted from the list!');
                } else {
                    $request->session()->flash('error_msg', $input.' not found in the list!');
                }
                $step=3;
            }
            else if($request->has('delete_selection')) {
                $selection = $request->get('selection');
                $deleted = 0;
                if(!empty($selection))
                foreach ($selection as $msisdn) {
                    $contact = $user->tmp_group_emails()->where('email', $msisdn)->first();
                    if(!empty($contact)) {
                        $contact->delete();
                        $deleted++;
                    } else {
                        $request->session()->flash('error_msg', $msisdn.' not found in the list!');
                    }
                }
                if($deleted>0)
                    $request->session()->flash('success_msg', $deleted.' email deleted from the list!');
                $step = 3;
            }
            //in case back button was pressed
            else if($request->has('back'))
            {
                //go back to step 1
                $step=2;
            }
        }
        else if($step==4)
        {
            //check if next button was pressed
            if($request->has('submit'))
            {
                $no_chars = strlen(session('group_email_personalised_data')['message_content']);
                $sender = session('group_email_personalised_data')['sender'];
                $subject = session('group_email_personalised_data')['subject'];
                $num_email = session('group_email_personalised_data')['recipients'];
                $msgs = session('group_email_personalised_data')['message_content'];
                $total_price = session('group_email_personalised_data')['total_price'];
                $name = session('group_email_personalised_data')['name'];
                $group_ids = implode(",", session('group_email_personalised_data')['selected_group']);

                $tot_cost = $total_price;

                $curr_bal = $credit->new_bal;

                //remaining sms user can send

                if(isset(session('group_email_personalised_data')['schedule_date']) && !empty(session('group_email_personalised_data')['schedule_date'])) {
                    $sch_date = Carbon::parse(session('group_email_personalised_data')['schedule_date']);
                    $now = Carbon::now()->addMinutes(1);
                    $date = $now->lte($sch_date) ? $sch_date : $now;
                } else {
                    $date = Carbon::now()->addMinutes(1);
                }

                if ($curr_bal >= $tot_cost) {
                    //copy msisdn to excel file and add it to the pending job list
                    $destinationPath = storage_path('bulk_email');
                    $fileName = $user->username. '_'. date('YmdHis');

                    try {
                        $res = Excel::create($fileName, function($excel) use (&$user) {
                            // Set the title
                            $excel->setTitle('GROUP SMS Details');
                            // Chain the setters
                            $excel->setCreator('Alphonse')->setCompany('Npontu');
                            $excel->setDescription('Send Group SMS Details');

                            $excel->sheet('Email', function ($sheet) use (&$user) {
                                $sheet->setOrientation('landscape');
                                $i = 1;
                                DB::beginTransaction();
                                $data = $user->tmp_group_emails()->get();
                                $sheet->appendRow($i, ['Email', 'Name']);
                                foreach ($data as $dat) {
                                    $i++;
                                    $sheet->appendRow($i, [$dat->email, empty($dat->name) ? '': $dat->name]);
                                }
                                $user->tmp_group_emails()->delete();
                                DB::commit();
                            });
                        })->store('xls', $destinationPath, true);

                    } catch (\Exception $e) {
                        $request->session()->flash('error_msg', 'Sorry, an error occurred while scheduling the blast!');
                        Log::error($e->getMessage());
                        $step = 4;
                        return view('email.send_personalised_group_email', ['step' => $step]);
                    }
                    //Create a job
                    $job = new EmailJob([
                        'username' => $user->username,
                        'sender' => $sender,
                        'message' => $msgs,
                        'subject' => $subject,
                        'sched_datetime' => $date,
                        'type' => 'p_group',
                        'status' => 'pending',
                        'created_by' => $user->username,
                        'file_path' => $res['full'],
                        'name' => $name,
                        'total_traffic' => $num_email,
                        'group_ids' => $group_ids
                    ]);

                    $user->jobs()->save($job);

                    //update audit trails
                    $user->audit_trails()->create([
                        'username' => $user->username,
                        'date' => Carbon::now()->toDateTimeString(),
                        'activity' => $user->username.' sent a personalised group mail to '.$num_email.' email(s)'
                    ]);

                    //send blast alert
                    $alertThreshold = intval(env('BLAST_ALERT', 1000));
                    if(intval($num_email) >= $alertThreshold) {
                        SmsTools::sendBlastAlert($user, $num_email, 'email');
                    }

                    $request->session()->flash('success', 'Your messages was successfully sent!');
                } else {
                    $request->session()->flash('error_msg', 'Sorry, you don\'t have enough credit to proceed!');
                }

                //reset session
                $step=0;
                $request->session()->forget('group_email_personalised_data');
                if(!$request->session()->has('success') || empty(session('success')))
                    $request->session()->flash('success', 'Your contacts was successfully uploaded!');
            }
            //in case back button was pressed
            else
            {
                //go back to step 2
                $step=3;
            }
        }

        if($step==1) {
            //fetch user groups
            $groups = $request->user()->groups()->orderBy('name', 'asc')->get(['name', 'id']);
            $emailtemplate = Email_templates::query()->select('template_name','template_head','template_foot')->get();
            return view('email.send_personalised_group_email', ['step' => $step, 'groups'=>$groups,'email_temp'=>$emailtemplate]);
        }
        else if($step==3)
        {
            return $dataTable->render('email.send_personalised_group_email', ['step'=>$step]);
        } else {
            $emailtemplate = Email_templates::query()->select('template_name','template_head','template_foot')->get();

            return view('email.send_personalised_group_email', ['step' => $step, 'email_temp'=>$emailtemplate]);
        }
    }

    public function get_image_for_image($id) {
        $img = SmsImage::findOrFail($id);
        $mime_type = $img->mime_type;
        return Response::download($img->path, $img->file_name, ['Content-Type: '.$mime_type]);
    }

    public static function send_email($msisdn, $msgs)
    {
        $should_send_email = true; // bug-fix

        if($should_send_email && !empty(trim($msisdn))) {
            $msisdn     = self::format_phone_number($msisdn);
            $senderId   = 'Deywuro';
            $username   = 'aamalan';
            $password   = '123456';

            try {
                $client = new Client();
                $response = $client->request('GET', 'http://api.deywuro.com/bulksms', [
                    'query' => [
                        'username' => $username,
                        'password' => $password,
                        'type' => '0',
                        'dlr' => '1',
                        'destination' => $msisdn,
                        'source' => $senderId,
                        'message' => $msgs
                    ]
                ]);
                //$body = $response->getBody();
            } catch (\Exception $e) {}
        }
    }

    public static function format_phone_number($phoneNumber){
        $phoneNumber = trim($phoneNumber);
        if(strlen($phoneNumber)==9 && !starts_with($phoneNumber, '0')) {
            return '233'.$phoneNumber;
        }
        if(strlen($phoneNumber)==10 && starts_with($phoneNumber, '0')) {
            return '233'.substr($phoneNumber, 1);
        }
        return $phoneNumber;
    }
}
