<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
include '../../../config/index.php';
$data = file_get_contents('php://input');
$obj = json_decode($data, true);

$MerchantRequestID = "";
$CheckoutRequestID = "";
$config = array(
    "env"              => "sandbox",
    "BusinessShortCode" => "4118529",
    "key"              => "fD4noqPNFA2lx4IC9mwEJHKADbbrqPSqZ5siXXk4FNpQlfUA", //Enter your consumer key here
    "secret"           => "0LkTViI7iBReZKEUQgZLubmFpUscJbawk4YUfUHvwDx9j6nzKK2Dv9JDQxPIqZ1w", //Enter your consumer secret here
    "username"         => "DIGIFUNZI",
    "TransactionType"  => "CustomerPayBillOnline",
    "passkey"          => "a51e3004f661cdfe8ab07f3b72f7248bbce9a4d7318bfe58c9bcc03927da767a", //Enter your passkey here
    "CallBackURL"      => $CallBackURL . "mpesa/adults/confirmcredit/index.php", //When using localhost, Use Ngrok to forward the response to your Localhost
    "AccountReference" => "Credits",
    "TransactionDesc"  => "Payment of X",
);
$phone = $obj['phoneNumber'];
$phone = (substr($phone, 0, 1) == "+") ? str_replace("+", "", $phone) : $phone;
$phone = (substr($phone, 0, 1) == "0") ? preg_replace("/^0/", "254", $phone) : $phone;
$phone = (substr($phone, 0, 1) == "7") ? "254{$phone}" : $phone;
$amount = $obj['CustomerPrice'];
$access_token = ($config['env']  == "live") ? "https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials" : "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials";
$credentials = base64_encode($config['key'] . ':' . $config['secret']);
$ch = curl_init("https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials");
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Basic " . $credentials]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response);
$token = isset($result->{'access_token'}) ? $result->{'access_token'} : "N/A";
$timestamp = date("YmdHis");
$password  = base64_encode($config['BusinessShortCode'] . "" . $config['passkey'] . "" . $timestamp);
$curl_post_data = array(
    "BusinessShortCode" => $config['BusinessShortCode'],
    "Password" => $password,
    "Timestamp" => $timestamp,
    "TransactionType" => $config['TransactionType'],
    "Amount" => $amount,
    "PartyA" => $phone,
    "PartyB" => $config['BusinessShortCode'],
    "PhoneNumber" => $phone,
    "CallBackURL" => $config['CallBackURL'],
    "AccountReference" => $config['AccountReference'],
    "TransactionDesc" => $config['TransactionDesc'],
);
$data_string = json_encode($curl_post_data);
// $endpoint = ($config['env'] == "live") ? "https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest" : "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest"; 
$ch = curl_init("https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $token,
    'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response     = curl_exec($ch);
curl_close($ch);
$result = json_decode(json_encode(json_decode($response)), true);
if (!preg_match('/^[0-9]{10}+$/', $phone) && array_key_exists('errorMessage', $result)) {
    $errors['phone'] = $result["errorMessage"];
}
if ($result['ResponseCode'] === "0") {          //STK Push request successful
    $MerchantRequestID = $result['MerchantRequestID'];
    $CheckoutRequestID = $result['CheckoutRequestID'];

    $InvoiceNo =  $obj["parent_id"] .  $obj["CreditPackages_id"] .  $obj["PackageCredits"] . date("isv");
    $InvoiceDate =  date("Y-m-d");
    $InvoiceDueDate =  date("Y-m-d", strtotime("+1 week",  strtotime($InvoiceDate)));
    $sql_we1 = 'INSERT INTO AdultCreditInvoices VALUES (NULL,
            "' . $obj["AdultStudent_id"] . '",
            "' . $obj["CreditPackages_id"] . '",
            "' . $obj["CustomerPrice"] . '",
            "' . $obj["PackageCredits"] . '",
            "' . $InvoiceNo . '",
            "' . $InvoiceDate . '",
            "' . $InvoiceDueDate . '",
            "Unpaid",
            NOW(),
            "false",
            "false",
            NOW())';

    if (mysqli_query($conn, $sql_we1)) {
        $AdultCreditInvoice_id = mysqli_insert_id($conn);
        $sql_b = "INSERT INTO AdultCreditMpesa VALUES (NULL,
                '" . $AdultCreditInvoice_id . "',
                '" . $obj['phoneNumber'] . "',
                '" . $obj["CustomerPrice"] . "',
                '" . $CheckoutRequestID . "',
                '" . $MerchantRequestID . "',
                '123456789',
                'Not executed', 
                NOW(),
                NOW())";

        if (mysqli_query($conn, $sql_b)) {
        }
    }
    $curl_post_data = array(
        'Success' => 'true',
        'MerchantRequestID' => $MerchantRequestID,
        'CheckoutRequestID' => $CheckoutRequestID,
        'phoneNumber' => $obj['phoneNumber'],
        'ResultCode' => '123456789',
    );
    echo json_encode($curl_post_data);
}
