<?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");

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require '../../../vendor/autoload.php';
include '../../../config/index.php';
$data = array();

function generatePassword($length = 6)
{
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $count = mb_strlen($chars);

    for ($i = 0, $result = ''; $i < $length; $i++) {
        $index = rand(0, $count - 1);
        $result .= mb_substr($chars, $index, 1);
    }

    return $result;
}
function getUnusedCode()
{
    include '../../../config/index.php';
    $sql_10P = "SELECT * FROM QuarkyKits   ORDER BY dated DESC";
    $result_10P = mysqli_query($conn, $sql_10P);
    if (mysqli_num_rows($result_10P) > 0) {
        while ($row_10P = mysqli_fetch_assoc($result_10P)) {
            $sql_pqk = "select * from ParentQuarkyKits   WHERE QuarkyKitID='" . $row_10P["QuarkyKitID"] . "'    ";

            $result_pqk = mysqli_query($conn, $sql_pqk);

            $sql_cqk = "select * from CenterQuarkyKits   WHERE QuarkyKitID='" . $row_10P["QuarkyKitID"] . "'    ";

            $result_cqk = mysqli_query($conn, $sql_cqk);

            if (mysqli_num_rows($result_pqk) === 0) {
                if (mysqli_num_rows($result_cqk) === 0) {
                    $curl_post_data = array(
                        'Success' => 'true',
                        'QuarkyKitID' => $row_10P['QuarkyKitID'],
                        'QuarkyCode' => $row_10P['QuarkyCode'],
                        'MaximumStudents' => $row_10P['MaximumStudents'],
                        'RegisteredStudents' => $row_10P['RegisteredStudents'],
                        'LimitReached' => $row_10P['LimitReached'],
                    );
                    return $curl_post_data;
                }
            }
        }
    }
}
function pushStkPayment($mPesaPhone, $Totalprice, $QuarkySoldID, $NoKits)
{
    include '../../../config/index.php';
    $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/quarky/confirm/index.php", //When using localhost, Use Ngrok to forward the response to your Localhost
        "AccountReference" => "Digifunzi",
        "TransactionDesc" => "Payment of X",
    );
    $phone = $mPesaPhone;
    $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 = $Totalprice;

    $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);
    // echo $response;

    $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") {

        $MerchantRequestID = $result['MerchantRequestID'];
        $CheckoutRequestID = $result['CheckoutRequestID'];
        $invoice_no = $QuarkySoldID . date("isv");
        $invoice_date = date("Y-m-d");
        $invoice_due_date = date("Y-m-d", strtotime("+1 week", strtotime($invoice_date)));

        $sql_qks_1 = 'INSERT INTO QuarkyInvoices VALUES (NULL,
                "' . $QuarkySoldID . '",
                "' . $NoKits . '",
                "' . $Totalprice . '",
                "' . $invoice_no . '",
                "' . $invoice_date . '",
                "' . $invoice_due_date . '",
                "Unpaid",
                "false",
                "false",
                now())';
        if (mysqli_query($conn, $sql_qks_1)) {
            $QuarkyInvoicesID = mysqli_insert_id($conn);
            $sql_qmps_1 = 'INSERT INTO QuarkyMpesa VALUES (NULL,
                    "' . $QuarkyInvoicesID . '",
                    "' . $mPesaPhone . '",
                    "' . $Totalprice . '",
                    "' . $CheckoutRequestID . '",
                    "' . $MerchantRequestID . '",
                    "123456789",
                    "Not executed", 
                    now())';
            if (mysqli_query($conn, $sql_qmps_1)) {
            }
        }
    }

    $curl_post_data = array(
        'Success' => 'true',
        'MerchantRequestID' => $MerchantRequestID,
        'CheckoutRequestID' => $CheckoutRequestID,
        'response' => $response,
    );
    return $curl_post_data;
}
$result_pass = generatePassword();


