<?php

namespace App\Http\Controllers\USSD;

use App\Http\Requests\IniitalRegistrationDebitRequest;
use App\InitialResellerDebit;
use App\UssdService;
use Carbon\Carbon;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Str;
use App\Http\Controllers\Controller;

class InitialDebitController extends Controller
{

    public function showPaymentForm()
    {
        return view('ussd.payment.reseller_initial_debit_payment');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @param int $id
     * @return RedirectResponse|Response
     */
    public function paymentRequest(IniitalRegistrationDebitRequest $request)
    {
        //payment end point
        $paymentEndpoint = "https://pay.npontu.com/api/pay";

        $transactionId = now() . '_' . $this->generateTransactionId();

        $request['number'] = substr_replace($request['number'], '233', 0, 1);

        $uid='npdeywuro';
        $pass='hdgt2314';

        $data = [
            'number' => $request['number'],
            'vendor' => $request['channel'],
            'uid'  => $uid,
            'pass' => $pass,
            'tp'   => $transactionId,
            'amt'  => 900.00,
            'cbk' => route('initial.debit.pay'),
            'msg'  => 'Reseller Registration Fee',
            'vou'  => $request['voucher'],
            'trans_type' => 'Debit'
        ];

        $this->appLog('RESELLER REGISTRATION FEE '.json_encode($data));

        //make api call for payment transaction
        $result = $this->makePayment($data, $paymentEndpoint);


        if ($result->status == 'success') {
            //save to payment table, if already exist, update
            InitialResellerDebit::create([
                'amount' => 900.00,
                'user_id' => auth()->id(),
                'transaction_id' => $transactionId,
                'status' => $result->status,
                'response_message' => 'Pending',
                'number' => $data['number'],
                'vendor' => $data['vendor'],
                'voucher' => $data['vou']
            ]);

            auth()->user()->company->update(['paid_initial_debit' => true]);

            session()->flash('success', 'Approve Transaction in your wallet to finalise payment. Thank you.');

            return redirect()->route('reseller.app');
        }

        //return error message
        session()->flash('error', 'Sorry, an error occurred in processing payment. Kindly retry.');

        return redirect()->back()->withInput();

    }


    private function makePayment(array $data, $endpoint)
    {

        $ch = curl_init($endpoint);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $output = json_decode(curl_exec($ch));

        //if output is null because of an error, return a custom object with status failed
        if (is_null($output)):
            $this->appLog('RESELLER REGISTRATION FEE PAYMENT null '.json_encode($output));
            return (object)['status' => 'failed', 'message' => 'Failed'];
        endif;

        //Response for mobile money is either an object or an array of object
        //If its an array, then get the first element of object and return it
        $this->appLog('RESELLER REGISTRATION FEE PAYMENT '.json_encode($output));
        return is_object($output) ? $output : $output[0];
    }

    public function paymentCallback(Request $request)
    {
        try {

            $this->appLog('RESELLER REGISTRATION FEE PAYMENT RESPONSE '.json_encode($request->all()));
            //get the transaction id, status and response message
            $transaction_id = $request->input('transaction_id');
            $status = strtolower($request->input('status'));
            $message = $request->input('responseMessage');

//            my changes
            $payment = InitialResellerDebit::where('transaction_id', $transaction_id)->first();

            $payment->update(['status' => $status,'response_message' => $message]);

                            //get the service id
                //            $serviceId = (integer)explode('_', $transaction_id)[0];
                //            //find the service
                //            $service = UssdService::query()->find($serviceId);

                            //set expiry date if not failed
                //            $expiryDate = $status === 'failed' ? null : Carbon::parse(now())->addDays(30);

                            //update the payment record
                //            $service->ussd_payment()->update(
                //                [
                //                    'status' => $status,
                //                    'response_message' => $message,
                //                    'phone_number' => $request->input('msisdn'),
                //                    'payment_date' => date('Y-m-d H:i:s'),
                //                    'expiry_date' => $expiryDate,
                //                    'has_expired' => 0
                //                ]
                //            );

                            //update the service purchase status to paid if successful]
                //            if ($status !== 'failed') {
                //                $service->update(['purchase_status' => UssdService::USSD_SERVICE_PURCHASE_STATUS_PAID]);
                //
                //                $service->update(['purchase_status'=>'paid','sessions'=>$service->ussd_payment->ussd_price->sessions]);
                //
                //                $this->appLog("UPDATED SERVICE $service->code WITH SESSIONS {$service->ussd_payment->ussd_price->sessions}");


                                //update the services table on server 6
                                //establish connection
                //                $connection = $this->ussdLiveDBConnection();
                //                //insert data into the db
                //                $extension = $this->extractExtensionFromServiceCode($service->code);
                //                //purchase status
                //                $purchaseStatus = UssdService::USSD_SERVICE_PURCHASE_STATUS_PAID;
                //
                //                $SQL =  "UPDATE services SET purchase_status = '$purchaseStatus'
                //                and session_used = 0 and package_session = '{$service->ussd_payment->ussd_price->sessions}'
                //                WHERE extension = '$extension'";

                //
                //                $this->appLog("QUERY SERVICE $service->code WITH QUERY {$SQL}");
                //
                //                mysqli_query($connection, $SQL);


        }catch (\Exception $ex)
        {
            $this->appLog('USSD callback ERROR '.$ex->getMessage());
        }
    }

    /**
     * Generates 12 digits long transaction id in upper case
     * @return string
     */
    public function generateTransactionId()
    {
        return strtoupper(Str::random(12));
    }
}
