<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Mpesa extends Model
{
    use HasFactory;

    public function lipaNaMpesaPassword()
    {
        //timestamp
        //passkey
        //businessShortCode


        $timestamp = date("Ymdhis");
        $passkey = 'bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919';
        $businessShortCode = 174379;
        $mpesaPassword = base64_encode($businessShortCode.$passkey.$timestamp);

        return $mpesaPassword;

    }

    public function getAccessToken()
    {
        $url = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';

        $consumer_key = 'QRZ6o59jDXY8MsHke39r6Fy5hmLyVBOc';
        $consumer_secret = 'xLicwBbjel98XrhH';

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        $credentials = base64_encode($consumer_key . ':' . $consumer_secret);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . $credentials)); //setting a custom header
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        $curl_response = curl_exec($curl);

        return json_decode($curl_response)->access_token;


    }

    public function registerUrls(){


        $base_url = 'https://staging.bluepages.co.ke';

        $body = array(
            'ShortCode' => 174379,
            'ResponseType' => 'Completed',
            'ConfirmationURL' => $base_url.'/api/mobile-money/stk/confirmation',
            'ValidationURL' => $base_url.'/api/mobile-money/stk/validation',
        );

        $url = 'https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl';

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization:Bearer '.$this->getAccessToken()));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($body));

        $response = curl_exec($curl);
        return $response;

    }


    public function stkPush($amount,$phone,$reference)
    {
        $businessShortCode = 174379;
        $formatedPhone = substr($phone, 1);//721223344
        $code = "254";
        $phoneNumber = $code.$formatedPhone;//254721223344

        // $cleanedNumber = str_replace(" ", "", $phone);
        // $phoneNumber = str_replace("+", " ", $cleanedNumber);


        $timestamp =  date("Ymdhis");
        $base_url = 'https://staging.bluepages.co.ke';

        $url ='https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest';
        // echo($phoneNumber);

        $curl_post_data = array(
            'BusinessShortCode' => $businessShortCode,
            'Password' => $this->lipaNaMpesaPassword(),
            'Timestamp' => $timestamp,
            'TransactionType' => 'CustomerPayBillOnline',
            'Amount' => $amount,
            'PartyA' => $phoneNumber,
            'PartyB' => $businessShortCode,
            'PhoneNumber' => $phoneNumber,
            'CallBackURL' => $base_url.'/api/payment/mpesa/callback',
            'AccountReference' => $reference,
            'TransactionDesc' => $reference,

        );


        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization:Bearer '.$this->getAccessToken()));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($curl_post_data));

        $response = curl_exec($curl);

        return $response;

    }

    public function stkPushStatus($transId)
    {
        $businessShortCode = 174379;
        $url = 'https://sandbox.safaricom.co.ke/mpesa/stkpushquery/v1/query';

        $curl_post_data = array(
            'BusinessShortCode' => $businessShortCode,
            'Password' => $this->lipaNaMpesaPassword(),
            'Timestamp' => date("Ymdhis"),
            'CheckoutRequestID' => $transId,


        );
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization:Bearer '.$this->getAccessToken()));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($curl_post_data));

        $response = curl_exec($curl);

        return $response;
    }

    public function processPayment($amount,$phone,$reference)
    {
        $response_data = $this->stkPush($phone,$amount,$reference);
        if($response_data){
            $data1 = json_decode($response_data, true);
            $status = $data1['ResponseCode'];
            if($status ==0){

                $cid = array(
                    "checkoutId" => $data1['CheckoutRequestID'],
                    "status" => 0
                );
                return $cid;


            }else{
                $cid = array(
                    "checkoutId" => "none",
                    "status" => 2

                );
                return $cid;
            }


        }else{

            $cid = array(
                "checkoutId" => "none",
                "status" => 2

            );

            return $cid;


        }

    }



}
