<?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 generatePassword($length = 6)
{
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $count = mb_strlen($chars);

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

    return $result;
}
function getCurrentClasses($class_id, $Streams_id, $center_id)
{
    include '../../../config/index.php';

    if ($Streams_id !== "") {
        $sql10 = "SELECT * FROM centerClasses WHERE class_id='" . $class_id . "' AND Streams_id='" . $Streams_id . "' AND center_id='" . $center_id . "' ORDER BY dated DESC LIMIT 1";
        // return (" sql 10" . $sql10);
        $result10 = mysqli_query($conn, $sql10);
        if (mysqli_num_rows($result10) > 0) {
            while ($row10 = mysqli_fetch_assoc($result10)) {
                $todaysDate = date("Y-m-d");
                $StartDate = date("Y-m-d", strtotime($row_enr["StartDate"]));

                $year = date("Y-m-d", strtotime($todaysDate));

                $sql_enr = "SELECT * FROM curriculumSession WHERE  curriculumEnrollment_id='" . $row10["curriculumEnrollment_id"] . "'  ";

                $result_enr = mysqli_query($conn, $sql_enr);
                if (mysqli_num_rows($result_enr) > 0) {
                    while ($row_enr = mysqli_fetch_assoc($result_enr)) {
                        $StartDate = date("Y", strtotime($row_enr["EndDate"]));

                        $year = date("Y", strtotime($todaysDate));

                        // if ($StartDate >= $year) {
                        //     return ($row10["centerClasses_id"]  );

                        // }
                        if ($StartDate >= $year) {
                            $curl_post_data = array(
                                'centerClasses_id' => $row10["centerClasses_id"],
                                'curriculumEnrollment_id' => $row_enr["curriculumEnrollment_id"],
                                'SessionName' => $row_enr["SessionName"],
                                'StartDate' => $row_enr["StartDate"],
                                'EndDate' => $row_enr["EndDate"]

                            );

                            return ($row10["centerClasses_id"]);
                        }
                    }
                }
            }
        } else {
            $sql10 = "SELECT * FROM centerClasses WHERE class_id='" . $class_id . "'  AND center_id='" . $center_id . "' ";

            $result10 = mysqli_query($conn, $sql10);
            if (mysqli_num_rows($result10) > 0) {
                while ($row10 = mysqli_fetch_assoc($result10)) {
                    $todaysDate = date("Y-m-d");
                    $StartDate = date("Y-m-d", strtotime($row_enr["StartDate"]));

                    $year = date("Y-m-d", strtotime($todaysDate));

                    $sql_enr = "SELECT * FROM curriculumSession WHERE  curriculumEnrollment_id='" . $row10["curriculumEnrollment_id"] . "'  ";

                    $result_enr = mysqli_query($conn, $sql_enr);
                    if (mysqli_num_rows($result_enr) > 0) {
                        while ($row_enr = mysqli_fetch_assoc($result_enr)) {
                            $StartDate = date("Y", strtotime($row_enr["EndDate"]));

                            $year = date("Y", strtotime($todaysDate));
                            // return (" StartDate  " .  $StartDate. " : year  " .  $year);
                            if ($StartDate >= $year) {
                                $curl_post_data = array(
                                    'centerClasses_id' => $row10["centerClasses_id"],
                                    'curriculumEnrollment_id' => $row_enr["curriculumEnrollment_id"],
                                    'SessionName' => $row_enr["SessionName"],
                                    'StartDate' => $row_enr["StartDate"],
                                    'EndDate' => $row_enr["EndDate"]

                                );

                                return ($row10["centerClasses_id"]);
                            }
                        }
                    }
                }
            }
        }
    } else {
        $sql10 = "SELECT * FROM centerClasses WHERE class_id='" . $class_id . "'  AND center_id='" . $center_id . "' ";
        $result10 = mysqli_query($conn, $sql10);
        if (mysqli_num_rows($result10) > 0) {
            while ($row10 = mysqli_fetch_assoc($result10)) {
                $todaysDate = date("Y-m-d");
                $StartDate = date("Y-m-d", strtotime($row_enr["StartDate"]));

                $year = date("Y-m-d", strtotime($todaysDate));

                $sql_enr = "SELECT * FROM curriculumSession WHERE  curriculumEnrollment_id='" . $row10["curriculumEnrollment_id"] . "'  ";

                $result_enr = mysqli_query($conn, $sql_enr);
                if (mysqli_num_rows($result_enr) > 0) {
                    while ($row_enr = mysqli_fetch_assoc($result_enr)) {
                        $StartDate = date("Y", strtotime($row_enr["EndDate"]));

                        $year = date("Y", strtotime($todaysDate));
                        if ($StartDate >= $year) {
                            $curl_post_data = array(
                                'centerClasses_id' => $row10["centerClasses_id"],
                                'curriculumEnrollment_id' => $row_enr["curriculumEnrollment_id"],
                                'SessionName' => $row_enr["SessionName"],
                                'StartDate' => $row_enr["StartDate"],
                                'EndDate' => $row_enr["EndDate"]

                            );

                            return ($row10["centerClasses_id"]);
                        }
                    }
                }
            }
        }
    }
}
function sendAnEmail($Email, $FirstName, $LastName, $result_pass, $EmailUrl)
{
    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($Email), $FirstName . " " . $LastName);     //Add a recipient
        $mail->addReplyTo('support@digifunzi.com', 'Information');

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

