<?php
namespace App\Traits;

use App\CompanyTrialMode;
use App\DataTables\UserMailPaymentHistoryDataTable;
use App\EmailPricing;
use App\MediaPrice;
use App\SocialMediaCredit;
use App\SocialPayment;
use App\SocialSubscriptionBalance;
use App\SubscriptionBalance;
use App\User;
use App\UserSocialSubscription;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;

trait SocialSubscription
{
    /** @noinspection PhpPossiblePolymorphicInvocationInspection */
    public function subscription_index()
    {


        $user = auth()->user();
        if($user->under_reseller()){
                 $packages = MediaPrice::query()->where([['is_active',true],['apply_to','clients'],['user_id',$user->reseller()->id]])->get();
        }
        else {
            $packages = MediaPrice::query()->where([['is_active', true], ['apply_to', 'clients'], ['user_id', null]])->get();
        }


        $subscription = $user->social_subscription;
        $subscriptionIsValid = $user->SocialSubscriptionIsValid();


        return view('social.subscription.index',compact('packages','subscription','subscriptionIsValid'));
    }


    public function subscription_signup(Request $request,MediaPrice $package)
    {
        return $request->isMethod('post') ? $this->subscription_post($request,$package) : view('social.subscription.payment',compact('package'));
    }

    public function subscription_post($request,$package)
    {

       $data = $request->validate(
            [
                'operator' => 'required',
                'momo_number' => 'required',
                'amount' => 'required',
                'voucher' => 'required_if:operator,==,vodafone',
            ]
        );

       $data['user_id']          = auth()->user()->id;
       $data['username']         = auth()->user()->username;
       $data['media_price_id']   = $package->id;
       $data['callback']         = route('social.payment.callback');
       $data['transaction_id']   = $data['user_id'].'_'.Str::random('20');
       $data['request_body']     = json_encode($data);
       $data = (object)$data;


        $payment = $this->socialPayCurl($data);
        return $payment->status ?? 'failed' == 'success' ? redirect()->route('social.subscription.index')->with(
            'success','Payment successfully initiated Kindly check your momo wallet to approve the transaction.') :
            redirect()->back()->withErrors('Error Payment could not be initiated Kindly try again !!');

    }



    public function payment_history(UserMailPaymentHistoryDataTable $history)
    {
        return $history->render('social.subscription.history');
    }



    public function socialPayCurl($params)
    {
        SocialPayment::query()->create((array)$params);
        $paymentEndpoint = "https://pay.npontu.com/api/pay";
        $request = array(
            'number' => $params->momo_number,
            'vendor' => $params->operator,
            'uid'    => 'npdeywuro',
            'pass'   => 'hdgt2314',
            'tp'     => $params->transaction_id,
            'cbk'    => $params->callback,
            'amt'    => $params->amount,
            'msg'    => 'DEYWURO SOCIAL PAYMENT',
            'vou'    => $params->voucher,
            'trans_type' => 'Debit'
        );
        $ch = curl_init($paymentEndpoint);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        return json_decode($output);
    }

    /** @noinspection PhpPossiblePolymorphicInvocationInspection */
    public function payCallback(Request $request)
    {
        try {

            $this->log("Social Momo" . $request->input('transaction_id') . '||' . $request->input('status'));

            $transaction_id = $request->input('transaction_id');
            $status = strtolower($request->input('status'));
            $responseMessage = $request->input('responseMessage');
            $expires_on = Carbon::parse(now())->addDays(30); //gets new expiry date
            $user_id = (integer)explode('_', $transaction_id)[0];  //converts user id to int after explosion
            $user = $this->user($user_id);  //gets the user details


            $payment = SocialPayment::query()->where('transaction_id', $transaction_id)->first();
            $payment->status   = $status;
            $payment->response = $responseMessage;
            $payment->save();  //updates the payment status

            if ($status == 'success') {


                UserSocialSubscription::query()->updateOrCreate(
                    ['user_id' => $user_id],
                    [
                        'is_paid' => true,
                        'expires_on' => $expires_on,
                        'media_price_id' => $payment->media_price_id
                    ]
                );

                $trial = CompanyTrialMode::query()->where('company_id', $this->user($user_id)->company->id)->first();
                $trial->update(['trial'=>false]);


                if($this->user($user_id)->role_id == 3) {   //for resellers

                    SocialSubscriptionBalance::query()->updateOrCreate(
                        ['user_id' => $user_id],
                        [
                            'media_price_id' => $payment->media_price->id,
                            'pricing' => $payment->media_price->cost,
                            'no_of_post' => $payment->media_price->package_type == 'unlimited' ? 99999999999999999999 : $payment->media_price->no_of_post,
                        ]
                    );
                }


                $message = "You have successfully been subscribed to the social media package.
                            The subscription expires on <b>$expires_on</b>.
                            For further assistance kindly contact <b>support@npontu.com</b><br>
                            Thank you.";

                $content = ['body' => $message, 'to' => $user->email, 'name' => $user->username,'subject'=>'DEYWURO PAYMENT NOTICE'];  //gets parameters ready for sending email
                $this->sendEmail($content);

            }

            else if($status == 'failed'){
                $message = "Your attempt to subscribe to a social media package failed.
                            Kindly review your request and try again
                            For further assistance you may contact <b>support@npontu.com</b><br>
                            Thank you.";
                $content = ['body' => $message, 'to' => $user->email, 'name' => $user->username,'subject'=>'DEYWURO PAYMENT NOTICE'];  //gets parameters ready for sending email
                $this->sendEmail($content);
            }


        }catch (\Exception $exception){
            $this->log("EXCEPTION || " . $request->input('transaction_id') . '||' . $exception->getMessage());
        }



    }

    public function log($message)
    {
        $now = Carbon::parse(now());
        file_put_contents(storage_path() . '/logs/social_pay.log', "\n" . 'INFO: ' . $now . ' || ' .$message . PHP_EOL, FILE_APPEND);
    }

    public function user($user)
    {
        return User::query()->find($user);
    }







}
