<?php

/** @noinspection ALL */

namespace App\Http\Controllers;

use App\AppTicket;
use App\AuditTrail;
use App\CompanyEmail;
use App\CompanyStatus;
use App\CompanyTrialMode;
use App\CreditHistory;
use App\DataTables\AllSenderIDDataTable;
use App\DataTables\CreditHistoryDataTable;
use App\DynamicUser;
use App\EmailLog;
use App\Otp;
use App\SavedMessage;
use App\SocialMediaCredit;
use App\SocialPaymentHistory;
use App\Tools\SmsTools;
use App\User;
use App\UserSenderId;
use Carbon\Carbon;
use Facebook\Exceptions\FacebookSDKException;
use Facebook\Facebook;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use PDF;

class DashboardController extends Controller
{
    //    public function __construct()
    //    {
    //        $this->middleware('paidInitialDebit')->except('logout');
    //    }

    public function verify($code)
    {
        $check = CompanyStatus::query()->where('r_code', $code)->first();

        if (!empty($check)):
            $exposed = (object) [
                'status' => $check->status,
                'comment' => $check->comment,
            ];
            return response()->json($exposed);
        else:
            return 'INVALID REQUEST CODE';
        endif;
    }

    private function get_weekly_start_day()
    {
        $date = Carbon::now()->setTime(0, 0, 0);
        while (!$date->isMonday()) {
            $date = $date->addDays(-1);
        }
        return $date;
    }

    private function get_weekly_end_day()
    {
        $date = Carbon::now()->setTime(23, 59, 59);
        while (!$date->isSunday()) {
            $date = $date->addDays(1);
        }
        return $date;
    }

    public function newPurchase()
    {

        $_enb = false;
        $_usr = \auth()->user();



        return view('newPurchase', [
            'user' => $_usr,

        ]);
    }

    public function newPurchaseReseller()
    {

        $_enb = false;
        $_usr = \auth()->user();



        return view('reseller.newPurchase', [
            'user' => $_usr,
        ]);
    }

    public function index()
    {

        $_enb = false;
        $_usr = \auth()->user();

        //        return auth()->user()->getReseller()->company->name;

        if ($_usr->created_by == "npontu") {
            $_enb = true;
        }

        $role = auth()->user()->role->name;
        if (strtolower($role) !== 'user')
            if (strtolower($role) == 'admin')
                return redirect()->route('admin.main_route');
            else
                return redirect()->route('reseller.main_route');



        //            dd(auth()->user()->can('view-report-otp'));
        //            dd(auth()->user()->can('manage-contacts'));
        return view('NewUI.dashboard');
    }

    public function email_index()
    {
        return view('welcome_email');
    }

    public function voice_index()
    {
        return view('welcome_voice');
    }

    public function get_user_log_summary(Request $request)
    {
        $user = Auth::user();

        $date = Carbon::now();
        $from_date = Carbon::parse($date->toDateString());
        $to_date = clone $from_date;
        $to_date = Carbon::parse($to_date->addDays(1)->addSeconds(-1));
        $type = $request['type'];

        if ($type == 'month') {
            $from_date = $from_date->setDate($from_date->year, $from_date->month, 1);
            $to_date = Carbon::parse($from_date->copy()->addMonth()->addSeconds(-1));
            $dash_title = 'Monthly Dashboard';
        } else if ($type == 'week') {
            $from_date = $this->get_weekly_start_day();
            $to_date = $this->get_weekly_end_day();
            $dash_title = 'Weekly Dashboard';
        } else {
            $date = $this->get_date_by_day_name($type);
            $from_date->setDate($date->year, $date->month, $date->day);
            $to_date->setDate($date->year, $date->month, $date->day);
            $dash_title = ucfirst($this->get_day_full_name($type)) . ' \'s Dashboard';
        }
        if ($type == null) {

            $date = Carbon::now();
            $from_date->setDate($date->year, $date->month, $date->day);
            $to_date->setDate($date->year, $date->month, $date->day);
            $dash_title = ucfirst($type) . 'Today Dashboard';
        }

        $data = DB::table('logs')->select(DB::raw('logs.status, count(*) as total'))
            ->where('user_id', '=', $user->id)
            ->whereBetween('submit_date', [$from_date, $to_date])
            ->groupBy('status')
            ->get();

        $tempArray = [];
        foreach ($data as $dat) {
            $status = str_replace("\n", "", $dat->status);
            $total = $dat->total;
            $tempArray["{$status}"] = $total;
        }

        $total_sms_sent = $user->logs()->whereBetween('submit_date', [
            $from_date->toDateTimeString(),
            $to_date->toDateTimeString()
        ])->count();

        //        dd($tempArray);

        $total_sms_delivered = isset($tempArray['DELIVRD']) ? $tempArray['DELIVRD'] : 0;
        $total_sms_ack = isset($tempArray['ACK/']) ? $tempArray['ACK/'] : 0;
        $total_sms_undelivered = isset($tempArray['UNDELIV']) ? $tempArray['UNDELIV'] : 0;
        $total_sms_expired = isset($tempArray['EXPIRED']) ? $tempArray['EXPIRED'] : 0;


        return [
            'dash_title' => $dash_title,
            'total_sms_sent' => $total_sms_sent,
            'total_sms_delivered' => $total_sms_delivered,
            'total_sms_ack' => $total_sms_ack,
            'total_sms_undelivered' => $total_sms_undelivered,
            'total_sms_expired' => $total_sms_expired,
            'total_balance' => $user->credit->new_bal,
            'total_balance' => $user->credit->currency == 'CFA' ? SmsTools::round_currency(($user->credit->new_bal * 92.32)) :
                SmsTools::round_currency($user->credit->new_bal)
        ];
    }

