<?php

namespace App\Http\Controllers;

use App\AuditTrail;
use App\BalanceThreshold;
use App\CompanyEmail;
use App\CompanyStatus;
use App\CompanyTrialMode;
use App\Credit;
use App\CreditHistory;
use App\DataTables\AllSenderIDDataTable;
use App\DataTables\CreditHistoryDataTable;
use App\EmailLog;
use App\Otp;
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 Illuminate\Support\Facades\Validator;
use Intervention\Image\Facades\Image;
use PDF;

class DashboardController extends Controller
{


    public function genOtp()
    {
        return view('account.account_otp.gen_otp');
    }

    public function appLog($message)
    {
        // $now = Carbon::parse(now());
        $date = date('Y-m-d h:i:s');
        file_put_contents(storage_path() . '/logs/pwd_otp.log', '\n   || Timestamp || ' . $date . ' || ' . $message . PHP_EOL, FILE_APPEND);
    }


    public function genOtpPost()
    {
        $user = Auth::user();

        $phone = $user->company->company_phone_number;
        if (empty($phone) || str_contains($phone, 'N/A')) {
            $phone = $user->phone_number;
        }

        $OTP = mt_rand(1111, 9999);

        $text = "Your Password Reset OTP is $OTP";

        $this->sendSms($text, $phone);

        $data = array('userID' => $user->id, "username" => $user->username, "msisdn" => $phone, "status" => "pending", "code" => $OTP, "created_at" => date('Y-m-d h:i'));

        DB::table('otps')->insert($data);

        $this->appLog("OTP generated for phone number: " . $phone . " and User: " . $data['username']);

        echo "1";
    }


    public function successJson($msg)
    {
        return response()->json([
            'code' => 200,
            'msg' => $msg
        ]);
    }

    public function failJson($msg)
    {
        return response()->json([
            'code' => 402,
            'msg' => $msg
        ]);
    }



    public function genOtpVerify(Request $request)
    {
        $code = $request->only(['code']);

        $user = Auth::user();
        $user_id = $user->id;

        $phone = $user->company->mobile_money_number;

        $otp = Otp::query()->where('userID', $user_id)
            ->where('status', 'pending')
            ->where('code', $code)->first();

        if (!empty($otp)) {

            $this->appLog("OTP for phone number: " . $phone . " found");

            $created_time = date($otp->created_at, strtotime('+ 5 minutes'));

            $real_time = (string) date('Y-m-d h:is');

            $created_time = (string) Carbon::parse($otp->created_at)->addMinutes(5);

            if ($created_time > $real_time) {

                $this->appLog("OTP for phone number: " . $phone . " verified");

                $otp->update([
                    'status' => 'verified'
                ]);

                session()->put([
                    'otp' => $otp->code,
                    'status' => $otp->status
                ]);

                return $this->successJson('verified');
            }

            $this->appLog("OTP for phone number: " . $phone . " does not exist");

            return $this->failJson('Otp expired or does not exist');
        }

        return $this->failJson('OTP does not exist');
    }


    public function otpResetPwd()
    {
        if (!empty(session()->get('otp'))) {
            return view('account.account_otp.reset_pwd');
        }

        return redirect()->route('gen.otp');
    }


    public function otpPostResetPwd(Request $request)
    {
        $data = $request->all();

        $validate = Validator::make($data, [
            'old_password' => 'required',
            'new_password' => 'required',
            'confirm_new_password' => 'required'
        ]);

        if ($validate->fails()) {
            return back()->withErrors($validate->errors()->first())->withInput();
        }
        $user = Auth::user();

        if ($data['old_password'] !== $user->pass) {
            return back()->withErrors("Invalid Old Password")->withInput();
        }

        if ($data['new_password'] !== $data['confirm_new_password']) {
            return back()->withErrors('New Passwords do not match')->withInput();
        }

        $new_pwd = bcrypt($request->get('new_password'));

        $user->update([
            'pass' => $data['new_password'],
            'password' => $new_pwd,
            'must_change_password' => 0
        ]);

        $myPassword = $request->get('new_password');
        $request->session()->put('myPassword', $myPassword);

        $this->appLog("Password reset for user: " . $user->username . " successful");

        return redirect()->route('app')->with('success', 'Password reset successful');
    }



    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();


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


        if (auth()->user()->must_change_password == 1) {
            return redirect()->route('gen.otp');
        }

        $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');

