<?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;
    }
    $result_pass = generatePassword();
    $sql_d="SELECT * FROM parents WHERE p_email='".$obj["Editp_email"]."' ORDER BY dated DESC limit 1";
    $result_d = mysqli_query($conn, $sql_d);  
    if (mysqli_num_rows($result_d) > 0) {
        while($row_d = mysqli_fetch_assoc($result_d)) {
            $sql = "UPDATE students SET
                parent_id='".$row_d['parent_id']."',
                centerClasses_id='".$obj['EditcenterClasses_id']."',
                learner_name='".$obj["Editlearner_name"]."',
                learner_last_name='".$obj["Editlearner_last_name"]."',
                learner_age='".$obj["Editdob"]."',
                username='".$obj["Editusername"]."'
                WHERE student_id='".$obj["Editstudent_id"]."'
                ";
       
            if (mysqli_query($conn, $sql)) {
                $curl_post_data = array(
                    'Success' => 'true',
                    'Reason' => 'You Have Succesfully Edited '.$obj["Editlearner_name"]." ".$obj["Editlearner_last_name"],
                    'student_id' => $obj["Editstudent_id"] 
                );
                echo json_encode($curl_post_data);  
            } else {
        
                $curl_post_data = array(
                    'Success' => 'false',
                    'Reason' => 'You Were Unsuccesfull in Editing '.$obj["Editlearner_name"]." ".$obj["Editlearner_last_name"]." Kindly contact Admin For Help",
                    'student_id' =>$obj["Editstudent_id"], 
                );
                echo json_encode($curl_post_data);              
            }
        }
    }else{
        if(!empty($obj["Editp_email"])) {
            $sql = "INSERT INTO parents VALUES (NULL,
                '".$obj['Editp_name']."',
                '".$obj['Editp_last_name']."',
                '".$obj["Editp_email"]."',
                '".$obj["Editp_phone"]."', 
                'assets/img/fav.png',
                '".md5($result_pass)."',
                'true',
                'false', 
                'false', 
                'false', 
                now())";
            
            if (mysqli_query($conn, $sql)) {
                $parent_id = mysqli_insert_id($conn);
                try {
                    $mail = new PHPMailer(true);        
                
                    //Server settings
                    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
                    $mail->isSMTP();                                            //Send using SMTP
                    $mail->Host       = 'digifunzi.com';                     //Set the SMTP server to send through
                    $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
                    $mail->Username   = 'support@digifunzi.com';                     //SMTP username
                    $mail->Password   = 'ZS4nGyfzf(aj';                               //SMTP password
                    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
                    $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

                    //Recipients
                    $mail->setFrom('support@digifunzi.com', 'Digifunzi');
                    $mail->addAddress(trim($obj["Editp_email"]), $obj["Editp_name"]." ".$obj["Editp_last_name"]);     //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 : '.$obj["Editp_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")));
                }
                $sqlstdntedit = "UPDATE students SET
                    parent_id='".$parent_id."',
                    centerClasses_id='".$obj['EditcenterClasses_id']."',
                    learner_name='".$obj["Editlearner_name"]."',
                    learner_last_name='".$obj["Editlearner_last_name"]."',
                    learner_age='".$obj["Editdob"]."',
                    username='".$obj["Editusername"]."'
                    WHERE student_id='".$obj["Editstudent_id"]."'
                    ";
            
                if (mysqli_query($conn, $sqlstdntedit)) {
                    $curl_post_data = array(
                        'Success' => 'true',
                        'Reason' => 'You Have Succesfully Edited '.$obj["Editlearner_name"]." ".$obj["Editlearner_last_name"],
                        'student_id' => $obj["Editstudent_id"] 
                    );
                    echo json_encode($curl_post_data);  
                } else {

                    $curl_post_data = array(
                        'Success' => 'false',
                        'Reason' => 'You Were Unsuccesfull in Editing '.$obj["Editlearner_name"]." ".$obj["Editlearner_last_name"]." Kindly contact Admin For Help",
                        'student_id' =>$obj["Editstudent_id"], 
                    );
                    echo json_encode($curl_post_data);              
                }
            }
        }else{
            $sqlstdntedit = "UPDATE students SET 
                    centerClasses_id='".$obj['EditcenterClasses_id']."',
                    learner_name='".$obj["Editlearner_name"]."',
                    learner_last_name='".$obj["Editlearner_last_name"]."',
                    learner_age='".$obj["Editdob"]."',
                    username='".$obj["Editusername"]."'
                    WHERE student_id='".$obj["Editstudent_id"]."'
                    ";
            
                if (mysqli_query($conn, $sqlstdntedit)) {
                    $curl_post_data = array(
                        'Success' => 'true',
                        'Reason' => 'You Have Succesfully Edited '.$obj["Editlearner_name"]." ".$obj["Editlearner_last_name"],
                        'student_id' => $obj["Editstudent_id"] 
                    );
                    echo json_encode($curl_post_data);  
                } else {

                    $curl_post_data = array(
                        'Success' => 'false',
                        'Reason' => 'You Were Unsuccesfull in Editing '.$obj["Editlearner_name"]." ".$obj["Editlearner_last_name"]." Kindly contact Admin For Help",
                        'student_id' =>$obj["Editstudent_id"], 
                    );
                    echo json_encode($curl_post_data);              
                }  
        }


    }



  
        
        // }
  

    // echo json_encode($data);
?>