<?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");
require '../../../../vendor/autoload.php';
include '../../../../config/index.php';
// $data = array();
$data = file_get_contents('php://input');
$obj = json_decode($data, true);


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

function getCompletionCertificate($selfPacedAdultStudent_id, $AdultStudent_id, $course_id)
{
    try {
        include '../../../../config/index.php';
        $LearnerName = "";
        $CourseName = "";
        $sql_d = "SELECT * FROM AdultStudents WHERE AdultStudent_id='" . $AdultStudent_id . "'";
        $result_d = mysqli_query($conn, $sql_d);
        if (mysqli_num_rows($result_d) > 0) {
            while ($row_d = mysqli_fetch_assoc($result_d)) {
                $LearnerName = $row_d["FirstName"] . " " . $row_d["LastName"];
            }
        }

        $sql_sfm = "SELECT * FROM courses WHERE course_id='" . $course_id . "'";

        $result_sfm = mysqli_query($conn, $sql_sfm);
        if (mysqli_num_rows($result_sfm) > 0) {
            while ($row_sfm = mysqli_fetch_assoc($result_sfm)) {
                $CourseName = $row_sfm["course_name"];
            }
        }

        $url = "https://digicerts.digifunzi.com/api/starter/certificate";

        $postData = [
            "LearnerType" => "AdultStudent",
            "LearnerName" => $LearnerName,
            "CourseName" => $CourseName,
            "CertNo" =>   str_pad($selfPacedAdultStudent_id, 4, '0', STR_PAD_LEFT),

        ];

        $ch = curl_init($url);

        $jsonData = json_encode($postData);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // Return response as string
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($jsonData)
        ]);
        curl_setopt($ch, CURLOPT_POST, true);            // POST request
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); // Attach data

        $response = curl_exec($ch);

        if ($response === false) {
            $error = curl_error($ch);
            curl_close($ch);
            die("cURL Error: " . $error);
        }

        curl_close($ch);

        $responseData = json_decode($response, true);
        $sql_msa = 'INSERT INTO selfPacedAdultCertificate VALUES (NULL,
            "' . $selfPacedAdultStudent_id . '",
            "' . $responseData["location"] . '",
            "Completed",
            NOW(),
            "false",
            "false",
            now())';
        if (mysqli_query($conn, $sql_msa)) {
        }
    } catch (Exception $e) {
        return " ";
    }
}


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;
}
$result_pass = generatePassword();
if ($obj["isLoggedIn"] === "true") {
    $sql = "select * from AdultStudents   WHERE Email='" . $obj["loginEmail"] . "'  AND  Password='" . md5($obj["loginPassword"]) . "'  ";
    $result = mysqli_query($conn, $sql);
    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $invoice_no = $obj["SelfPacedClasses_id"] . $obj["SelfPacedCourses_id"] . date("isv");
            $invoice_date =  date("Y-m-d");
            $invoice_due_date =  date("Y-m-d", strtotime("+1 week",  strtotime($invoice_date)));
            $sql_we = 'INSERT INTO AdultSelfInvoices VALUES (NULL,
                    "' . $row["AdultStudent_id"] . '",
                    "' . $obj["SelfPacedClasses_id"] . '",
                    "' . $obj["SelfPacedCourses_id"] . '", 
                    "' . $obj["Price"] . '",
                    "' . $obj["totalAmount"] . '",
                    "' . $invoice_no . '",
                    "' . $invoice_date . '",
                    "' . $invoice_due_date . '",
                    "Paid", 
                    now())';

            if (mysqli_query($conn, $sql_we)) {
                $AdultSelfInvoice_id = mysqli_insert_id($conn);
                $sql_psi = "SELECT * FROM global_settings ORDER BY dated DESC LIMIT 1 ";
                $result_psi = mysqli_query($conn, $sql_psi);
                if (mysqli_num_rows($result_psi) > 0) {
                    while ($row_psi  = mysqli_fetch_assoc($result_psi)) {
                        $AllCredits = ((int)$row_psi["FreeParentCredits"] / 60) * (int)$row_psi["MentorSessionCreditValue"];
                        $sql_pe = "SELECT * FROM AdultCreditsWallet WHERE AdultStudent_id='" . $row["AdultStudent_id"] . "' ";
                        $result_pe = mysqli_query($conn, $sql_pe);
                        if (mysqli_num_rows($result_pe) > 0) {
                            while ($row_pe = mysqli_fetch_assoc($result_pe)) {
                                $CreditAmount = (int)$row_pe["CreditAmount"] + $AllCreditsCredits;
                                $Credits = (int)$row_pe["Credits"] + $AllCredits;
                                $Available = (int)$row_pe["Available"] + $AllCredits;

                                $sql_pe1 = "UPDATE AdultCreditsWallet SET
                                            CreditAmount=" . ($CreditAmount) . ",
                                            Credits=" . ($Credits) . ",
                                            Available=" . ($Available) . "
                                        WHERE AdultStudent_id='" . $row_pe["AdultStudent_id"] . "' ";
                                if (mysqli_query($conn, $sql_pe1)) {
                                    echo "";
                                }
                            }
                        } else {

                            $sql_we1 = 'INSERT INTO AdultCreditsWallet VALUES (NULL,
                                        "' . $row["AdultStudent_id"] . '",
                                        "' . $AllCredits . '",
                                        "' . $AllCredits . '",
                                        "true",
                                        "0",
                                        "0",
                                        "' . $AllCredits . '",
                                        "false",
                                        "false",
                                        NOW())';
                            if (mysqli_query($conn, $sql_we1)) {
                                echo "";
                            }
                        }
                    }
                }
                $sql_spc = "SELECT * FROM SelfPacedCourses  WHERE SelfPacedCourses_id='" . $obj["SelfPacedCourses_id"] . "' ";
                $result_spc = mysqli_query($conn, $sql_spc);
                if (mysqli_num_rows($result_spc) > 0) {
                    while ($row_spc = mysqli_fetch_assoc($result_spc)) {
                        $sql_cls = "SELECT * FROM SelfPacedClasses  WHERE SelfPacedClasses_id='" . $obj["SelfPacedClasses_id"] . "' ";
                        $result_cls = mysqli_query($conn, $sql_cls);
                        if (mysqli_num_rows($result_cls) > 0) {
                            while ($row_cls = mysqli_fetch_assoc($result_cls)) {
                                $StartDate = date("Y-m-d");
                                $CompletionDate = date("Y-m-d", strtotime("+1 month", strtotime($StartDate)));
                                $sql_upd_spl = 'INSERT INTO selfPacedAdultStudent VALUES(NULL,
                                            "' . $row["AdultStudent_id"] . '",
                                            "' . $obj["SelfPacedClasses_id"] . '",
                                            "' . $obj["SelfPacedCourses_id"] . '",
                                            "false",
                                            "true",
                                            "' . $row_cls["PassMark"] . '",
                                            "' . $StartDate . '",
                                            "' . $CompletionDate . '",
                                            "0",
                                            "true",
                                            "false",
                                            "false", 
                                            "false", 
                                            NOW())';

                                if (mysqli_query($conn, $sql_upd_spl)) {
                                    $selfPacedAdultStudent_id = mysqli_insert_id($conn);
                                    $sql_clp = "SELECT * FROM course_lesson_plan WHERE course_id='" . $row_spc["courses_id"] . "'";
                                    $result_clp = mysqli_query($conn, $sql_clp);
                                    if (mysqli_num_rows($result_clp) > 0) {
                                        while ($row_clp = mysqli_fetch_assoc($result_clp)) {
                                            getCompletionCertificate($selfPacedAdultStudent_id, $row["AdultStudent_id"], $row_spc["course_id"]);

                                            $sql_upd_spls = 'INSERT INTO selfPacedAdultStudentSession VALUES(NULL,
                                                        "' . $selfPacedAdultStudent_id . '",
                                                        "' . $row["AdultStudent_id"] . '",
                                                        "' . $obj["SelfPacedCourses_id"] . '",
                                                        "' . $row_clp["course_lesson_plan_id"] . '",
                                                        "0",
                                                        "false",
                                                        NOW(),
                                                        "false",
                                                        "false", 
                                                        "false", 
                                                        NOW())';

                                            if (mysqli_query($conn, $sql_upd_spls)) {
                                                $selfPacedLearnerSession_id = mysqli_insert_id($conn);
                                            }
                                            $sql_i = 'INSERT INTO selfPacedAdultStudentAssignment VALUES (NULL,
                                                        "' . $selfPacedAdultStudent_id . '",
                                                        "' . $row["AdultStudent_id"] . '",
                                                        "' . $obj["SelfPacedCourses_id"] . '",
                                                        "' . $row_clp["course_lesson_plan_id"] . '",
                                                        "",
                                                        "Issued",
                                                        "",
                                                        now(),
                                                        "false",
                                                        "false",
                                                        "false",
                                                        now())';

                                            if (mysqli_query($conn, $sql_i)) {
                                                $selfPacedAdultStudentAssignment_id = mysqli_insert_id($conn);
                                                $sql_spa = 'INSERT INTO selfPacedAdultStudentAssignmentRating VALUES (NULL,
                                                            "' . $selfPacedAdultStudentAssignment_id . '",
                                                            "0",
                                                            "0",
                                                            "0",
                                                            "0",
                                                            "0",
                                                            "0",
                                                            "0",
                                                            "", 
                                                            "false",
                                                            "false",
                                                            "false",
                                                            now())';

                                                if (mysqli_query($conn, $sql_spa)) {
                                                }
                                                $sql_clp_1 = "SELECT * FROM LessonAssignmentChecklist WHERE course_id='" . $row_spc["courses_id"] . "' AND  course_lesson_plan_id='" . $row_clp["course_lesson_plan_id"] . "' AND  SelfPacedCourses_id='" . $obj["SelfPacedCourses_id"] . "' ";
                                                $result_clp_1 = mysqli_query($conn, $sql_clp_1);
                                                if (mysqli_num_rows($result_clp_1) > 0) {
                                                    while ($row_clp_1 = mysqli_fetch_assoc($result_clp_1)) {
                                                        $sql_spa_1 = 'INSERT INTO selfPacedAdultStudentAssignmentChecklist VALUES (NULL,
                                                                    "' . $selfPacedAdultStudentAssignment_id . '",
                                                                    "' . $row_clp_1["LessonAssignmentChecklist_id"] . '",
                                                                    "false",
                                                                    "false",
                                                                    "false",
                                                                    "false",
                                                                    now())';

                                                        if (mysqli_query($conn, $sql_spa_1)) {
                                                        }
                                                    }
                                                }
                                            }
                                            $i = $i + 1;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                $sql_rc = "INSERT INTO RedeemedCoupons VALUES (NULL,
                            '" . $obj["appliedCoupon"]["Coupon_id"] . "',
                            '" . $row["AdultStudent_id"] . "',
                            'AdultStudent',
                            'AdultSelfInvoices',
                            '" .  $AdultSelfInvoice_id . "',
                             'AdultSelfMpesa',
                            '',
                            now(),
                            '" . $obj["appliedDiscount"] . "',
                            '" . $obj["totalAmount"]  . "',
                            'Redeemed',
                            'false',
                            'false', 
                            now())";
                if (mysqli_query($conn, $sql_rc)) {
                    $sql_20 = 'UPDATE Coupons SET Status="Redeemed" , Updated=NOW() WHERE Coupon_id="' . $obj["appliedCoupon"]["Coupon_id"] . '"   ';
                    if (mysqli_query($conn, $sql_20)) {
                    }
                }
                if ($obj["paymentPlan"] === "installments") {
                    $RemainingAMount = 0;
                    $CouponUsed = "false";
                    $Coupon_id = "";
                    if ((int) $obj["appliedDiscount"] > 0) {
                        $CouponUsed = "true";
                        $Coupon_id =  $obj["appliedCoupon"]["Coupon_id"];
                    }
                    if ((int) $obj["installmentOption"] > 1) {
                        $RemainingAMount = ((int) $obj["totalAmount"] * (int)$obj["installmentOption"]) - (int)$obj["installmentOption"];
                    }
                    $sql_spi = "INSERT INTO SelfPartialInstallments VALUES (NULL,
                                '" . $obj["installmentOption"] . "',
                                '1',
                                '" . $obj["totalAmount"] . "',
                                '" . $obj["CutOffDays"]  . "',
                                now(),
                                DATE_ADD(CURDATE(), INTERVAL '" . $obj["CutOffDays"]  . "' DAY),
                                'Paying',
                                'B2CSelfpaced',
                                '" . $obj["SelfPacedCourses_id"] . "',
                                '" . $obj["Price"]  . "',
                                '" . $obj["totalAmount"]  . "',
                                '" . $RemainingAMount  . "',
                                'Adult',
                                '" . $AdultStudent_id . "',
                                '" . $AdultSelfInvoice_id . "',
                                '" . $CouponUsed . "',
                                '" . $Coupon_id . "',
                                'false',
                                'false', 
                                'false',
                                'false',
                                now())";


                    if (mysqli_query($conn, $sql_spi)) {
                    }
                }
                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($obj["Email"]), $obj["FirstName"]);     //Add a recipient
                    $mail->addReplyTo('support@digifunzi.com', 'Information');

                    $mail->isHTML(true);                                  //Set email format to HTML
                    $mail->Subject = 'Enrollment Confirmed - Welcome 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/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, Log-in to your account with your login details.</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="#25476A"><a href="' . $EmailUrl . '" 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 #25476A; display: inline-block;">Log-in to your account</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 . '</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=".$obj["center"]."&enrolled=true&date=".strtotime( date("Y/m/d h:i:s")));
                    // echo 'Message has been sent';
                } catch (Exception $e) {
                    //   header("Location: ./?center=".$obj["center"]."&enroll_error=true&date=".strtotime( date("Y/m/d h:i:s")));
                }
                $curl_post_data = array(
                    'Success' => 'true',
                    'Response' => 'You Have Succesfully Registered a new Student',
                );
                echo json_encode($curl_post_data);
            } else {
                $curl_post_data = array(
                    'Success' => 'false',
                    'Response' => 'You Are Unable to Succesfully Registered a new Student, try again Later',
                );
                echo json_encode($curl_post_data);
            }
        }
    }
} else {
    $sql = "select * from AdultStudents   WHERE Email='" . $obj["Email"] . "'  ";
    $result = mysqli_query($conn, $sql);
    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {

            $invoice_no = $obj["SelfPacedClasses_id"] . $obj["SelfPacedCourses_id"] . date("isv");
            $invoice_date =  date("Y-m-d");
            $invoice_due_date =  date("Y-m-d", strtotime("+1 week",  strtotime($invoice_date)));

            $sql_we = 'INSERT INTO AdultSelfInvoices VALUES (NULL,
                        "' . $row["AdultStudent_id"] . '",
                        "' . $obj["SelfPacedClasses_id"] . '",
                        "' . $obj["SelfPacedCourses_id"] . '", 
                        "' . $obj["Price"] . '",
                        "' . $obj["totalAmount"] . '",
                        "' . $invoice_no . '",
                        "' . $invoice_date . '",
                        "' . $invoice_due_date . '",
                        "Paid",
                        now())';

            if (mysqli_query($conn, $sql_we)) {
                $AdultSelfInvoice_id = mysqli_insert_id($conn);
                $sql_spc = "SELECT * FROM SelfPacedCourses  WHERE SelfPacedCourses_id='" . $obj["SelfPacedCourses_id"] . "' ";
                $result_spc = mysqli_query($conn, $sql_spc);
                if (mysqli_num_rows($result_spc) > 0) {
                    while ($row_spc = mysqli_fetch_assoc($result_spc)) {
                        $sql_cls = "SELECT * FROM SelfPacedClasses  WHERE SelfPacedClasses_id='" . $obj["SelfPacedClasses_id"] . "' ";
                        $result_cls = mysqli_query($conn, $sql_cls);
                        if (mysqli_num_rows($result_cls) > 0) {
                            while ($row_cls = mysqli_fetch_assoc($result_cls)) {
                                $StartDate = date("Y-m-d");
                                $CompletionDate = date("Y-m-d", strtotime("+1 month", strtotime($StartDate)));
                                $sql_upd_spl = 'INSERT INTO selfPacedAdultStudent VALUES(NULL,
                                            "' . $row["AdultStudent_id"] . '",
                                            "' . $obj["SelfPacedClasses_id"] . '",
                                            "' . $obj["SelfPacedCourses_id"] . '",
                                            "false",
                                            "true",
                                            "' . $row_cls["PassMark"] . '",
                                            "' . $StartDate . '",
                                            "' . $CompletionDate . '",
                                            "0",
                                            "true",
                                            "false",
                                            "false", 
                                            "false", 
                                            NOW())';

                                if (mysqli_query($conn, $sql_upd_spl)) {
                                    $selfPacedAdultStudent_id = mysqli_insert_id($conn);

                                    $sql_clp = "SELECT * FROM course_lesson_plan WHERE course_id='" . $row_spc["courses_id"] . "'";

                                    $result_clp = mysqli_query($conn, $sql_clp);
                                    if (mysqli_num_rows($result_clp) > 0) {
                                        while ($row_clp = mysqli_fetch_assoc($result_clp)) {
                                            getCompletionCertificate($selfPacedAdultStudent_id, $row["AdultStudent_id"], $row_spc["course_id"]);

                                            $sql_upd_spls = 'INSERT INTO selfPacedAdultStudentSession VALUES(NULL,
                                                        "' . $selfPacedAdultStudent_id . '",
                                                         "' . $row["AdultStudent_id"] . '",
                                                        "' . $obj["SelfPacedCourses_id"] . '",
                                                        "' . $row_clp["course_lesson_plan_id"] . '",
                                                        "0",
                                                        "false",
                                                        NOW(),
                                                        "false",
                                                        "false", 
                                                        "false", 
                                                        NOW())';

                                            if (mysqli_query($conn, $sql_upd_spls)) {
                                                $selfPacedLearnerSession_id = mysqli_insert_id($conn);
                                            }
                                            $sql_i = 'INSERT INTO selfPacedAdultStudentAssignment VALUES (NULL,
                                                        "' . $selfPacedAdultStudent_id . '",
                                                        "' . $row["AdultStudent_id"] . '",
                                                        "' . $obj["SelfPacedCourses_id"] . '",
                                                        "' . $row_clp["course_lesson_plan_id"] . '",
                                                        "",
                                                        "Issued",
                                                        "",
                                                        now(),
                                                        "false",
                                                        "false",
                                                        "false",
                                                        now())';

                                            if (mysqli_query($conn, $sql_i)) {
                                                $selfPacedAdultStudentAssignment_id = mysqli_insert_id($conn);
                                                $sql_spa = 'INSERT INTO selfPacedAdultStudentAssignmentRating VALUES (NULL,
                                                            "' . $selfPacedAdultStudentAssignment_id . '",
                                                            "0",
                                                            "0",
                                                            "0",
                                                            "0",
                                                            "0",
                                                            "0",
                                                            "0",
                                                            "", 
                                                            "false",
                                                            "false",
                                                            "false",
                                                            now())';

                                                if (mysqli_query($conn, $sql_spa)) {
                                                }
                                                $sql_clp_1 = "SELECT * FROM LessonAssignmentChecklist WHERE course_id='" . $row_spc["courses_id"] . "' AND  course_lesson_plan_id='" . $row_clp["course_lesson_plan_id"] . "' AND  SelfPacedCourses_id='" . $obj["SelfPacedCourses_id"] . "' ";
                                                $result_clp_1 = mysqli_query($conn, $sql_clp_1);
                                                if (mysqli_num_rows($result_clp_1) > 0) {
                                                    while ($row_clp_1 = mysqli_fetch_assoc($result_clp_1)) {
                                                        $sql_spa_1 = 'INSERT INTO selfPacedAdultStudentAssignmentChecklist VALUES (NULL,
                                                                    "' . $selfPacedAdultStudentAssignment_id . '",
                                                                    "' . $row_clp_1["LessonAssignmentChecklist_id"] . '",
                                                                    "false",
                                                                    "false",
                                                                    "false",
                                                                    "false",
                                                                    now())';

                                                        if (mysqli_query($conn, $sql_spa_1)) {
                                                        }
                                                    }
                                                }
                                            }
                                            $i = $i + 1;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                $sql_psi = "SELECT * FROM global_settings ORDER BY dated DESC LIMIT 1 ";
                $result_psi = mysqli_query($conn, $sql_psi);
                if (mysqli_num_rows($result_psi) > 0) {
                    while ($row_psi  = mysqli_fetch_assoc($result_psi)) {
                        $AllCredits = ((int)$row_psi["FreeParentCredits"] / 60) * (int)$row_psi["MentorSessionCreditValue"];
                        $sql_pe = "SELECT * FROM AdultCreditsWallet WHERE AdultStudent_id='" . $row["AdultStudent_id"] . "' ";
                        $result_pe = mysqli_query($conn, $sql_pe);
                        if (mysqli_num_rows($result_pe) > 0) {
                            while ($row_pe = mysqli_fetch_assoc($result_pe)) {
                                $CreditAmount = (int)$row_pe["CreditAmount"] + $AllCreditsCredits;
                                $Credits = (int)$row_pe["Credits"] + $AllCredits;
                                $Available = (int)$row_pe["Available"] + $AllCredits;

                                $sql_pe1 = "UPDATE AdultCreditsWallet SET
                                            CreditAmount=" . ($CreditAmount) . ",
                                            Credits=" . ($Credits) . ",
                                            Available=" . ($Available) . "
                                        WHERE AdultStudent_id='" . $row_pe["AdultStudent_id"] . "' ";
                                if (mysqli_query($conn, $sql_pe1)) {
                                    echo "";
                                }
                            }
                        } else {

                            $sql_we1 = 'INSERT INTO AdultCreditsWallet VALUES (NULL,
                                        "' . $row["AdultStudent_id"] . '",
                                        "' . $AllCredits . '",
                                        "' . $AllCredits . '",
                                        "true",
                                        "0",
                                        "0",
                                        "' . $AllCredits . '",
                                        "false",
                                        "false",
                                        NOW())';
                            if (mysqli_query($conn, $sql_we1)) {
                                echo "";
                            }
                        }
                    }
                }
                $sql_rc = "INSERT INTO RedeemedCoupons VALUES (NULL,
                        '" . $obj["appliedCoupon"]["Coupon_id"] . "',
                        '" . $row["AdultStudent_id"] . "',
                        'AdultStudent',
                        'AdultSelfInvoices',
                        '" .  $AdultSelfInvoice_id . "',
                            'AdultSelfMpesa',
                        '',
                        now(),
                        '" . $obj["appliedDiscount"] . "',
                        '" . $obj["totalAmount"]  . "',
                        'Redeemed',
                        'false',
                        'false', 
                        now())";
                if (mysqli_query($conn, $sql_rc)) {
                    $sql_20 = 'UPDATE Coupons SET Status="Redeemed" , Updated=NOW() WHERE Coupon_id="' . $obj["appliedCoupon"]["Coupon_id"] . '"   ';
                    if (mysqli_query($conn, $sql_20)) {
                    }
                }
                if ($obj["paymentPlan"] === "installments") {
                    $RemainingAMount = 0;
                    $CouponUsed = "false";
                    $Coupon_id = "";
                    if ((int) $obj["appliedDiscount"] > 0) {
                        $CouponUsed = "true";
                        $Coupon_id =  $obj["appliedCoupon"]["Coupon_id"];
                    }
                    if ((int) $obj["installmentOption"] > 1) {
                        $RemainingAMount = ((int) $obj["totalAmount"] * (int)$obj["installmentOption"]) - (int)$obj["installmentOption"];
                    }
                    $sql_spi = "INSERT INTO SelfPartialInstallments VALUES (NULL,
                            '" . $obj["installmentOption"] . "',
                                '1',
                            '" . $obj["totalAmount"] . "',
                            '" . $obj["CutOffDays"]  . "',
                            now(),
                            DATE_ADD(CURDATE(), INTERVAL '" . $obj["CutOffDays"]  . "' DAY),
                            'Paying',
                            'B2CSelfpaced',
                            '" . $obj["SelfPacedCourses_id"] . "',
                            '" . $obj["Price"]  . "',
                            '" . $obj["totalAmount"]  . "',
                            '" . $RemainingAMount  . "',
                            'Adult',
                            '" . $AdultStudent_id . "',
                            '" . $AdultSelfInvoice_id . "',
                            '" . $CouponUsed . "',
                            '" . $Coupon_id . "',
                            'false',
                            'false', 
                            'false',
                            'false',
                            now())";


                    if (mysqli_query($conn, $sql_spi)) {
                    }
                }
                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($obj["Email"]), $obj["FirstName"]);     //Add a recipient
                    $mail->addReplyTo('support@digifunzi.com', 'Information');

                    $mail->isHTML(true);                                  //Set email format to HTML
                    $mail->Subject = 'Enrollment Confirmed - Welcome 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/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, Log-in to your account with your login details.</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="#25476A"><a href="' . $EmailUrl . '" 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 #25476A; display: inline-block;">Log-in to your account</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 . '</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=".$obj["center"]."&enrolled=true&date=".strtotime( date("Y/m/d h:i:s")));
                    // echo 'Message has been sent';
                } catch (Exception $e) {
                    //   header("Location: ./?center=".$obj["center"]."&enroll_error=true&date=".strtotime( date("Y/m/d h:i:s")));
                }
                $curl_post_data = array(
                    'Success' => 'true',
                    'Response' => 'You Have Succesfully Registered a new Student',
                );
                echo json_encode($curl_post_data);
            } else {
                $curl_post_data = array(
                    'Success' => 'false',
                    'Response' => 'You Are Unable to Succesfully Registered a new Student, try again Later',
                );
                echo json_encode($curl_post_data);
            }
        }
    } else {

        $invoice_no = $obj["SelfPacedClasses_id"] . $obj["SelfPacedCourses_id"] . date("isv");
        $invoice_date =  date("Y-m-d");
        $invoice_due_date =  date("Y-m-d", strtotime("+1 week",  strtotime($invoice_date)));
        if (
            !empty($obj["Email"]) &&
            !empty($obj["FirstName"]) &&
            !empty($obj["Password"])
        ) {
            $sql_we1 = 'INSERT INTO AdultStudents VALUES (NULL,
                "' . $obj["FirstName"] . '",
                "' . $obj["LastName"] . '",
                "' . $obj["Gender"] . '",
                "' . $obj["Email"] . '",
                "' . $obj["PhoneNumber"] . '",
                "' . $obj["Location"] . '",
                "",
                "assets/img/fav.png",
                "' . md5($obj["Password"]) . '",
                "true", 
                "' . $obj["IDNumber"] . '", 
                "No",
                "None",
                "false",
                "false",
                "false",
                "false",
                "false",
                "false",
                "false",
                now())';
            if (mysqli_query($conn, $sql_we1)) {
                $AdultStudent_id = mysqli_insert_id($conn);

                $sql_we = 'INSERT INTO AdultSelfInvoices VALUES (NULL,
                            "' . $AdultStudent_id . '",
                            "' . $obj["SelfPacedClasses_id"] . '",
                            "' . $obj["SelfPacedCourses_id"] . '", 
                            "' . $obj["Price"] . '",
                            "' . $obj["totalAmount"] . '",
                            "' . $invoice_no . '",
                            "' . $invoice_date . '",
                            "' . $invoice_due_date . '",
                            "Paid",
                            now())';

                if (mysqli_query($conn, $sql_we)) {
                    $AdultSelfInvoice_id = mysqli_insert_id($conn);
                    $sql_spc = "SELECT * FROM SelfPacedCourses  WHERE SelfPacedCourses_id='" . $obj["SelfPacedCourses_id"] . "' ";
                    $result_spc = mysqli_query($conn, $sql_spc);
                    if (mysqli_num_rows($result_spc) > 0) {
                        while ($row_spc = mysqli_fetch_assoc($result_spc)) {
                            $sql_cls = "SELECT * FROM SelfPacedClasses  WHERE SelfPacedClasses_id='" . $obj["SelfPacedClasses_id"] . "' ";
                            $result_cls = mysqli_query($conn, $sql_cls);
                            if (mysqli_num_rows($result_cls) > 0) {
                                while ($row_cls = mysqli_fetch_assoc($result_cls)) {
                                    $StartDate = date("Y-m-d");
                                    $CompletionDate = date("Y-m-d", strtotime("+1 month", strtotime($StartDate)));
                                    $sql_upd_spl = 'INSERT INTO selfPacedAdultStudent VALUES(NULL,
                                            "' . $AdultStudent_id . '",
                                            "' . $obj["SelfPacedClasses_id"] . '",
                                            "' . $obj["SelfPacedCourses_id"] . '",
                                            "false",
                                            "true",
                                            "' . $row_cls["PassMark"] . '",
                                            "' . $StartDate . '",
                                            "' . $CompletionDate . '",
                                            "0",
                                            "true",
                                            "false",
                                            "false", 
                                            "false", 
                                            NOW())';

                                    if (mysqli_query($conn, $sql_upd_spl)) {
                                        $selfPacedAdultStudent_id = mysqli_insert_id($conn);

                                        $sql_clp = "SELECT * FROM course_lesson_plan WHERE course_id='" . $row_spc["courses_id"] . "'";

                                        $result_clp = mysqli_query($conn, $sql_clp);
                                        if (mysqli_num_rows($result_clp) > 0) {
                                            while ($row_clp = mysqli_fetch_assoc($result_clp)) {
                                                getCompletionCertificate($selfPacedAdultStudent_id, $AdultStudent_id, $row_spc["course_id"]);

                                                $sql_upd_spls = 'INSERT INTO selfPacedAdultStudentSession VALUES(NULL,
                                                        "' . $selfPacedAdultStudent_id . '",
                                                        "' . $AdultStudent_id . '",
                                                        "' . $obj["SelfPacedCourses_id"] . '",
                                                        "' . $row_clp["course_lesson_plan_id"] . '",
                                                        "0",
                                                        "false",
                                                        NOW(),
                                                        "false",
                                                        "false", 
                                                        "false", 
                                                        NOW())';

                                                if (mysqli_query($conn, $sql_upd_spls)) {
                                                    $selfPacedLearnerSession_id = mysqli_insert_id($conn);
                                                }
                                                $sql_i = 'INSERT INTO selfPacedAdultStudentAssignment VALUES (NULL,
                                                        "' . $selfPacedAdultStudent_id . '",
                                                        "' . $AdultStudent_id . '",
                                                        "' . $obj["SelfPacedCourses_id"] . '",
                                                        "' . $row_clp["course_lesson_plan_id"] . '",
                                                        "",
                                                        "Issued",
                                                        "",
                                                        now(),
                                                        "false",
                                                        "false",
                                                        "false",
                                                        now())';

                                                if (mysqli_query($conn, $sql_i)) {
                                                    $selfPacedAdultStudentAssignment_id = mysqli_insert_id($conn);
                                                    $sql_spa = 'INSERT INTO selfPacedAdultStudentAssignmentRating VALUES (NULL,
                                                            "' . $selfPacedAdultStudentAssignment_id . '",
                                                            "0",
                                                            "0",
                                                            "0",
                                                            "0",
                                                            "0",
                                                            "0",
                                                            "0",
                                                            "", 
                                                            "false",
                                                            "false",
                                                            "false",
                                                            now())';

                                                    if (mysqli_query($conn, $sql_spa)) {
                                                    }
                                                    $sql_clp_1 = "SELECT * FROM LessonAssignmentChecklist WHERE course_id='" . $row_spc["courses_id"] . "' AND  course_lesson_plan_id='" . $row_clp["course_lesson_plan_id"] . "' AND  SelfPacedCourses_id='" . $obj["SelfPacedCourses_id"] . "' ";
                                                    $result_clp_1 = mysqli_query($conn, $sql_clp_1);
                                                    if (mysqli_num_rows($result_clp_1) > 0) {
                                                        while ($row_clp_1 = mysqli_fetch_assoc($result_clp_1)) {
                                                            $sql_spa_1 = 'INSERT INTO selfPacedAdultStudentAssignmentChecklist VALUES (NULL,
                                                                    "' . $selfPacedAdultStudentAssignment_id . '",
                                                                    "' . $row_clp_1["LessonAssignmentChecklist_id"] . '",
                                                                    "false",
                                                                    "false",
                                                                    "false",
                                                                    "false",
                                                                    now())';

                                                            if (mysqli_query($conn, $sql_spa_1)) {
                                                            }
                                                        }
                                                    }
                                                }
                                                $i = $i + 1;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    $sql_psi = "SELECT * FROM global_settings ORDER BY dated DESC LIMIT 1 ";
                    $result_psi = mysqli_query($conn, $sql_psi);
                    if (mysqli_num_rows($result_psi) > 0) {
                        while ($row_psi  = mysqli_fetch_assoc($result_psi)) {
                            $AllCredits = ((int)$row_psi["FreeParentCredits"] / 60) * (int)$row_psi["MentorSessionCreditValue"];
                            $sql_pe = "SELECT * FROM AdultCreditsWallet WHERE AdultStudent_id='" . $AdultStudent_id . "' ";
                            $result_pe = mysqli_query($conn, $sql_pe);
                            if (mysqli_num_rows($result_pe) > 0) {
                                while ($row_pe = mysqli_fetch_assoc($result_pe)) {
                                    $CreditAmount = (int)$row_pe["CreditAmount"] + $AllCreditsCredits;
                                    $Credits = (int)$row_pe["Credits"] + $AllCredits;
                                    $Available = (int)$row_pe["Available"] + $AllCredits;

                                    $sql_pe1 = "UPDATE AdultCreditsWallet SET
                                            CreditAmount=" . ($CreditAmount) . ",
                                            Credits=" . ($Credits) . ",
                                            Available=" . ($Available) . "
                                        WHERE AdultStudent_id='" . $row_pe["AdultStudent_id"] . "' ";
                                    if (mysqli_query($conn, $sql_pe1)) {
                                        echo "";
                                    }
                                }
                            } else {

                                $sql_we1 = 'INSERT INTO AdultCreditsWallet VALUES (NULL,
                                        "' . $AdultStudent_id . '",
                                        "' . $AllCredits . '",
                                        "' . $AllCredits . '",
                                        "true",
                                        "0",
                                        "0",
                                        "' . $AllCredits . '",
                                        "false",
                                        "false",
                                        NOW())';
                                if (mysqli_query($conn, $sql_we1)) {
                                    echo "";
                                }
                            }
                        }
                    }
                    $sql_rc = "INSERT INTO RedeemedCoupons VALUES (NULL,
                            '" . $obj["appliedCoupon"]["Coupon_id"] . "',
                            '" . $AdultStudent_id . "',
                            'AdultStudent',
                            'AdultSelfInvoices',
                            '" .  $AdultSelfInvoice_id . "',
                            'AdultSelfMpesa',
                            '',
                            now(),
                            '" . $obj["appliedDiscount"] . "',
                            '" . $obj["totalAmount"]  . "',
                            'Redeemed',
                            'false',
                            'false', 
                            now())";
                    if (mysqli_query($conn, $sql_rc)) {
                        $sql_20 = 'UPDATE Coupons SET Status="Redeemed" , Updated=NOW() WHERE Coupon_id="' . $obj["appliedCoupon"]["Coupon_id"] . '"   ';
                        if (mysqli_query($conn, $sql_20)) {
                        }
                    }
                    if ($obj["paymentPlan"] === "installments") {
                        $RemainingAMount = 0;
                        $CouponUsed = "false";
                        $Coupon_id = "";
                        if ((int) $obj["appliedDiscount"] > 0) {
                            $CouponUsed = "true";
                            $Coupon_id =  $obj["appliedCoupon"]["Coupon_id"];
                        }
                        if ((int) $obj["installmentOption"] > 1) {
                            $RemainingAMount = ((int) $obj["totalAmount"] * (int)$obj["installmentOption"]) - (int)$obj["installmentOption"];
                        }
                        $sql_spi = "INSERT INTO SelfPartialInstallments VALUES (NULL,
                                '" . $obj["installmentOption"] . "',
                                '1',
                                '" . $obj["totalAmount"] . "',
                                '" . $obj["CutOffDays"]  . "',
                                now(),
                                DATE_ADD(CURDATE(), INTERVAL '" . $obj["CutOffDays"]  . "' DAY),
                                'Paying',
                                'B2CSelfpaced',
                                '" . $obj["SelfPacedCourses_id"] . "',
                                '" . $obj["Price"]  . "',
                                '" . $obj["totalAmount"]  . "',
                                '" . $RemainingAMount  . "',
                                'Adult',
                                '" . $AdultStudent_id . "',
                                '" . $AdultSelfInvoice_id . "',
                                '" . $CouponUsed . "',
                                '" . $Coupon_id . "',
                                'false',
                                'false', 
                                'false',
                                'false',
                                now())";


                        if (mysqli_query($conn, $sql_spi)) {
                        }
                    }
                    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($obj["Email"]), $obj["FirstName"]);     //Add a recipient
                        $mail->addReplyTo('support@digifunzi.com', 'Information');

                        $mail->isHTML(true);                                  //Set email format to HTML
                        $mail->Subject = 'Enrollment Confirmed - Welcome 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/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, Log-in to your account with the login details you created.</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="#25476A"><a href="' . $EmailUrl . '" 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 #25476A; display: inline-block;">Log-in to your account</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 . '</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=".$obj["center"]."&enrolled=true&date=".strtotime( date("Y/m/d h:i:s")));
                        // echo 'Message has been sent';
                    } catch (Exception $e) {
                        //   header("Location: ./?center=".$obj["center"]."&enroll_error=true&date=".strtotime( date("Y/m/d h:i:s")));
                    }
                    $curl_post_data = array(
                        'Success' => 'true',
                        'Response' => 'You Have Succesfully Registered a new Student',
                    );
                    echo json_encode($curl_post_data);
                } else {
                    $curl_post_data = array(
                        'Success' => 'false',
                        'Response' => 'You Are Unable to Succesfully Registered a new Student, try again Later',
                    );
                    echo json_encode($curl_post_data);
                }
            }
        } else {
            $curl_post_data = array(
                'Success' => 'false',
                'Response' => 'You Are Unable to Succesfully Registered a new Student, try again Later',
            );
            echo json_encode($curl_post_data);
        }
    }
}