        return view('welcome', [
            'enable_pay' => $_enb,

        ]);
    }

    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\'s Dashboard';
        }

        $data = DB::table('sms_log')->select(DB::raw('sms_log.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->sms_log()->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' => 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\'s 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' => 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();

        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 sms_log
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);
                $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
            $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 `sms_log` 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 post_user_profile(Request $request)
    {
        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 = bcrypt($request['new_password']);
                        $user->pass = $request['new_password'];
                        $user->must_change_password = false;
                        $user->save();
                    }

                    $myPassword = $request['new_password'];
                    $request->session()->put('myPassword', $myPassword);

                    $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'], $request->user()->getAuthPassword())) {
                $user = $request->user();
                $user->password = bcrypt($request['new_password']);
                $user->pass = $request['new_password'];
                $user->must_change_password = false;
                $user->save();

                $myPassword = $request['new_password'];
                $request->session()->put('myPassword', $myPassword);

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


            $this->validate($request, [
                'phone_number' => 'required|digits_between:9,20',
                'email' => 'nullable|email',
                'credit_threshold_1' => 'required',
                'credit_threshold_2' => 'nullable',
                'credit_threshold_3' => 'nullable',
            ]);

            $data = [
                'user_id' => \auth()->id(),
                'phone_number' => $request->phone_number,
                'email' => $request->email,
                'credit_threshold_1' => $request->credit_threshold_1,
                'credit_threshold_2' => $request->credit_threshold_2,
                'credit_threshold_3' => $request->credit_threshold_3,
            ];

            BalanceThreshold::query()->updateOrCreate(['user_id' => auth()->id()], $data);
            $request->session()->flash('success', 'Your Balance Threshold has been successfully updated!');
        } else {
            //update user detail
            $this->validate($request, [
                'organisation' => 'present',
                'phone_number' => 'required',
                'mobile_money_number' => 'required',
                'website_url' => 'present'
            ]);
            $inputs = $request->except(['picture', 'mobile_money_number']);

            $request->user()->update($inputs);
            $request->user()->company()->update(['mobile_money_number' => $request->mobile_money_number]);

            //update picture
            if (!empty($request['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);
                    }
                }
            }

            $request->session()->flash('success', 'Your details have been successfully updated!');
        }
        return redirect()->back();
    }

    public function get_user_profile()
    {

        $send_ids = UserSenderId::query()->where('user_id', Auth::user()->id)->get();
        $email = CompanyEmail::query()->where('company_id', @Auth::user()->company->id)->get();
        $panel = session()->get('my_panel_value');
        $balance_threshold = BalanceThreshold::query()->where('user_id', '=', \auth()->id())->first() ?? null;

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

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

        try {

            $data = $request->all();
            $data['user_id'] = Auth::user()->id;
            $user = \auth()->user();

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




            $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('mtn@messenger.com', 'MESSENGER');
                $m->to('dorothy.sarpong@mtn.com');
                $m->cc('support@npontu.com');
                $m->cc('Benedict.bentil@mtn.com');
                $m->cc('Peter.anani@mtn.com');
                $m->cc('Josephine.asante@mtn.com');
                $m->cc('Maame.simpson@mtn.com');
                $m->subject('SENDER ID REQUEST');
            });
            DB::commit();
        } catch (\Exception $exception) {
            file_put_contents(storage_path() . '/logs/laravel.log', "\n" . $exception->getMessage() . PHP_EOL, FILE_APPEND);
            return redirect()->back()->withErrors('Sorry request could not be processed, contact support for assistance');
        }

        return redirect()->back()->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'
        ]);

        try {

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

            $data = $request->all();

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

            $sender->update($data);
        } 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 all_sender_ids(AllSenderIDDataTable $all_of_them)
    {
        return $all_of_them->render('admin.company.senderId.index');
    }

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


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

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

        $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]);
        } else {
            return redirect()->route('login');
        }
    }


    public function sendOTPCode()
    {
        $user = Auth::user();
        $phone = $user->company->mobile_money_number;
        $OTP = $this->randomString(4);
        $text = "Your MESSENGER credit purchase OTP is $OTP";
        $this->sendSms($text, $phone);

        $data = array('userID' => $user->id, "username" => $user->username, "msisdn" => $phone, "status" => "pending", "code" => $OTP);
        DB::table('otps')->insert($data);
        echo "1";
    }

    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') {

            //            dd($request);
            // Receive Amount
            $reqamount = $this->price($request);

            //Start with payment processing
            $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;

            //Save to DB

            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);
    }

    public function sendSms($text, $phone)
    {
        $message = urlencode($text);
        $num = urlencode($phone);
        $sender = urlencode('Messenger');
        $url = "https://deywuro.com/api/sms?username=Sammy&password=cse@2021_npontu&source=$sender&destination=" . $num . "&message=" . $message;

        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_exec($curl);
        curl_close($curl);
    }

    private function price($request)
    {

        return 1;
    }

    //TODO this method adds GHC to client's balance for each promotion benefit
    public function promo(Request $request)
    {

        $this->validate($request, [
            'email' => 'required'
        ]);

        $username = Auth::user()->username;

        file_put_contents(storage_path() . '/sms_log/promoEmail.log', "\n" . 'ABE DEBUG:user details email || username ' . json_encode($request->email) . '||' . json_encode($username) . PHP_EOL, FILE_APPEND);

        return redirect()->back()->with('success', 'Your request is being processed. Your Account will be credited upon validation. Thank You!');

        $email = $request->email;
        $add_amt = 3.0;


        $username = Auth::user()->username;

        file_put_contents(storage_path() . '/sms_log/promoEmail.log', "\n" . 'ABE DEBUG:user details email || username ' . json_encode($request->email) . '||' . json_encode($username) . PHP_EOL, FILE_APPEND);


        return redirect()->back()->with('success', 'Your request is being processed. Your Account will be credited upon validation. Thank You!');


        //        $prom = DB::connection("mysql2")->table("promotions")->select("select * from promotions where email = '$email'");
        $prom = DB::connection("mysql2")->table("promotions")->where([['email', '=', "$email"], ['status', 'allow']])->get();

        if (count($prom) > 0) {
            foreach ($prom as $data) {

                $add_amt += $add_amt;

                DB::connection("mysql2")->table("promotions")->where('id', $data->id)->update([
                    'status' => 'disallow',
                ]);
            }

            $user_id = Auth::user()->id;

            $query = Credit::query()->where('user_id', $user_id)->first();

            if (isset($query)) {

                $new_bal = $query->new_bal += $add_amt;

                DB::table('credits')->where('user_id', $user_id)->update([
                    'new_bal' => $new_bal,
                ]);

                return redirect()->back()->with('success', 'Your account has been topped up with ' . $add_amt . ' GHC Successfully');
            }
        } else {
            return redirect()->back()->withInput()->withErrors(array('error' => 'You are not qualified for this promotion. Buy bigger package from your mtn business manager account'));
        }
    }
}