$sql_10P = "SELECT * FROM QuarkyKits  WHERE   QuarkyCode='" . $_GET['QuarkyCode'] . "'";
$result_10P = mysqli_query($conn, $sql_10P);
if (mysqli_num_rows($result_10P) > 0) {
    while ($row_10P = mysqli_fetch_assoc($result_10P)) {
        $sql_pqk = "select * from ParentQuarkyKits   WHERE QuarkyKitID='" . $row_10P["QuarkyKitID"] . "'    ";

        $result_pqk = mysqli_query($conn, $sql_pqk);

        $sql_cqk = "select * from CenterQuarkyKits   WHERE QuarkyKitID='" . $row_10P["QuarkyKitID"] . "'    ";

        $result_cqk = mysqli_query($conn, $sql_cqk);

        if (mysqli_num_rows($result_pqk) > 0) {
            $curl_post_data = array(
                'Success' => 'false',
                'Reason' => 'Kit Alredy Registered'
            );

            echo json_encode($curl_post_data);
        } else if (mysqli_num_rows($result_cqk) > 0) {
            $curl_post_data = array(
                'Success' => 'false',
                'Reason' => 'Kit Alredy Registered'
            );

            echo json_encode($curl_post_data);
        } else if ($row_10P["MaximumStudents"] === $row_10P["RegisteredStudents"]) {
            $curl_post_data = array(
                'Success' => 'false',
                'Reason' => 'Students Have Maximised Out'
            );

            echo json_encode($curl_post_data);
        } else {

            if ($_GET["loginRegister"] == "false") {
                $sql = "select * from parents   WHERE p_email='" . $_GET["EmailLogin"] . "'  AND  p_password='" . md5($_GET["PasswordLogin"]) . "'  ";
                $result = mysqli_query($conn, $sql);
                if (mysqli_num_rows($result) > 0) {
                    while ($row = mysqli_fetch_assoc($result)) {
                        $sql_we1 = 'INSERT INTO ParentQuarkyKits VALUES (NULL,
                            "' . $row_10P["QuarkyKitID"] . '",
                            "' . $row["parent_id"] . '",
                            "false",
                            "false",
                            now())';
                        if (mysqli_query($conn, $sql_we1)) {
                        }
                        $sql_qs_1 = 'INSERT INTO QuarkySold VALUES (NULL,
                            "' . $row_10P["QuarkyKitID"] . '",
                            "Assigned",
                            "' . $_GET["DefaultPrice"] . '",
                            "' . $_GET["Shipping"] . '",
                            "' . $_GET["Totalprice"] . '",
                            "Parent",
                            "' . $row["parent_id"] . '",
                            "' . $_GET["Delivery"] . '",
                            "' . $_GET["Address"] . '",
                            "' . $_GET["RecipientPhone"] . '",
                            "",
                            "",
                            "",
                            "",
                            "",
                            "false",
                            "false",
                            now())';
                        if (mysqli_query($conn, $sql_qs_1)) {
                            $QuarkySoldID = mysqli_insert_id($conn);
                            $usedpushstk = pushStkPayment($_GET["mPesaPhone"], $_GET["Totalprice"], $QuarkySoldID, $_GET["NoKits"]);

                            $curl_post_data = array(
                                'Success' => 'true',
                                'MerchantRequestID' => $usedpushstk["MerchantRequestID"],
                                'CheckoutRequestID' => $usedpushstk["CheckoutRequestID"],
                                'FirstName' => $_GET["center_name"],
                                'Email' => $_GET["center_email"],
                                'Phone' => $_GET['mPesaPhone'],
                                'ResultCode' => '123456789',
                            );
                            echo json_encode($curl_post_data);
                        }
                    }
                }
            } else {
                $sql = "select * from parents WHERE p_email='" . $_GET["Email"] . "' ";

                $result = mysqli_query($conn, $sql);
                if (mysqli_num_rows($result) > 0) {
                    while ($row = mysqli_fetch_assoc($result)) {
                        $sql_we1 = 'INSERT INTO ParentQuarkyKits VALUES (NULL,
                            "' . $row_10P["QuarkyKitID"] . '",
                            "' . $row["parent_id"] . '",
                            "false",
                            "false",
                            now())';
                        if (mysqli_query($conn, $sql_we1)) {
                        }
                        $sql_qs_1 = 'INSERT INTO QuarkySold VALUES (NULL,
                            "' . $row_10P["QuarkyKitID"] . '",
                            "Assigned",
                            "' . $_GET["DefaultPrice"] . '",
                            "' . $_GET["Shipping"] . '",
                            "' . $_GET["Totalprice"] . '",
                            "Parent",
                            "' . $row["parent_id"] . '",
                            "' . $_GET["Delivery"] . '",
                            "' . $_GET["Address"] . '",
                            "' . $_GET["RecipientPhone"] . '",
                            "",
                            "",
                            "",
                            "",
                            "",
                            "false",
                            "false",
                            now())';
                        if (mysqli_query($conn, $sql_qs_1)) {
                            $QuarkySoldID = mysqli_insert_id($conn);
                            $usedpushstk = pushStkPayment($_GET["mPesaPhone"], $_GET["Totalprice"], $QuarkySoldID, $_GET["NoKits"]);

                            $curl_post_data = array(
                                'Success' => 'true',
                                'MerchantRequestID' => $usedpushstk["MerchantRequestID"],
                                'CheckoutRequestID' => $usedpushstk["CheckoutRequestID"],
                                'FirstName' => $_GET["center_name"],
                                'Email' => $_GET["center_email"],
                                'Phone' => $_GET['mPesaPhone'],
                                'ResultCode' => '123456789',
                            );
                            echo json_encode($curl_post_data);
                        }
                    }
                } else {
                    $sql_we1 = 'INSERT INTO parents VALUES (NULL,
                    "' . $_GET["FirstName"] . '",
                    "' . $_GET["LastName"] . '",
                    "' . $_GET["Email"] . '",
                    "' . $_GET["Phone"] . '",
                    "assets/img/fav.png",
                    "' . $_GET["IDNumber"] . '",
                    "",
                    "' . $_GET["Gender"] . '",
                    "No",
                    "None",
                    "' . $_GET["Address"] . '",
                    "True",
                    "",
                    "' . md5($result_pass) . '",
                    "true", 
                    "true",
                    "false",
                    "false",
                    now())';
                    if (mysqli_query($conn, $sql_we1)) {
                        $parent_id = mysqli_insert_id($conn);
                        try {
                            $mail = new PHPMailer(true);

                            //Server settings
                            $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
                            $mail->isSMTP();                                            //Send using SMTP
                            $mail->Host = 'digifunzi.com';                     //Set the SMTP server to send through
                            $mail->SMTPAuth = true;                                   //Enable SMTP authentication
                            $mail->Username = 'support@digifunzi.com';                     //SMTP username
                            $mail->Password = 'ZS4nGyfzf(aj';                               //SMTP password
                            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
                            $mail->Port = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

                            //Recipients
                            $mail->setFrom('support@digifunzi.com', 'Digifunzi');
                            $mail->addAddress(trim($_GET["Email"]), $_GET["FirstName"]);     //Add a recipient
                            $mail->addReplyTo('support@digifunzi.com', 'Information');

                            $mail->isHTML(true);                                  //Set email format to HTML
                            $mail->Subject = 'You Have Enrolled to Digifunzi';
                            $mail->Body = '<!DOCTYPE html>
                        <html>
                        
                        <head>
                            <title></title>
                            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                            <meta name="viewport" content="width=device-width, initial-scale=1">
                            <meta http-equiv="X-UA-Compatible" content="IE=edge" />
                            <link href="https://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet">
                            <style type="text/css">
                            
                        
                                body,
                                table,
                                td,
                                a {
                                    -webkit-text-size-adjust: 100%;
                                    -ms-text-size-adjust: 100%;
                                }
                        
                                table,
                                td {
                                    mso-table-lspace: 0pt;
                                    mso-table-rspace: 0pt;
                                }
                        
                                img {
                                    -ms-interpolation-mode: bicubic;
                                }
                        
                                img {
                                    border: 0;
                                    height: auto;
                                    line-height: 100%;
                                    outline: none;
                                    text-decoration: none;
                                }
                        
                                table {
                                    border-collapse: collapse !important;
                                }
                        
                                body {
                                    height: 100% !important;
                                    margin: 0 !important;
                                    padding: 0 !important;
                                    width: 100% !important;
                                }
                        
                                a[x-apple-data-detectors] {
                                    color: inherit !important;
                                    text-decoration: none !important;
                                    font-size: inherit !important;
                                    font-family: inherit !important;
                                    font-weight: inherit !important;
                                    line-height: inherit !important;
                                }
                                @media screen and (max-width:600px) {
                                    h1 {
                                        font-size: 32px !important;
                                        line-height: 32px !important;
                                    }
                                }
                                div[style*="margin: 16px 0;"] {
                                    margin: 0 !important;
                                }
                            </style>
                        </head>
                    
                        <body style="background-color: #f4f4f4; margin: 0 !important; padding: 0 !important;">
                            <div style="display: none; font-size: 1px; color: #fefefe; line-height: 1px;  font-family: Comfortaa; max-height: 0px; max-width: 0px; opacity: 0; overflow: hidden;">
                            </div>
                            <table border="0" cellpadding="0" cellspacing="0" width="100%">
                                <tr>
                                    <td bgcolor="#b6e8f3" align="center">
                                        <table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;">
                                            <tr>
                                                <td align="center" valign="top" style="padding: 40px 10px 40px 10px;"> </td>
                                            </tr>
                                        </table> 
                                    </td>
                                </tr>
                                <tr>
                                    <td bgcolor="#b6e8f3" align="center" style="padding: 0px 10px 0px 10px;">
                                        <table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;">
                                            <tr>
                                                <td bgcolor="#ffffff" align="center" valign="top" style="padding: 40px 20px 20px 20px; border-radius: 4px 4px 0px 0px; color: #111111;  font-family: Comfortaa; font-size: 48px; font-weight: 400; letter-spacing: 4px; line-height: 48px;">
                                                    <h1 style="font-size: 48px; font-weight: 400; margin: 2;">Welcome!</h1> <img src=" https://app.digifunzi.com/assets/img/digifunzi-transparent.png" width="125" height="120" style="display: block; border: 0px;" />
                                                </td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
                                <tr>
                                    <td bgcolor="#f4f4f4" align="center" style="padding: 0px 10px 0px 10px;">
                                        <table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;">
                                            <tr>
                                                <td bgcolor="#ffffff" align="left" style="padding: 20px 30px 40px 30px; color: #666666;  font-family: Comfortaa; font-size: 18px; font-weight: 400; line-height: 25px;">
                                                    <p style="margin: 0;">Were excited to have you get started. First, Login to your account with the login details below and choose your own password. </p>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td bgcolor="#ffffff" align="left" style="padding:  20px 30px 40px 30px; color: #666666;  font-family: Comfortaa; font-size: 18px; font-weight: 400; line-height: 25px;">
                                                    <p style="margin: 0;">Email : ' . $_GET["Email"] . '</p>
                                                </td>
                                            </tr>
                                            <tr>
                                            <td bgcolor="#ffffff" align="left" style="padding: 0px 30px 20px 30px; color: #666666;  font-family: Comfortaa; font-size: 18px; font-weight: 400; line-height: 25px;">
                                                <p style="margin: 0;">OTP Code : ' . $result_pass . '</p>
                                            </td>
                                        </tr>
                                            <tr>
                                                <td bgcolor="#ffffff" align="left">
                                                    <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                                        <tr>
                                                            <td bgcolor="#ffffff" align="center" style="padding: 20px 30px 60px 30px;">
                                                                <table border="0" cellspacing="0" cellpadding="0">
                                                                    <tr>
                                                                        <td align="center" style="border-radius: 3px;" bgcolor="#1e88e5">
                                                                        <a href="' . $EmailUrl . 'newaccount" target="_blank" 
                                                                        style="font-size: 20px; font-family: Helvetica, Arial, sans-serif; color: #ffffff; text-decoration: none; color: #ffffff; text-decoration: none; padding: 15px 25px; border-radius: 2px; border: 1px solid #1e88e5; display: inline-block;">Login</a></td>
                                                                    </tr>
                                                                </table>
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </td>
                                            </tr> 
                                            <tr>
                                                <td bgcolor="#ffffff" align="left" style="padding: 0px 30px 0px 30px; color: #666666;  font-family: Comfortaa; font-size: 18px; font-weight: 400; line-height: 25px;">
                                                    <p style="margin: 0;">If that doesnt work, copy and paste the following link in your browser:</p>
                                                </td>
                                            </tr> 
                                            <tr>
                                                <td bgcolor="#ffffff" align="left" style="padding: 20px 30px 20px 30px; color: #666666;  font-family: Comfortaa; font-size: 18px; font-weight: 400; line-height: 25px;">
                                                    <p style="margin: 0;"><a href="#" target="_blank" style="color: #FFA73B;">' . $EmailUrl . 'newaccount</a></p>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td bgcolor="#ffffff" align="left" style="padding: 0px 30px 20px 30px; color: #666666;  font-family: Comfortaa; font-size: 18px; font-weight: 400; line-height: 25px;">
                                                    <p style="margin: 0;">If you have any questions, contact us on +254-790-25-25-23 ; were always happy to help out.</p>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td bgcolor="#ffffff" align="left" style="padding: 0px 30px 40px 30px; border-radius: 0px 0px 4px 4px; color: #666666;  font-family: Comfortaa; font-size: 18px; font-weight: 400; line-height: 25px;">
                                                    <p style="margin: 0;"> Regards,<br>Digifunzi Team</p>
                                                </td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
                                <tr>
                                    <td bgcolor="#f4f4f4" align="center" style="padding: 30px 10px 0px 10px;">
                                        <table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;">
                                            <tr>
                                                <td bgcolor="#b6e8f3" align="center" style="padding: 30px 30px 30px 30px; border-radius: 4px 4px 4px 4px; color: #666666;  font-family: Comfortaa; font-size: 18px; font-weight: 400; line-height: 25px;">
                                                    <h2 style="font-size: 20px; font-weight: 400; color: #111111; margin: 0;">Need more help?</h2>
                                                    <p style="margin: 0;"><a href="#" target="_blank" style="color: #FFA73B;">Email us info@digifunzi.com </a></p>
                                                </td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
                                
                            </table>
                        </body>
                        
                        
                        </html>';
                            $mail->SMTPDebug = 0;
                            $mail->send();
                            //    header("Location: ./?center=".$_GET["center"]."&enrolled=true&date=".strtotime( date("Y/m/d h:i:s")));
                            // echo 'Message has been sent';
                        } catch (Exception $e) {
                        }
                        $sql_pqk = 'INSERT INTO ParentQuarkyKits VALUES (NULL,
                        "' . $row_10P["QuarkyKitID"] . '",
                        "' . $parent_id . '",
                        "false",
                        "false",
                        now())';
                        if (mysqli_query($conn, $sql_pqk)) {
                        }
                        $sql_qs_1 = 'INSERT INTO QuarkySold VALUES (NULL,
                            "' . $row_10P["QuarkyKitID"] . '",
                            "Assigned",
                            "' . $_GET["DefaultPrice"] . '",
                            "' . $_GET["Shipping"] . '",
                            "' . $_GET["Totalprice"] . '",
                            "Parent",
                            "' . $parent_id . '",
                            "' . $_GET["Delivery"] . '",
                            "' . $_GET["Address"] . '",
                            "' . $_GET["RecipientPhone"] . '",
                            "",
                            "",
                            "",
                            "",
                            "",
                            "false",
                            "false",
                            now())';
                        if (mysqli_query($conn, $sql_qs_1)) {
                            $QuarkySoldID = mysqli_insert_id($conn);
                            $usedpushstk = pushStkPayment($_GET["mPesaPhone"], $_GET["Totalprice"], $QuarkySoldID, $_GET["NoKits"]);

                            $curl_post_data = array(
                                'Success' => 'true',
                                'MerchantRequestID' => $usedpushstk["MerchantRequestID"],
                                'CheckoutRequestID' => $usedpushstk["CheckoutRequestID"],
                                'FirstName' => $_GET["center_name"],
                                'Email' => $_GET["center_email"],
                                'Phone' => $_GET['mPesaPhone'],
                                'ResultCode' => '123456789',
                            );
                            echo json_encode($curl_post_data);
                        }
                    }
                }
            }
        }
    }
} else {
    if ($_GET['SelectKit'] === "true") {
        if ($_GET["loginRegister"] == "false") {

            $sql = "select * from parents   WHERE p_email='" . $_GET["EmailLogin"] . "'  AND  p_password='" . md5($_GET["PasswordLogin"]) . "'  ";
            $result = mysqli_query($conn, $sql);
            if (mysqli_num_rows($result) > 0) {
                while ($row = mysqli_fetch_assoc($result)) {
                    $sql_we1 = 'INSERT INTO ParentQuarkyKits VALUES (NULL,
                            "",
                            "' . $row["parent_id"] . '",
                            "false",
                            "false",
                            now())';
                    if (mysqli_query($conn, $sql_we1)) {
                    }
                    $sql_qs_1 = 'INSERT INTO QuarkySold VALUES (NULL,
                        "",
                        "Unassigned",
                        "' . $_GET["DefaultPrice"] . '",
                        "' . $_GET["Shipping"] . '",
                        "' . $_GET["Totalprice"] . '",
                        "Parent",
                        "' . $row["parent_id"] . '",
                        "' . $_GET["Delivery"] . '",
                        "' . $_GET["Address"] . '",
                        "' . $_GET["RecipientPhone"] . '",
                        "",
                        "",
                        "",
                        "",
                        "",
                        "false",
                        "false",
                        now())';
                    if (mysqli_query($conn, $sql_qs_1)) {
                        $QuarkySoldID = mysqli_insert_id($conn);
                        $usedpushstk = pushStkPayment($_GET["mPesaPhone"], $_GET["Totalprice"], $QuarkySoldID, $_GET["NoKits"]);

                        $curl_post_data = array(
                            'Success' => 'true',
                            'MerchantRequestID' => $usedpushstk["MerchantRequestID"],
                            'CheckoutRequestID' => $usedpushstk["CheckoutRequestID"],
                            'FirstName' => $_GET["center_name"],
                            'Email' => $_GET["center_email"],
                            'Phone' => $_GET['mPesaPhone'],
                            'ResultCode' => '123456789',
                        );
                        echo json_encode($curl_post_data);
                    }
                }
            }
        } else {
            $sql = "select * from parents   WHERE p_email='" . $_GET["Email"] . "'     ";
            $result = mysqli_query($conn, $sql);
            if (mysqli_num_rows($result) > 0) {
                while ($row = mysqli_fetch_assoc($result)) {
                    $sql_we1 = 'INSERT INTO ParentQuarkyKits VALUES (NULL,
                            "",
                            "' . $row["parent_id"] . '",
                            "false",
                            "false",
                            now())';
                    if (mysqli_query($conn, $sql_we1)) {
                    }
                    $sql_qs_1 = 'INSERT INTO QuarkySold VALUES (NULL,
                        "",
                        "Unassigned",
                        "' . $_GET["DefaultPrice"] . '",
                        "' . $_GET["Shipping"] . '",
                        "' . $_GET["Totalprice"] . '",
                        "Parent",
                        "' . $row["parent_id"] . '",
                        "' . $_GET["Delivery"] . '",
                        "' . $_GET["Address"] . '",
                        "' . $_GET["RecipientPhone"] . '",
                        "",
                        "",
                        "",
                        "",
                        "",
                        "false",
                        "false",
                        now())';
                    if (mysqli_query($conn, $sql_qs_1)) {
                        $QuarkySoldID = mysqli_insert_id($conn);
                        $usedpushstk = pushStkPayment($_GET["mPesaPhone"], $_GET["Totalprice"], $QuarkySoldID, $_GET["NoKits"]);

                        $curl_post_data = array(
                            'Success' => 'true',
                            'MerchantRequestID' => $usedpushstk["MerchantRequestID"],
                            'CheckoutRequestID' => $usedpushstk["CheckoutRequestID"],
                            'FirstName' => $_GET["center_name"],
                            'Email' => $_GET["center_email"],
                            'Phone' => $_GET['mPesaPhone'],
                            'ResultCode' => '123456789',
                        );
                        echo json_encode($curl_post_data);
                    }
                }
            } else {
                $sql_we1 = 'INSERT INTO parents VALUES (NULL,
                "' . $_GET["FirstName"] . '",
                "' . $_GET["LastName"] . '",
                "' . $_GET["Email"] . '",
                "' . $_GET["Phone"] . '",
                "assets/img/fav.png",
                "' . $_GET["IDNumber"] . '",
                "",
                "' . $_GET["Gender"] . '",
                "No",
                "None",
                "' . $_GET["Address"] . '",
                "True",
                "",
                "' . md5($result_pass) . '",
                "true", 
                "true",
                "false",
                "false",
                now())';
                if (mysqli_query($conn, $sql_we1)) {
                    $parent_id = mysqli_insert_id($conn);
                    try {
                        $mail = new PHPMailer(true);

                        //Server settings
                        $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
                        $mail->isSMTP();                                            //Send using SMTP
                        $mail->Host = 'digifunzi.com';                     //Set the SMTP server to send through
                        $mail->SMTPAuth = true;                                   //Enable SMTP authentication
                        $mail->Username = 'support@digifunzi.com';                     //SMTP username
                        $mail->Password = 'ZS4nGyfzf(aj';                               //SMTP password
                        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
                        $mail->Port = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

                        //Recipients
                        $mail->setFrom('support@digifunzi.com', 'Digifunzi');
                        $mail->addAddress(trim($_GET["Email"]), $_GET["FirstName"]);     //Add a recipient
                        $mail->addReplyTo('support@digifunzi.com', 'Information');

                        $mail->isHTML(true);                                  //Set email format to HTML
                        $mail->Subject = 'You Have Enrolled to Digifunzi';
                        $mail->Body = '<!DOCTYPE html>
                        <html>
                        
                        <head>
                            <title></title>
                            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                            <meta name="viewport" content="width=device-width, initial-scale=1">
                            <meta http-equiv="X-UA-Compatible" content="IE=edge" />
                            <link href="https://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet">
                            <style type="text/css">
                            
                        
                                body,
                                table,
                                td,
                                a {
                                    -webkit-text-size-adjust: 100%;
                                    -ms-text-size-adjust: 100%;
                                }
                        
                                table,
                                td {
                                    mso-table-lspace: 0pt;
                                    mso-table-rspace: 0pt;
                                }
                        
                                img {
                                    -ms-interpolation-mode: bicubic;
                                }
                        
                                img {
                                    border: 0;
                                    height: auto;
                                    line-height: 100%;
                                    outline: none;
                                    text-decoration: none;
                                }
                        
                                table {
                                    border-collapse: collapse !important;
                                }
                        
                                body {
                                    height: 100% !important;
                                    margin: 0 !important;
                                    padding: 0 !important;
                                    width: 100% !important;
                                }
                        
                                a[x-apple-data-detectors] {
                                    color: inherit !important;
                                    text-decoration: none !important;
                                    font-size: inherit !important;
                                    font-family: inherit !important;
                                    font-weight: inherit !important;
                                    line-height: inherit !important;
                                }
                                @media screen and (max-width:600px) {
                                    h1 {
                                        font-size: 32px !important;
                                        line-height: 32px !important;
                                    }
                                }
                                div[style*="margin: 16px 0;"] {
                                    margin: 0 !important;
                                }
                            </style>
                        </head>
                    
                        <body style="background-color: #f4f4f4; margin: 0 !important; padding: 0 !important;">
                            <div style="display: none; font-size: 1px; color: #fefefe; line-height: 1px;  font-family: Comfortaa; max-height: 0px; max-width: 0px; opacity: 0; overflow: hidden;">
                            </div>
                            <table border="0" cellpadding="0" cellspacing="0" width="100%">
                                <tr>
                                    <td bgcolor="#b6e8f3" align="center">
                                        <table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;">
                                            <tr>
                                                <td align="center" valign="top" style="padding: 40px 10px 40px 10px;"> </td>
                                            </tr>
                                        </table> 
                                    </td>
                                </tr>
                                <tr>
                                    <td bgcolor="#b6e8f3" align="center" style="padding: 0px 10px 0px 10px;">
                                        <table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;">
                                            <tr>
                                                <td bgcolor="#ffffff" align="center" valign="top" style="padding: 40px 20px 20px 20px; border-radius: 4px 4px 0px 0px; color: #111111;  font-family: Comfortaa; font-size: 48px; font-weight: 400; letter-spacing: 4px; line-height: 48px;">
                                                    <h1 style="font-size: 48px; font-weight: 400; margin: 2;">Welcome!</h1> <img src=" https://app.digifunzi.com/assets/img/digifunzi-transparent.png" width="125" height="120" style="display: block; border: 0px;" />
                                                </td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
                                <tr>
                                    <td bgcolor="#f4f4f4" align="center" style="padding: 0px 10px 0px 10px;">
                                        <table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;">
                                            <tr>
                                                <td bgcolor="#ffffff" align="left" style="padding: 20px 30px 40px 30px; color: #666666;  font-family: Comfortaa; font-size: 18px; font-weight: 400; line-height: 25px;">
                                                    <p style="margin: 0;">Were excited to have you get started. First, Login to your account with the login details below and choose your own password. </p>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td bgcolor="#ffffff" align="left" style="padding:  20px 30px 40px 30px; color: #666666;  font-family: Comfortaa; font-size: 18px; font-weight: 400; line-height: 25px;">
                                                    <p style="margin: 0;">Email : ' . $_GET["Email"] . '</p>
                                                </td>
                                            </tr>
                                            <tr>
                                            <td bgcolor="#ffffff" align="left" style="padding: 0px 30px 20px 30px; color: #666666;  font-family: Comfortaa; font-size: 18px; font-weight: 400; line-height: 25px;">
                                                <p style="margin: 0;">OTP Code : ' . $result_pass . '</p>
                                            </td>
                                        </tr>
                                            <tr>
                                                <td bgcolor="#ffffff" align="left">
                                                    <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                                        <tr>
                                                            <td bgcolor="#ffffff" align="center" style="padding: 20px 30px 60px 30px;">
                                                                <table border="0" cellspacing="0" cellpadding="0">
                                                                    <tr>
                                                                        <td align="center" style="border-radius: 3px;" bgcolor="#1e88e5">
                                                                        <a href="https://lms.digifunzi.com/newaccount" target="_blank" 
                                                                        style="font-size: 20px; font-family: Helvetica, Arial, sans-serif; color: #ffffff; text-decoration: none; color: #ffffff; text-decoration: none; padding: 15px 25px; border-radius: 2px; border: 1px solid #1e88e5; display: inline-block;">Login</a></td>
                                                                    </tr>
                                                                </table>
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </td>
                                            </tr> 
                                            <tr>
                                                <td bgcolor="#ffffff" align="left" style="padding: 0px 30px 0px 30px; color: #666666;  font-family: Comfortaa; font-size: 18px; font-weight: 400; line-height: 25px;">
                                                    <p style="margin: 0;">If that doesnt work, copy and paste the following link in your browser:</p>
                                                </td>
                                            </tr> 
                                            <tr>
                                                <td bgcolor="#ffffff" align="left" style="padding: 20px 30px 20px 30px; color: #666666;  font-family: Comfortaa; font-size: 18px; font-weight: 400; line-height: 25px;">
                                                    <p style="margin: 0;"><a href="#" target="_blank" style="color: #FFA73B;">https://lms.digifunzi.com/newaccount</a></p>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td bgcolor="#ffffff" align="left" style="padding: 0px 30px 20px 30px; color: #666666;  font-family: Comfortaa; font-size: 18px; font-weight: 400; line-height: 25px;">
                                                    <p style="margin: 0;">If you have any questions, contact us on +254-790-25-25-23 ; were always happy to help out.</p>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td bgcolor="#ffffff" align="left" style="padding: 0px 30px 40px 30px; border-radius: 0px 0px 4px 4px; color: #666666;  font-family: Comfortaa; font-size: 18px; font-weight: 400; line-height: 25px;">
                                                    <p style="margin: 0;"> Regards,<br>Digifunzi Team</p>
                                                </td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
                                <tr>
                                    <td bgcolor="#f4f4f4" align="center" style="padding: 30px 10px 0px 10px;">
                                        <table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;">
                                            <tr>
                                                <td bgcolor="#b6e8f3" align="center" style="padding: 30px 30px 30px 30px; border-radius: 4px 4px 4px 4px; color: #666666;  font-family: Comfortaa; font-size: 18px; font-weight: 400; line-height: 25px;">
                                                    <h2 style="font-size: 20px; font-weight: 400; color: #111111; margin: 0;">Need more help?</h2>
                                                    <p style="margin: 0;"><a href="#" target="_blank" style="color: #FFA73B;">Email us info@digifunzi.com </a></p>
                                                </td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
                                
                            </table>
                        </body>
                        
                        
                        </html>';
                        $mail->SMTPDebug = 0;
                        $mail->send();
                        //    header("Location: ./?center=".$_GET["center"]."&enrolled=true&date=".strtotime( date("Y/m/d h:i:s")));
                        // echo 'Message has been sent';
                    } catch (Exception $e) {
                    }
                    $sql_pqk = 'INSERT INTO ParentQuarkyKits VALUES (NULL,
                        "",
                        "' . $parent_id . '",
                        "false",
                        "false",
                        now())';
                    if (mysqli_query($conn, $sql_pqk)) {
                    }
                    $sql_qs_1 = 'INSERT INTO QuarkySold VALUES (NULL,
                    "",
                    "Unassigned",
                    "' . $_GET["DefaultPrice"] . '",
                    "' . $_GET["Shipping"] . '",
                    "' . $_GET["Totalprice"] . '",
                    "Parent",
                    "' . $parent_id . '",
                    "' . $_GET["Delivery"] . '",
                    "' . $_GET["Address"] . '",
                    "' . $_GET["RecipientPhone"] . '",
                    "",
                    "",
                    "",
                    "",
                    "",
                    "false",
                    "false",
                    now())';
                    if (mysqli_query($conn, $sql_qs_1)) {
                        $QuarkySoldID = mysqli_insert_id($conn);
                        $usedpushstk = pushStkPayment($_GET["mPesaPhone"], $_GET["Totalprice"], $QuarkySoldID, $_GET["NoKits"]);

                        $curl_post_data = array(
                            'Success' => 'true',
                            'MerchantRequestID' => $usedpushstk["MerchantRequestID"],
                            'CheckoutRequestID' => $usedpushstk["CheckoutRequestID"],
                            'FirstName' => $_GET["center_name"],
                            'Email' => $_GET["center_email"],
                            'Phone' => $_GET['mPesaPhone'],
                            'ResultCode' => '123456789',
                        );
                        echo json_encode($curl_post_data);
                    }
                }
            }
        }
    } else {
        $curl_post_data = array(
            'Success' => 'false',
            'Reason' => 'QR Codes Not Found',
            'usedcode' => 'false ',
        );

        echo json_encode($curl_post_data);
    }
}













// }


// echo json_encode($data);
