<?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 = file_get_contents('php://input');

$obj = json_decode($data, true);
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";

        // Data to send in POST request
        $postData = [
            "LearnerType" => "AdultStudent",
            "LearnerName" => $LearnerName,
            "CourseName" => $CourseName,
            "CertNo" =>   str_pad($selfPacedAdultStudent_id, 4, '0', STR_PAD_LEFT),

        ];

        // Initialize cURL
        $ch = curl_init($url);

        // Encode data as JSON
        $jsonData = json_encode($postData);

        // cURL options
        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

        // Execute the request and wait for response
        $response = curl_exec($ch);

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

        // Close cURL
        curl_close($ch);

        // Decode JSON response (if API returns JSON)
        $responseData = json_decode($response, true);




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

$sql_10 = "SELECT * FROM AdultCreditsWallet WHERE AdultStudent_id='" . $obj["AdultStudent_id"] . "' ";

$result_10 = mysqli_query($conn, $sql_10);
if (mysqli_num_rows($result_10) > 0) {
    while ($row_10 = mysqli_fetch_assoc($result_10)) {
        $Used =  (int)$row_10["Used"] + (int)$obj["Credits"];
        $Available =  (int)$row_10["Available"] - (int)$obj["Credits"];
        $Previously_available = (int)$row_10["Available"];
        $sql_we1 = 'INSERT INTO AdultCreditsTracking VALUES (NULL,
                "' . $row_10["AdultCreditsWallet_id"] . '",
                "' . $obj["AdultStudent_id"] . '", 
                "", 
                "' . $obj["SelfPacedCourses_id"] . '",
                "Purchased",
                "' . (int)$obj["Credits"] . '",
                "false",
                "false",
                NOW())';

        if (mysqli_query($conn, $sql_we1)) {
        }

        $sql_we1 = 'UPDATE  AdultCreditsWallet SET
                        Used="' . $Used . '",
                        Available="' . $Available . '"
                        WHERE AdultStudent_id="' . $obj["AdultStudent_id"] . '"';

        if (mysqli_query($conn, $sql_we1)) {

            $course_name = "";
            $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_spc_10 = "select * from courses WHERE course_id='" . $row_spc["courses_id"] . "'  ";
                    $result_spc_10 = mysqli_query($conn, $sql_spc_10);
                    if (mysqli_num_rows($result_spc_10) > 0) {
                        while ($row_spc_10 = mysqli_fetch_assoc($result_spc_10)) {
                            $course_name = $row_spc_10["course_name"];
                        }
                    }

                    $sql_cls = "SELECT * FROM SelfPacedClasses  WHERE SelfPacedClasses_id='" . $row_spc["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,
                                "' . $obj["AdultStudent_id"] . '",
                                "' . $row_spc["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);
                                getCompletionCertificate($selfPacedAdultStudent_id, $obj["AdultStudent_id"], $row_spc["course_id"]);

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

                                        $sql_upd_spls = 'INSERT INTO selfPacedAdultStudentSession VALUES(NULL,
                                            "' . $selfPacedAdultStudent_id . '",
                                            "' . $obj["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)) {
                                            $selfPacedAdultStudentSession_id = mysqli_insert_id($conn);
                                        }
                                        $sql_i = 'INSERT INTO selfPacedAdultStudentAssignment VALUES (NULL,
                                                "' . $selfPacedAdultStudent_id . '",
                                                "' . $obj["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_c10 = "select * from AdultStudents WHERE AdultStudent_id='" . $obj["AdultStudent_id"] . "'  ";
            $result_c10 = mysqli_query($conn, $sql_c10);
            if (mysqli_num_rows($result_c10) > 0) {
                while ($row_c10 = mysqli_fetch_assoc($result_c10)) {
                    $learner_name = $row_c10["learner_name"];
                    $learner_last_name = $row_c10["learner_last_name"];

                    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`
                        $mail->setFrom('support@digifunzi.com', 'Digifunzi');
                        $mail->addAddress($row_pts["Email"], $row_pts["FirstName"]);     //Add a recipient
                        $mail->addReplyTo('support@digifunzi.com', 'Information');
                        $mail->isHTML(true);                                  //Set email format to HTML
                        $mail->Subject = 'Course Purchase Notification';
                        $mail->Body    = '<!DOCTYPE html>
                            <html>
                            
                            <head>
                                <title>Course Purchase Notification</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;">Course Enrolled!</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;">We are writing to inform you have successfully enrolled in to a new self-paced course. Here are the complete details: </p>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td bgcolor="#ffffff" align="center" style="padding:  0px 30px 20px 30px;">
                                                        <table border="0" cellpadding="0" cellspacing="0" width="100%" style="border: 1px solid #e0e0e0; max-width: 600px;">
                                                            <!-- Table Header -->
                                                            <tr>
                                                                <td bgcolor="#25476a" align="center" colspan="2" style="padding: 12px 15px; color: #ffffff; font-family: Comfortaa; font-size: 15px; font-weight: 600;">
                                                                    Purchase Summary
                                                                </td>
                                                            </tr>
                                                            <!-- Purchase Date & Time -->
                                                            <tr>
                                                                <td bgcolor="#f8fafc" align="left" style="padding: 12px 15px; color: #666666; font-family: Comfortaa; font-size: 14px;">
                                                                    Purchase Date & Time
                                                                </td>
                                                                <td bgcolor="#ffffff" align="left" style="padding: 12px 15px; color: #25476a; font-family: Comfortaa; font-size: 16px; font-weight: 600;">
                                                                    ' . date("M j, Y • g:i A", strtotime(date("Y-m-d H:i:s"))) . '
                                                                </td>
                                                            </tr>
                                                            <!-- Learner Name -->
                                                            <tr>
                                                                <td bgcolor="#f8fafc" align="left" style="padding: 12px 15px; color: #666666; font-family: Comfortaa; font-size: 14px;">
                                                                    Learner Name
                                                                </td>
                                                                <td bgcolor="#ffffff" align="left" style="padding: 12px 15px; color: #25476a; font-family: Comfortaa; font-size: 16px; font-weight: 600;">
                                                                    ' . $row_c10["FirstName"] . ' ' . $row_c10["LastName"] . '
                                                                </td>
                                                            </tr>
                                                            <!-- Credits Used -->
                                                            <tr>
                                                                <td bgcolor="#f8fafc" align="left" style="padding: 12px 15px; color: #666666; font-family: Comfortaa; font-size: 14px;">
                                                                    Credits Used
                                                                </td>
                                                                <td bgcolor="#ffffff" align="left" style="padding: 12px 15px; color: #38aae1; font-family: Comfortaa; font-size: 16px; font-weight: 600;">
                                                                ' . number_format((int)$obj["Credits"]) . ' Credits
                                                                </td>
                                                            </tr>
                                                            <!-- Course Name -->
                                                            <tr>
                                                                <td bgcolor="#f8fafc" align="left" style="padding: 12px 15px; color: #666666; font-family: Comfortaa; font-size: 14px;">
                                                                    Course Name
                                                                </td>
                                                                <td bgcolor="#ffffff" align="left" style="padding: 12px 15px; color: #25476a; font-family: Comfortaa; font-size: 16px; font-weight: 600;">
                                                                    ' . $course_name . '
                                                                </td>
                                                            </tr>
                                                        </table>
                                                    </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();
                    } catch (Exception $e) {
                        //   header("Location: ./?center=".$_GET["center"]."&enroll_error=true&date=".strtotime( date("Y/m/d h:i:s")));
                    }
                }
            }
            $curl_post_data = array(
                'Success' => 'true',
                'Reason' => 'You Have Succesfully Booked an Online Session with a technical mentor',

            );
            echo json_encode($curl_post_data);
        } else {
            $curl_GET_data = array(
                'Success' => 'false',
                'Reason' => 'Unable to create session, please try again later',
                'mentor_id' => '',
            );
            echo json_encode($curl_GET_data);
        }
    }
}