    public function get_email_log_summary(Request $request)
    {
        $user = Auth::user();

        $date = Carbon::now();
        $from_date = Carbon::parse($date->toDateString());
        $to_date = clone $from_date;
        $to_date = Carbon::parse($to_date->addDays(1)->addSeconds(-1));
        $type = $request['type'];

        if ($type == 'month') {
            $from_date = $from_date->setDate($from_date->year, $from_date->month, 1);
            $to_date = Carbon::parse($from_date->copy()->addMonth()->addSeconds(-1));
            $dash_title = 'Monthly Dashboard';
        } else if ($type == 'week') {
            $from_date = $this->get_weekly_start_day();
            $to_date = $this->get_weekly_end_day();
            $dash_title = 'Weekly Dashboard';
        } else {
            $date = $this->get_date_by_day_name($type);
            $from_date->setDate($date->year, $date->month, $date->day);
            $to_date->setDate($date->year, $date->month, $date->day);
            $dash_title = ucfirst($this->get_day_full_name($type)) . ' \'s Dashboard';
        }
        if ($type == null) {
            $date = Carbon::now();
            $from_date->setDate($date->year, $date->month, $date->day);
            $to_date->setDate($date->year, $date->month, $date->day);
            $dash_title = ucfirst($type) . 'Today Dashboard';
        }

        $data = EmailLog::select(DB::raw('email_logs.status, count(*) as total'))
            ->where('user_id', '=', $user->id)
            ->whereBetween('submit_date', [$from_date, $to_date])
            ->groupBy('status')->get();

        $tempArray = [];

        foreach ($data as $dat) {
            $status = strtoupper($dat->status);
            $total = $dat->total;
            $tempArray["{$status}"] = $total;
        }

        $total_sms_sent = $user->email_logs()->whereBetween('submit_date', [
            $from_date->toDateTimeString(),
            $to_date->toDateTimeString()
        ])->count();

        //init
        $total_sms_delivered = $total_sms_ack = $total_sms_rejected = $total_sms_failed = 0;

        //process
        $total_sms_delivered += isset($tempArray['DELIVERED']) ? $tempArray['DELIVERED'] : 0;
        $total_sms_delivered += isset($tempArray['OPENED']) ? $tempArray['OPENED'] : 0;
        $total_sms_delivered += isset($tempArray['COMPLAINED']) ? $tempArray['COMPLAINED'] : 0;
        $total_sms_ack += isset($tempArray['SENT']) ? $tempArray['SENT'] : 0;
        $total_sms_ack += isset($tempArray['ACCEPTED']) ? $tempArray['ACCEPTED'] : 0;
        $total_sms_rejected += isset($tempArray['REJECTED']) ? $tempArray['REJECTED'] : 0;
        $total_sms_failed += isset($tempArray['FAILED']) ? $tempArray['FAILED'] : 0;

        return [
            'dash_title' => $dash_title,
            'total_sms_sent' => $total_sms_sent,
            'total_sms_delivered' => $total_sms_delivered,
            'total_sms_ack' => $total_sms_ack,
            'total_sms_rejected' => $total_sms_rejected,
            'total_sms_failed' => $total_sms_failed,
            'total_balance' => $user->credit->currency == 'CFA' ? SmsTools::round_currency(($user->credit->new_bal * 92.32)) :
                SmsTools::round_currency($user->credit->new_bal)
        ];
    }

    public function get_performance_for_comparison() {}