$result_d = mysqli_query($conn, $sql_d);
if (mysqli_num_rows($result_d) === 0) {

    $sql_prnt = "INSERT INTO parents VALUES (NULL,
        '" . $obj['FirstName'] . "',
        '" . $obj['LastName'] . "',
        '" . $obj["Email"] . "',
        '" . $obj["PhoneNumber"] . "', 
        'assets/img/fav.png',
        '" . $obj["IDNumber"] . "', 
        '" . $obj["DateOfBirthString"] . "', 
        '" . $obj["Gender"] . "', 
        'No', 
        'None', 
        '" . $obj["Location"] . "', 
        'true', 
        '" . $obj["Relationship"] . "',
        '" . md5($result_pass) . "',
        'true',
        'false', 
        'false', 
        'false', 
        now())";
    if (mysqli_query($conn, $sql_prnt)) {
        $parent_id = mysqli_insert_id($conn);
        $curl_post_data = array(
            'Success' => 'true',
            'Reason' => 'You Were Succesfully in Adding a Parent',
            'parent_id' =>  $parent_id
        );
        echo json_encode($curl_post_data);

        sendAnEmail($obj["Email"], $obj["FirstName"], $obj["LastName"],  $result_pass, $EmailUrl);

        foreach ($obj["Students"] as $newobj) {
            $class_id = $newobj['class_id'];
            $Streams_id = $newobj['Streams_id'];
            $center_id = $_GET['center_id'];
            $centerClasses_id = getCurrentClasses($class_id, $Streams_id, $center_id);
            if (isset($class_id)) {
                $sql_student = "INSERT INTO students VALUES (NULL,
                NULL,
                '" . $_GET['center_id'] . "',
                '" . $centerClasses_id . "',
                '" . $newobj["FirstName"] . "',
                '" . $newobj["LastName"] . "', 
                '" . $newobj["Gender"] . "', 
                'No', 
                'None', 
                '', 
                '" . $newobj["DateOfBirthString"] . "', 
                'assets/img/fav.png',
                'True', 
                'False', 
                '" . $newobj["Username"] . "', 
                '" . md5($newobj["Password"]) . "',
                'False',
                'false', 
                'false', 
                'false', 
                'false', 
                'false', 
                now())";

                if (mysqli_query($conn, $sql_student)) {
                    $student_id = mysqli_insert_id($conn);
                    $sqlps = "INSERT INTO ParentStudents VALUES (NULL,
                    '" . $parent_id . "',
                    '" . $student_id . "',
                    '" . $_GET["center_id"] . "',
                    '" . $obj["Relationship"] . "', 
                    'false', 
                    now())";

                    if (mysqli_query($conn, $sqlps)) {
                        $ParentStudents_id = mysqli_insert_id($conn);
                        $sql_s_u = "UPDATE students SET ParentStudents_id='" . $ParentStudents_id  . "' WHERE student_id='" . $student_id . "'";

                        if (mysqli_query($conn, $sql_s_u)) {
                            $ParentStudents_id = mysqli_insert_id($conn);
                        }
                    }
                }
            } else {
                $sqlps = "INSERT INTO ParentStudents VALUES (NULL,
                    '" . $parent_id . "',
                    '',
                    '" . $_GET["center_id"] . "',
                    '" . $obj["Relationship"] . "', 
                    'false', 
                    now())";

                if (mysqli_query($conn, $sqlps)) {
                }
            }
        }
    } else {
        $curl_post_data = array(
            'Success' => 'false',
            'Reason' => 'You Were Unable to Succesfully Add a Parent',
            'student_id' => '',
        );
        echo json_encode($curl_post_data);
    }
} else {
    $curl_post_data = array(
        'Success' => 'false',
        'Reason' => 'Parent Aleready Exists in the System',
        'student_id' => '',
    );
    echo json_encode($curl_post_data);
}
