<?php

namespace App\Console\Commands;

use App\BalanceThreshold;
use App\Credit;
use App\Mail\BalanceCheckerMail;
use App\Tools\SmsTools;
use App\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
use function foo\func;

class BalanceChecker extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'user:balance-checker';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $users = User::all();

        $users->map( function ($user){
            $balance_thresholds = BalanceThreshold::query()->where('user_id','=',$user->id)->get();

            $user_balance = $user->credit->new_bal ?? null;
            $user_price = $user->credit->price ?? null;

            if ((count($balance_thresholds) > 0) && $user_balance){

                $balance_thresholds->map( function ($balance_threshold) use($user_balance,$user_price,$user) {
                    $name = $user->first_name;
                    $email = $balance_threshold->email;

                    if ($balance_threshold->credit_threshold_1 && ($user_balance <= $balance_threshold->credit_threshold_1) && ($balance_threshold->alert_sent_1 == false)){
                        $available_sms = number_format(floor($balance_threshold->credit_threshold_1/$user_price));
                        $msg = "Threshold Alert : Your balance has currently hit your set limit of Ghc {$balance_threshold->credit_threshold_1}.
                         
You can send only $available_sms amount of SMS. 
Please recharge soon before it runs out.

Thank You
SMS CLIENT MTN Ghana";
                        $this->sendSms($msg, $balance_threshold->phone_number);
                        $this->sendEmail($name, $email, $balance_threshold->credit_threshold_1, $available_sms);
                        $balance_threshold->update(['alert_sent_1' => true]); // update alert sent to true

                    } elseif ($balance_threshold->credit_threshold_2 && ($user_balance <= $balance_threshold->credit_threshold_2) && ($balance_threshold->alert_sent_2 == false)){
                        $available_sms = number_format(floor($balance_threshold->credit_threshold_2/$user_price));
                        $msg = "Threshold Alert : Your balance has currently hit your set limit of Ghc {$balance_threshold->credit_threshold_2}.
                         
You can send only $available_sms amount of SMS. 
Please recharge soon before it runs out.

Thank You
SMS CLIENT MTN Ghana";
                        $this->sendSms($msg, $balance_threshold->phone_number);
                        $this->sendEmail($name, $email, $balance_threshold->credit_threshold_2, $available_sms);
                        $balance_threshold->update(['alert_sent_2' => true]); // update alert sent to true

                    } elseif ($balance_threshold->credit_threshold_3 && ($user_balance <= $balance_threshold->credit_threshold_3) && ($balance_threshold->alert_sent_3 == false)){
                        $available_sms = number_format(floor($balance_threshold->credit_threshold_3/$user_price));
                        $msg = "Threshold Alert : Your balance has currently hit your set limit of Ghc {$balance_threshold->credit_threshold_3}.
                         
You can send only $available_sms amount of SMS.
Please recharge soon before it runs out.

Thank You
SMS CLIENT MTN Ghana";
                        $this->sendSms($msg, $balance_threshold->phone_number);
                        $this->sendEmail($name, $email, $balance_threshold->credit_threshold_3, $available_sms);
                        $balance_threshold->update(['alert_sent_3' => true]); // update alert sent to true
                    }


                    if ($user_balance > $balance_threshold->credit_threshold_1){
                        $balance_threshold->update(['alert_sent_1' => false]); // update alert sent to true
                    }
                    if ($user_balance > $balance_threshold->credit_threshold_2){
                        $balance_threshold->update(['alert_sent_2' => false]); // update alert sent to true
                    }
                    if ($user_balance > $balance_threshold->credit_threshold_3){
                        $balance_threshold->update(['alert_sent_3' => false]); // update alert sent to true
                    }

                });
            }

        });
    }

    private function sendEmail($name, $email, $balance_threshold, $available_sms)
    {
        try{
            Mail::to($email)->cc(['support@npontu.com'])->send(new BalanceCheckerMail($name, $balance_threshold, $available_sms));
        }catch (\Exception $ex){
            file_put_contents(public_path('BalanceCheckerMail.log'),"{$ex->getMessage()} \n",FILE_APPEND);
        }
    }

    public function sendSms($text,$phone,$source = 'LOW CREDIT'){

        $now = date('Y-m-d H:i:s');
        $message = urlencode($text);
        $num = urlencode($phone);
        $password = 'beta80admin09test';

        $url = "https://mtnmessenger.com/api/sms?username=betatest&password=$password&source=$source&destination=" . $num . "&message=". $message;
        $directSubmit = file_get_contents($url);

        $this->info($now, "Single SMS fired| $directSubmit");
        return true;
    }
}