    private function get_date_by_day_name($day_name)
    {
        $now = Carbon::now()->addDays(-1);
        switch ($day_name) {
            case 'sun':
                while (!$now->isSunday()) {
                    $now = $now->addDays(-1);
                }
                return $now;
            case 'mon':
                while (!$now->isMonday()) {
                    $now = $now->addDays(-1);
                }
                return $now;
            case 'tue':
                while (!$now->isTuesday()) {
                    $now = $now->addDays(-1);
                }
                return $now;
            case 'wed':
                while (!$now->isWednesday()) {
                    $now = $now->addDays(-1);
                }
                return $now;
            case 'thu':
                while (!$now->isThursday()) {
                    $now = $now->addDays(-1);
                }
                return $now;
            case 'fri':
                while (!$now->isFriday()) {
                    $now = $now->addDays(-1);
                }
                return $now;
            case 'sat':
                while (!$now->isSaturday()) {
                    $now = $now->addDays(-1);
                }
                return $now;
            default:
                return $now;
        }
    }

    private function get_day_name(Carbon $date)
    {
        if ($date->isMonday()) {
            return "Mon";
        }
        if ($date->isTuesday()) {
            return "Tue";
        }
        if ($date->isWednesday()) {
            return "Wed";
        }
        if ($date->isThursday()) {
            return "Thu";
        }
        if ($date->isFriday()) {
            return "Fri";
        }
        if ($date->isSaturday()) {
            return "Sat";
        }
        if ($date->isSunday()) {
            return "Sun";
        }
        return "Unknown";
    }

    private function get_day_full_name($day)
    {
        $day = strtolower($day);

        switch ($day) {
            case 'sun':
                return 'Sunday';
                break;
            case 'mon':
                return 'Monday';
                break;
            case 'tue':
                return 'Tuesday';
                break;
            case 'wed':
                return 'Wednesday';
                break;
            case 'thu':
                return 'Thursday';
                break;
            case 'fri':
                return 'Friday';
                break;
            case 'sat':
                return 'Saturday';
                break;
            default:
                return 'N / A';
                break;
        }
    }

    public function get_traffic_performance_data(Request $request)
    {


        $returnvalue = [];
        $returnvalue[] = ['Count', 'Delivered', 'Undelivered', 'Acknowledged', 'Expired'];
        $type = $request['type'];
        $user = Auth::user();

        //        dd($user->username);


        if ($type != 'month') {
            //process for day of week
            $data = DB::select("select
         LEFT(submit_date,10) AS sentAt,
         `status` as stat,
         count(username) as t
        from logs
        where username=?
        and (submit_date between DATE_SUB(CURDATE(),INTERVAL 7 DAY)  and DATE_ADD(CURDATE(), INTERVAL 1 DAY))
        GROUP BY sentAt,stat
        ORDER BY sentAt", [$user->username]);

            $main = [];
            $cdate = '';
            $tempArray = [];
            $prevRecord = [];

            foreach ($data as $dat) {
                $status = str_replace("\n", "", $dat->stat);
                //                $status = $dat->stat;
                $total = $dat->t;
                $tempArray["{$status}"] = $total;
                if ($cdate != $dat->sentAt) {
                    if (!empty($cdate)) {
                        $main["$cdate"] = $prevRecord;
                        $tempArray = ["{$status}" => $total];
                    }

                    $cdate = $dat->sentAt;
                }
                $prevRecord = $tempArray;
            }
            $main["$cdate"] = $prevRecord;

            foreach ($main as $key => $tempArray) {
                $returnvalue[] = [
                    $this->get_day_name(Carbon::parse($key)),
                    isset($tempArray['DELIVRD']) ? (int)$tempArray['DELIVRD'] : 0,
                    isset($tempArray['UNDELIV']) ? (int)$tempArray['UNDELIV'] : 0,
                    isset($tempArray['ACK']) ? (int)$tempArray['ACK'] : 0,
                    isset($tempArray['EXPIRED']) ? (int)$tempArray['EXPIRED'] : 0
                ];
            }
        } else {
            //process for month
            //            dd()
            $now = Carbon::now();
            for ($i = 1; $i <= 5; $i++) {
                $to_date = SmsTools::get_end_of_week($now->year, $now->month, $i);
                $from_date = SmsTools::get_start_of_week($to_date);

                $data = DB::select('select `status`, count(*) as total from `logs` where `user_id`=? AND `submit_date` between ? and ? GROUP BY `status`', [
                    Auth::user()->id,
                    $from_date->toDateTimeString(),
                    $to_date->toDateTimeString()
                ]);
                $tempArray = [];
                foreach ($data as $dat) {
                    $status = str_replace("\n", "", $dat->status);
                    $total = $dat->total;
                    $tempArray["{$status}"] = $total;
                }
                $returnvalue[] = [
                    'Week ' . $i,
                    isset($tempArray['DELIVRD']) ? (int)$tempArray['DELIVRD'] : 0,
                    isset($tempArray['UNDELIV']) ? (int)$tempArray['UNDELIV'] : 0,
                    isset($tempArray['ACK/']) ? (int)$tempArray['ACK/'] : 0,
                    isset($tempArray['EXPIRED']) ? (int)$tempArray['EXPIRED'] : 0
                ];
            }
        }
        return $returnvalue;
    }

    public function get_email_traffic_performance(Request $request)
    {
        $returnvalue = [];
        $returnvalue[] = ['Count', 'Delivered', 'Rejected', 'Acknowledged', 'Failed'];
        $type = $request['type'];
        $user = Auth::user();

        if ($type != 'month') {
            //process for day of week
            $data = DB::select("select
         LEFT(submit_date,10) AS sentAt,
         `status` as stat,
         count(username) as t
        from email_logs
        where username=?
        and (submit_date between DATE_SUB(CURDATE(),INTERVAL 7 DAY)  and DATE_ADD(CURDATE(), INTERVAL 1 DAY))
        GROUP BY sentAt,stat", [$user->username]);

            $main = [];
            $cdate = '';
            $tempArray = [];
            foreach ($data as $dat) {
                $status = strtoupper($dat->stat);
                $total = $dat->t;
                $tempArray["{$status}"] = $total;
                if ($cdate != $dat->sentAt) {
                    if (!empty($cdate)) {
                        $main["$cdate"] = $tempArray;
                        $tempArray = [];
                    }
                    $cdate = $dat->sentAt;
                }
            }
            $main["$cdate"] = $tempArray;

            foreach ($main as $key => $tempArray) {
                //init
                $total_sms_delivered = $total_sms_ack = $total_sms_rejected = $total_sms_failed = 0;
                //process
                $total_sms_delivered += isset($tempArray['DELIVERED']) ? $tempArray['DELIVERED'] : 0;
                $total_sms_delivered += isset($tempArray['OPENED']) ? $tempArray['OPENED'] : 0;
                $total_sms_delivered += isset($tempArray['COMPLAINED']) ? $tempArray['COMPLAINED'] : 0;
                $total_sms_ack += isset($tempArray['SENT']) ? $tempArray['SENT'] : 0;
                $total_sms_ack += isset($tempArray['ACCEPTED']) ? $tempArray['ACCEPTED'] : 0;
                $total_sms_rejected += isset($tempArray['REJECTED']) ? $tempArray['REJECTED'] : 0;
                $total_sms_failed += isset($tempArray['FAILED']) ? $tempArray['FAILED'] : 0;

                $returnvalue[] = [
                    $this->get_day_name(Carbon::parse($key)),
                    $total_sms_delivered,
                    $total_sms_rejected,
                    $total_sms_ack,
                    $total_sms_failed
                ];
            }
        } else {
            //process for month
            $now = Carbon::now();
            for ($i = 1; $i <= 5; $i++) {
                $to_date = SmsTools::get_end_of_week($now->year, $now->month, $i);
                $from_date = SmsTools::get_start_of_week($to_date);

                $data = DB::select('select `status`, count(*) as total from `email_logs` where `user_id`=? AND `submit_date` between ? and ? GROUP BY `status`', [
                    Auth::user()->id,
                    $from_date->toDateTimeString(),
                    $to_date->toDateTimeString()
                ]);
                $tempArray = [];
                foreach ($data as $dat) {
                    $status = $dat->status;
                    $total = $dat->total;
                    $tempArray["{$status}"] = $total;
                }
                //process
                $total_sms_delivered = $total_sms_ack = $total_sms_rejected = $total_sms_failed = 0;
                $total_sms_delivered += isset($tempArray['DELIVERED']) ? $tempArray['DELIVERED'] : 0;
                $total_sms_delivered += isset($tempArray['OPENED']) ? $tempArray['OPENED'] : 0;
                $total_sms_delivered += isset($tempArray['COMPLAINED']) ? $tempArray['COMPLAINED'] : 0;
                $total_sms_ack += isset($tempArray['SENT']) ? $tempArray['SENT'] : 0;
                $total_sms_ack += isset($tempArray['ACCEPTED']) ? $tempArray['ACCEPTED'] : 0;
                $total_sms_rejected += isset($tempArray['REJECTED']) ? $tempArray['REJECTED'] : 0;
                $total_sms_failed += isset($tempArray['FAILED']) ? $tempArray['FAILED'] : 0;

                $returnvalue[] = [
                    'Week ' . $i,
                    $total_sms_delivered,
                    $total_sms_rejected,
                    $total_sms_ack,
                    $total_sms_failed
                ];
            }
        }

        return $returnvalue;
    }

    public function get_user_picture($id)
    {
        $record = User::findOrFail($id);
        if (!empty($record->picture)) {

            $pic = Image::make($record->picture->picture);
            $response = Response::make($pic->encode('jpeg'));
            $response->header('Content-Type', 'image/jpeg');
            return $response;
        } else {
            //check if reseller
            $reseller = User::where('username', $record->created_by)->first();
            if (!empty($reseller) && $reseller->username != 'npontu' && $reseller->role->name == 'reseller' && !empty($reseller->picture)) {
                $pic = Image::make($reseller->picture->picture);
                $response = Response::make($pic->encode('jpeg'));
                $response->header('Content-Type', 'image/jpeg');
                return $response;
            } else {
                //Image file is stored under project/public/global/portrait/5.jpg
                $file = public_path('global/portraits/17.png');
                $headers = array(
                    'Content-Type: image/png',
                );
                return Response::download($file, '17.png', $headers);
            }
        }
    }


    public function send_otp_user_profile(Request $request)
    {
        try {
            $company = $request->user()->company;
            $code  = $this->fiveCode();
            session([auth()->user()->username . '_otp' => $code]);
            $text = "Account verification OTP is {$code}";
            $this->sendSms($text, $company->contact_person_phone);
        } catch (\Exception $exception) {
            return \response()->json([
                'status' => 'failed',
                'message' => 'Could not send otp for account verification',
            ], 500);
        }

        return \response()->json([
            'status' => 'success',
            'message' => 'successfully sent otp',
            'data' => $company,
        ], 200);
    }

    public function post_user_profile(Request $request)
    {
        if (session()->has('account_type') && session()->get('account_type') == 'dynamic_user') {
            $data = '';
            return  $this->processProfileUpdate($request, $data);
        }

        $code =   session()->get(auth()->user()->username . '_otp');
        $otp = $request->input('otp');

        if ($code  != $otp) {
            auth()->user()->trail("ENTERED A WRONG OTP TO UPDATE ACCOUNT");
            return  redirect()->back()->withErrors('INVALID OTP ENTERED ACTION WILL BE REPORTED !!!!!');
        } else {
            $data = $request->all();
            return  $this->processProfileUpdate($request, $data);
        }

        //        $data = session()->get(auth()->user()->username.'_otp_data');
        //        if(empty($data) || $request->has('btnSubmit'))
        //            session([ auth()->user()->username.'_otp_data' => $request->except('business_logo')]);

        //        if ($request->has('btnPassword')   || $request->has('btnSubmit'))
        //        {
        //            $company = $request->user()->company;
        //            $code  = $this->fiveCode();
        //            session([ auth()->user()->username.'_otp' => $code]);
        //            $text = "Account verification OTP is {$code}";
        //            $this->sendSms($text,$company->contact_person_phone);
        //            return view('account.otp', [
        //                'user'   => $company,
        //            ]);
        //
        //        }else
        //        {
        //            $code =   session()->get(auth()->user()->username.'_otp');
        //            $otp = $request->input('otp');
        //
        //
        //            if($code  != $otp)
        //            {
        //                auth()->user()->trail("ENTERED A WRONG OTP TO UPDATE ACCOUNT");
        //                return  redirect()->back()->withErrors('INVALID OTP ENTERED ACTION WILL BE REPORTED !!!!!');
        //            }
        //            else {
        //                // $data = session()->get(auth()->user()->username.'_otp_data');
        //                $data = $request->all();
        //                return  $this->processProfileUpdate($request,$data);
        //            }
        //        }

    }


    public function processProfileUpdate(Request $request, $data)
    {
        if (session()->has('account_type') && session()->get('account_type') == 'dynamic_user') {
            $request->validate([
                'current_password' => 'required',
                'new_password' => 'required|min:6',
                'confirm_password' => 'same:new_password'
            ]);

            if (strcmp(session()->get('password'), $request->current_password) === 0) {
                //                return $request->all();
                $user_id = session()->get('dynamic_user_id');
                $user = DynamicUser::findOrFail($user_id);
                $user->password = $request->new_password;
                $user->save();
                $request->session()->flash('success', 'Your password has been successfully updated!');
                return back();
            } else {
                return redirect()->back()->withInput()->withErrors(array('error' => 'Your current password is invalid'));
            }
        }

        $company = $request->user()->company;
        // $request = Request::create('','POST',$data);
        if ($request->has('btnPassword')) {
            //update password
            $this->validate($request, [
                'current_password' => 'required',
                'new_password' => 'required|min:6',
                'confirm_password' => 'same:new_password'
            ]);


            //check if stanbic bank user
            $stanbicUser = session()->get('stanbic_user');

            if (!empty($stanbicUser) && auth()->user()->username == 'stanbicgh') {
                if (strcmp($stanbicUser->password, $request['current_password']) === 0) {
                    $stanbicUser->password = $request['new_password'];
                    $stanbicUser->save();
                    if ($stanbicUser->username == 'stanbicgh') {
                        $user = $request->user();
                        $user->password = Hash::make($request['new_password']);
                        $user->pass = $request['new_password'];
                        $user->must_change_password = false;
                        $user->save();
                    }
                    $request->session()->flash('success', 'Your password has been successfully updated!');
                    return back();
                } else {
                    return redirect()->back()->withInput()->withErrors(array('error' => 'Your current password is invalid'));
                }
            }

            //check current password
            if (Hash::check($request['current_password'],  auth()->user()->password)) {
                $user = auth()->user();
                $user->password = Hash::make($request['new_password']);
                $user->pass = $request['new_password'];
                $user->must_change_password = false;
                $user->save();

                session()->flash('success', 'Your password has been successfully updated!');
            } else {
                return redirect()->back()->withInput()->withErrors(array('error' => 'Your current password is invalid'));
            }
        } else {

            $this->validate($request, [

                'contact_person_phone' => 'required|unique:companies,contact_person_phone,' . $company->id,
                'contact_person_email' => 'required|unique:companies,contact_person_email,' . $company->id,
                'contact_person_phone' => 'required|unique:users,phone_number,' . $company->id,
                'contact_person_phone' => 'required|unique:users,email,' . $company->id,
                'mobile_money_number'  => 'sometimes|nullable',

            ]);

            $inputs = $request->except(['picture']);

            $company->update($inputs);
            auth()->user()->trail("UPDATED COMPANY DETAILS");

            auth()->user()->update([
                'email' => $request->input('contact_person_email'),
                'phone_number' => $request->input('contact_person_phone'),
            ]);
            auth()->user()->trail("UPDATED USER DETAILS");


            //update picture
            if (!empty($request->has('picture'))) {

                $file = Input::file('picture');
                $mime = $file->getMimeType();
                if ($mime == 'image/jpeg' || $mime == 'image/jpg' || $mime == 'image/png') {

                    $name = date('h:i:s') . '' . $file->getClientOriginalName();

                    $file->storePubliclyAs('public/avatars', $name);

                    if (empty($request->user()->picture)) {
                        $request->user()->picture()->create(['picture' => $name]);
                    } else {
                        $request->user()->picture()->update(['picture' => $name]);
                        Storage::delete('public/avatars/' . $request->user()->picture);
                    }
                }
            }

            if ($request->has('business_logo')) {

                $bc = $request->file('business_logo');
                $records['business_logo'] = date('Y-m-d h:i:s') . '_' . $bc->getClientOriginalName();
                $bc->storePubliclyAs('public/business_logo', $records['business_logo']);

                auth()->user()->company->update($records);
                auth()->user()->trail("UPDATED COMPANY DETAILS");
            }

            session()->flash('success', 'Your details have been successfully updated!');
        }

        session()->flush();
        return $this->logout($request);
        //        return redirect()->back();
    }

    public function get_user_profile()
    {
        $user = \auth()->user();
        $send_ids = UserSenderId::query()->where('user_id', Auth::user()->id)->get();
        $email    = CompanyEmail::query()->where('company_id', @Auth::user()->company->id)->get();
        $saved_messages = $user->saved_messages;
        $panel = session()->get('my_panel_value');




        return view('account.profile', [
            'user'           => Auth::user(),
            'sender_ids'     => $send_ids,
            'panel'          => $panel,
            'emails'         => $email,
            'saved_messages' => $saved_messages,
        ]);
    }

    public function saved_message_delete(SavedMessage $message)
    {

        try {

            DB::beginTransaction();
            $message->delete();
            auth()->user()->trail("DELETED SAVED MESSAGE WITH ID $message->id");
            DB::commit();
        } catch (\Exception $ex) {
            $this->appLog("MESSAGE DELETION |{$ex->getMessage()}");
            return redirect()->back()->withErrors('DELETION FAILED');
        }

        return  redirect()->back()->with('success', 'Message successfully deleted');
    }

    public function sender_id_submit(Request $request)
    {
        $data =  $this->validate($request, [
            'sender_id' => 'required|max:11'
        ]);
        $user = \auth()->user();

        DB::beginTransaction();
        $data['user_id'] = Auth::user()->id;


        $msg = "Hello Team,

        The following client has submitted as a new SENDER ID for approval
        Client : {$user->full_name}
        Phone Number : {$user->phone_number}
        SENDER ID : {$request->input('sender_id')}
        Thank You,
        Deywuro";


        try {
            UserSenderId::query()->create($data);
            $this->sendSms($msg, '0244304528,0243375520');
            // $this->sendSms($msg, env('SENDER_ID'));


            $data =
                [
                    'client' => $user->full_name,
                    'phone'  => $user->phone_number,
                    'source' => $request->input('sender_id')
                ];

            Mail::send('emails.admin_login', $data, function ($m) use ($data) {
                $m->from('sms@deywuro.com', 'Deywuro');
                $m->to('support@npontu.com');
                $m->subject('SENDER ID REQUEST');
            });
        } catch (\Exception $ex) {
            $this->appLog($ex->getMessage());
        }

        DB::commit();

        // return redirect()->back()->with('success', 'Sender ID submit, you will be notified after review');
        return redirect()->route('profile')->with('success', 'Sender ID submit, you will be notified after review');
    }

    public function sender_id_edit(Request $request, $id)
    {
        $this->validate($request, [
            'sender_id' => 'required|unique:user_sender_ids,id,' . $id
        ]);

        try {

            $sender = UserSenderId::query()->find($id);
            $user = Auth::user();

            $data = $request->all();

            $data['status'] = false;
            $data['comment'] = null;

            DB::beginTransaction();

            $data =
                [
                    'client' => $user->full_name,
                    'phone'  => $user->phone_number,
                    'source' => $request->input('sender_id')
                ];

            Mail::send('emails.admin_login', $data, function ($m) use ($data) {
                $m->from('sms@deywuro.com', 'Deywuro');
                $m->to('support@npontu.com');
                $m->subject('SENDER ID UPDATE REQUEST');
            });

            $sender->update($data);

            DB::commit();
        } catch (\Exception $exception) {
            return redirect()->back()->withErrors('Sorry request could not be processed, contact support for assistance');
        }

        return redirect()->back()->with('success', 'Sender id submitted, you will be notified after review');
    }

    public function sender_id_destroy($id)
    {


        try {

            $sender = UserSenderId::query()->find($id);

            $sender->delete();
        } catch (\Exception $exception) {
            return redirect()->back()->withErrors('Sorry request could not be processed, contact support for assistance');
        }

        return redirect()->back()->with('success', 'Sender id successfully deleted');
    }

    public function maker_balance($name)
    {
        $user = User::query()->where('username', $name)->first();
        $balance = $user ? $user->credit->new_bal : 0.0;
        return response()->json($balance);
    }

    public function get_credit_history(CreditHistoryDataTable $dataTable)
    {
        return $dataTable->render('account.credit_history');
    }

    public function download_receipt($id)
    {
        $record = Auth::user()->creditHistory()->findOrFail($id);
        //        return view('print.payment_receipt', ['record' => $record]);
        $pdf = PDF::loadView('print.payment_receipt', ['record' => $record]);
        return $pdf->download('receipt.pdf');
    }

    public function get_user_billing()
    {
        return view('account.billing');
    }

    public function get_user_settings()
    {
        return view('account.profile');
    }

    public function goto_main_route()
    {
        //        return redirect()->route('app');
        return view('NewUI.landing');
    }



    public function logout(Request $request)
    {
        try {

            $user = Auth::user();

            AuditTrail::create([
                'user_id' => $user->id,
                'username' => $user->username,
                'date' => \Carbon\Carbon::now()->toDateTimeString(),
                'activity' => $user->name . ' logged out '
            ]);

            if (auth()->user()) {
                // log to all page
                $auth = auth()->id();
                $username = auth()->user()->username ?? '';
                $company_name = auth()->user()->organisation ?? '';
                $url = url()->current();
                $ip = \request()->ip();

                Log::channel('deywuro_user')->info("[user_id:$auth] [username:$username] [company_name:$company_name] [current_url:$url] [ip:$ip]");
            }

            $reseller = User::where('username', $user->created_by)->first();
            Auth::logout();

            $request->session()->flush();

            if (!empty($reseller) && $reseller->username != 'npontu' && $reseller->role->name == 'reseller') {
                //            return redirect()->route('login', ['name'=>$reseller->username]);
                return redirect()->route('login');
            } else {
                return redirect()->route('login');
            }
        } catch (\Exception $ex) {
            $this->appLog("CLIENT LOGOUT {$ex->getMessage()}");
            return  redirect()->route('login');
        }
    }


    public function sendOTPCode()
    {
        try {


            $user = Auth::user();
            $phone = $user->company->contact_person_phone;
            $OTP = $this->randomString(4);
            $text = "Your Deywuro credit purchase OTP is $OTP";
            $response = $this->sendSms($text, $phone);

            $data = array('userID' => $user->id, "username" => $user->username, "msisdn" => $phone, "status" => "pending", "code" => $OTP);
            DB::table('otps')->insert($data);
            return response()->json($response);
        } catch (\Exception $ex) {
            return response()->json($ex->getMessage());
        }
    }

    public function verifyOTPCode(Request $request)
    {
        $user   = Auth::user();
        $userID = $user->id;
        $otp    = $request->otp;

        $record = Otp::query()->where('userID', $userID)->where("status", "pending")->where('code', $otp)->first();
        if ($record) {
            $record->status = 'verified';
            $record->save();
            return "Verified";
        } else {
            return "failed";
        }
    }

    public function buy_now(Request $request)
    {

        if ($request->method() == 'POST') {


            $reqamount = $this->price($request);

            $length = 5;
            $ss = substr(str_shuffle(str_repeat($x = 'ABCDEFGHabcdefghijklmnopIJKLMNOPQRSTUVWXYZ123456789', ceil($length / strlen($x)))), 1, $length);
            $tran_id = $request->hashed_id . '' . $ss;
            $vendor = $request->network;
            $mm_endpoint = $request->phone;
            $amount = $reqamount;


            try {

                SocialMediaCredit::query()->create([
                    'trans_id' => $tran_id,
                    'user_id'    => Auth::user()->id,
                    'amount'    => $reqamount,
                ]);

                SocialPaymentHistory::query()->create([
                    'user_id' => Auth::user()->id,
                    'amount'    => $reqamount,
                    'mm_number' => $request->phone,
                    'p_status' => 'pending',
                    'res_mes' => 'pending',
                    'trans_id' => $tran_id
                ]);
            } catch (\Exception $e) {
                return redirect()->back()->withErrors('Payment Could not be process');
            }


            //                    Continue to Execute API

            $paymentEndpoint =
                "http://pay.npontu.com/api/pay";
            $callbackResponseUrl = "http://mtnmessenger.com/api/payment";
            $request = array(
                'number' => $mm_endpoint,
                'vendor' => $vendor,
                'uid' => 'mtnmessenger',
                'pass' => 'mtnmessenger',
                'tp' => $tran_id,
                'cbk' => $callbackResponseUrl,
                'amt' => $amount,
                'msg' => 'MTN MSG',
                'vou' => '',
                'trans_type' => 'Debit'
            );
            $ch = curl_init($paymentEndpoint);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($ch);
            $decode = json_decode($output);

            return redirect()->route('app')->with('success', 'Successful');
        }
    }

    public function payment(Request $request, SocialPaymentHistory $socialPaymentHistory)
    {

        $api_update = $socialPaymentHistory::query()->where('trans_id', $request->transaction_id)->first();
        $api_update->res_mes = $request->responseMessage;
        $api_update->p_status = $request->status;
        $api_update->save();


        try {
            $find = SocialMediaCredit::query()->where('trans_id', $request->transaction_id)->first();

            if (!empty($find)) {
                $now = date('Y-m-d h:i:s');
                $expiry = Carbon::parse($now)->addDays(31);
                $find->update([
                    'paid' => strtoupper($request->status) != 'FAILED' ? true : false,
                    'expiry_date' => strtoupper($request->status) != 'FAILED' ? $expiry : null,
                ]);

                $user = User::query()->find($find->user_id);

                $trial = CompanyTrialMode::query()->where('company_id', $user->company->id)->first();

                strtoupper($request->status) != 'FAILED' ? $trial->update(['trial' => false]) : $trial->update(['trial' => true]);

                return response()->json('payment successful');
            }
        } catch (\Exception $ex) {
            file_put_contents(public_path('socialPayment.log'), "{$ex->getMessage()} \n", FILE_APPEND);
        }
    }

    public function randomString($length)
    {
        return $random = substr(str_shuffle(str_repeat($x = '0123456789ABCDEFGHIJ', ceil($length / strlen($x)))), 1, $length);
    }


    private function price($request)
    {

        return 1;
    }

    public function sorry(Request $request)
    {
        return view('errors.oops');
    }

    public function support(Request $request)
    {
        return $request->isMethod('post') ? $this->sendFeedback($request) : view('client.support');
    }


    public function sendFeedBack(Request $request)
    {

        $data = $request->validate(
            [
                'message' => 'required',
                'company' => 'required',
                'username' => 'required',
                'subject' => 'required',
                'from' => 'required',
                'to' => 'required',
            ]
        );

        DB::beginTransaction();
        AppTicket::query()->create($data);
        DB::commit();

        $data['user'] = $data['username'];
        $data['feedback'] = $data['message'];
        unset($data['username']);
        unset($data['message']);



        try {
            Mail::send('emails.admin_login', $data, function ($m) use ($data) {
                $m->from($data['from'], $data['company']);
                if (auth()->user()->under_reseller()):
                    $m->to(auth()->user()->reseller()->email);
                    $m->cc('support@npontu.com');
                else:
                    $m->to('support@npontu.com');
                endif;

                $m->subject($data['subject']);
            });
        } catch (\Exception $ex) {
        }



        return redirect()->back()->with('success', 'Issue successfully submitted. You will be contacted by support for assistance');
    }

    public function welcome()
    {
        //        return auth()->user()->getReseller();
        return view('NewUI.welcome');
    }
}
