<?php
namespace App\Controllers;
SESSION_START();
use \Core\View;
use \Core\Inputs;
use \Core\Userlog;
use \Core\Menu;
use \Core\Form;
use App\Models\Homem;
use App\Email\Emails;
class Homes extends \Core\Controller
{
    /** Browser Checking code started */
    private static function checkbrower()
    {
        $mystring = $_SERVER['HTTP_USER_AGENT'];
        $word = 'Chrome';
        if(strpos($mystring, $word) !== false)
        {
            if(strpos($mystring, 'Mozilla') !== false)
            {
                return "1";
            } 
        }
        else if(strpos($mystring, 'Mozilla') !== false)
        {
            return "1";
        } 
        else
        {
            return "0";
        }
    }
    private static function checkiphone()
    {
        $iPod    = stripos($_SERVER['HTTP_USER_AGENT'],"iPod");
        $iPhone  = stripos($_SERVER['HTTP_USER_AGENT'],"iPhone");
        $iPad    = stripos($_SERVER['HTTP_USER_AGENT'],"iPad");
        $Android = stripos($_SERVER['HTTP_USER_AGENT'],"Android");
        $webOS   = stripos($_SERVER['HTTP_USER_AGENT'],"webOS");
        if($iPod || $iPhone || $iPad || $Android || $webOS)
        {
            echo 1;
        }
        else
        {
            echo 0;
        }
    }
    /** Browser Checking code Ended */

    /** CSS, Script started */
    private static function css()
    {
        $css = 
        '<!DOCTYPE html>
        <html lang="en">
        <head>
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
            <title>Hindu College of Engineering & Technology || Guntur</title>
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
            <title>Hindu College of Engineering & Technology || Guntur</title>
            <link rel="stylesheet" href="https://assets.hinduengg.com/hindu/assets/css/bootstrap.min.css">
            <link rel="stylesheet" href="https://assets.hinduengg.com/hindu/assets/css/style.css">
            <link rel="stylesheet" href="https://assets.hinduengg.com/hindu/assets/sweetalert2/dist/sweetalert2.min.css" >
            <style>
                @media print
                {
                    body * {
                        visibility: hidden;
                    }
                    .print-this, .print-this * {
                        visibility: visible;
                    }
                }
            </style>
            <script>
                function exportTableToExcel(tableID, filename = "")
                {
                    var downloadLink;
                    var dataType = "application/vnd.ms-excel";
                    var tableSelect = document.getElementById(tableID);
                    var tableHTML = tableSelect.outerHTML.replace(/ /g, "%20");
                    
                    // Specify file name
                    filename = filename?filename+".xls":"excel_data.xls";
                    
                    // Create download link element
                    downloadLink = document.createElement("a");
                    
                    document.body.appendChild(downloadLink);
                    
                    if(navigator.msSaveOrOpenBlob){
                        var blob = new Blob(["\ufeff", tableHTML], {
                            type: dataType
                        });
                        navigator.msSaveOrOpenBlob( blob, filename);
                    }else{
                        // Create a link to the file
                        downloadLink.href = "data:" + dataType + ", " + tableHTML;
                    
                        // Setting the file name
                        downloadLink.download = filename;
                        
                        //triggering the function
                        downloadLink.click();
                    }
                }
            </script>
        </head>';
        return $css;  
    }
    private static function script()
    {
        $script =
                '
                <div class="footer navbar-fixed-bottom text-center">        
                    <span class="text-muted text-center">Copyright &#169 2020. Hindu College of Engineering & Technology, Guntur</span>
                </div>
                <script src="https://assets.hinduengg.com/hindu/assets/word/jquery.min.js" ></script>
                <script src="https://assets.hinduengg.com/hindu/assets/js/bootstrap.min.js" ></script>
                <script src="https://assets.hinduengg.com/hindu/assets/vendor/sweetalert2/dist/sweetalert2.min.js" ></script>';
        return $script;  
    }
    private static function blockscript()
    {
        $script =
                '
                <div class="footer navbar-fixed-bottom text-center">        
                    <span class="text-muted text-center">Copyright &#169 2020. Hindu College of Engineering & Technology, Guntur</span>
                </div>
                <script src="https://assets.hinduengg.com/hindu/assets/word/jquery.min.js" ></script>
                <script src="https://assets.hinduengg.com/hindu/assets/js/bootstrap.min.js" ></script>
                <script src="https://assets.hinduengg.com/hindu/assets/sweetalert2/dist/sweetalert2.min.js" ></script>
                <!-- Script to stop mouse right click start-->
            <script>
                //Disable right click script
                var message = "";
                ///////////////////////////////////
                function clickIE() {
                    if (document.all) {
                        (message);
                        return false;
                    }
                }

                function clickNS(e) {
                    if (document.layers || (document.getElementById && !document.all)) {
                        if (e.which == 2 || e.which == 3) {
                            (message);
                            return false;
                        }
                    }
                }
                if (document.layers) {
                    document.captureEvents(Event.MOUSEDOWN);
                    document.onmousedown = clickNS;
                } else {
                    document.onmouseup = clickNS;
                    document.oncontextmenu = clickIE;
                }

                document.oncontextmenu = new Function("return false")
            </script>
            <!-- Script to stop mouse right click end-->

            <!-- Script to prevent selection start-->
            <script>
                $(document).ready(function () {
                    $("body").bind("cut copy", function (e) {
                        e.preventDefault();
                    });
                });
            </script>
            <!-- Script to prevent selection end-->
                ';
        return $script;  
    }
    private static function datem($id)
    {
        $data = explode('-', $id);
        $final = $data[2].'-'.$data[1].'-'.$data[0];
        return $final;
    }
    /** CSS, Script Ended */
    
    public static function changepassword()
    {
        if($_SESSION['user_role'] != '')
        {
            echo static::css();
            echo '<body>';
                echo '
                <div class="clearfix"></div>
                <form id="frm_exam" action="/Homes/savechangepassword" method="POST">                
                <div class="container">
                    <div class="container-fluid">
                        <div class="row" style="margin-top:20px;">
                            <div class="col-xl-4"></div>
                            <div class="col-xl-4">
                                <section class="box" style="margin-top: 10px;">
                                    <header class="panel_header">
                                        <h4 class="title pull-left">Change Your Password Here</h4>
                                        <div class="actions panel_actions pull-right">
                                            <a class="fa fa-refresh" onclick="refreshClick()"></a>
                                            <a class="box_toggle fa fa-chevron-down"></a>
                                        </div>
                                    </header>
                                    <div class="content-body">    
                                        <div class="row">
                                            <div class="col-lg-12">
                                                <div class="form-group">                                      
                                                    <input type="text" name="oldpassword" id="oldpassword" class="form-control" placeholder="Old Password" required>
                                                </div>
                                            </div>                              
                                        </div>
                                        <div class="row">
                                            <div class="col-lg-12">
                                                <div class="form-group">                                            
                                                    <input type="text" name="newpassword" id="newpassword" class="form-control" placeholder="New Password" required>
                                                </div>
                                            </div>                              
                                        </div>
                                        <div class="row">
                                            <div class="col-lg-12">
                                                <div class="form-group">                                            
                                                    <input type="text" name="cnfpassword" id="cnfpassword" class="form-control" placeholder="Confirm New Password" onchange="comaprepass()" required>
                                                </div>
                                            </div>                              
                                        </div>
                                        <div class="row submitbutton" >
                                            <div class="col-md-12">  
                                                <div class="form-group">
                                                    <button id="btn_reg" style="display:none;" class="btn btn-primary pull-right" type="submit" style="background-color: #002366 !important;">Submit</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>                        
                                </section>
                            </div>
                            <div class="col-xl-4"></div>
                        </div>
                    </div>
                </div>
                </form>
                ';
            echo '</body>';
            echo static::script();
            echo '<script>
            function comaprepass()
            {
                var pass1 = $("#newpassword").val();
                var pass2 = $("#cnfpassword").val();
                if(pass1 == pass2)
                {
                    $("#btn_reg").show();
                }
                else
                {
                    $("#btn_reg").hide();
                    swal("Password Mismatch", "Please enter same password in the new and confirm password.", "error");
                    setInterval(function () {
                        location.reload();
                    }, 1000);
                }
            }
            </script>';
        }
    }
    public static function savechangepassword()
    {
        if($_SESSION['user_role'] != '')
        {
            if(isset($_POST['oldpassword']))
            {
                if(sizeof(Homem::getdata("SELECT * FROM `user_master` WHERE `id`='$_SESSION[user_id]' AND `password`='$_POST[oldpassword]'")) == 1)
                {
                    Homem::insert("UPDATE `user_master` SET `password`='$_POST[newpassword]' WHERE `id`='$_SESSION[user_id]'");
                    if(sizeof(Homem::getdata("SELECT * FROM `user_master` WHERE `id`='$_SESSION[user_id]' AND `password`='$_POST[newpassword]'")) == 1)
                    {
                        echo '<script>window.location="/Homes/home?status=1";</script>';
                    }
                }
                else
                {
                    echo '<script>window.location="/Homes/home?status=0";</script>';
                }
            }
        }
    }
    public static function changemobile()
    {
        if($_SESSION['user_role'] != '')
        {
            echo static::css();
            echo '<body>';
                echo '
                <div class="clearfix"></div>
                <form id="frm_exam" action="/Homes/savechangemobile" method="POST">                
                <div class="container">
                    <div class="container-fluid">
                        <div class="row" style="margin-top:20px;">
                            <div class="col-xl-4"></div>
                            <div class="col-xl-4">
                                <section class="box" style="margin-top: 10px;">
                                    <header class="panel_header">
                                        <h4 class="title pull-left">Change Your Mobile Number Here</h4>
                                        <div class="actions panel_actions pull-right">
                                            <a class="fa fa-refresh" onclick="refreshClick()"></a>
                                            <a class="box_toggle fa fa-chevron-down"></a>
                                        </div>
                                    </header>
                                    <div class="content-body">    
                                        <div class="row">
                                            <div class="col-lg-12">
                                                <div class="form-group">                                      
                                                    <input type="number" name="mobile" id="mobile" class="form-control" placeholder="Mobile Number" required>
                                                </div>
                                            </div>                              
                                        </div>
                                        <div class="row submitbutton" >
                                            <div class="col-md-12">  
                                                <div class="form-group">
                                                    <button id="btn_reg" style="display:block;" class="btn btn-primary pull-right" type="submit" style="background-color: #002366 !important;">Submit</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>                        
                                </section>
                            </div>
                            <div class="col-xl-4"></div>
                        </div>
                    </div>
                </div>
                </form>
                ';
            echo '</body>';
            echo static::script();
            echo '<script>
            </script>';
        }
    }
    public static function savechangemobile()
    {
        if($_SESSION['user_role'] != '')
        {
            if(isset($_POST['mobile']))
            {
                Homem::insert("UPDATE `user_master` SET `mobile`='', `v_mobile`='' WHERE `id`='$_SESSION[user_id]'");
                if(sizeof(Homem::getdata("SELECT * FROM `user_master` WHERE `id`='$_SESSION[user_id]' AND `mobile`=''")) == 1)
                {
                    if(sizeof(Homem::getdata("SELECT * FROM `user_master` WHERE `mobile`='$_POST[mobile]'")) == 0)
                    {
                        Homem::insert("UPDATE `user_master` SET `mobile`='$_POST[mobile]' WHERE `id`='$_SESSION[user_id]'");
                        if(sizeof(Homem::getdata("SELECT * FROM `user_master` WHERE `id`='$_SESSION[user_id]' AND `mobile`='$_POST[mobile]'")) == 1)
                        {
                            echo '<script>window.location="/Homes/home?status=1";</script>';
                        }
                        else
                        {
                            echo '<script>window.location="/Homes/home?status=0";</script>';
                        }
                    }
                    else
                    {
                        echo '<script>window.location="/Homes/home?status=0";</script>';
                    }
                }
                else
                {
                    echo '<script>window.location="/Homes/home?status=0";</script>';
                }
            }
        }
    }
    public static function home()
    {
        if($_SESSION['user_role'] != '')
        {
            $a = '';
            $pdata = Homem::getdata("SELECT * FROM user_master um JOIN email_token et ON um.id=et.fk_user_id WHERE um.email!='' AND et.status='1' AND (um.v_email='' OR um.v_email='0') AND um.id='$_SESSION[user_id]' ORDER BY et.e_time DESC");
            if(sizeof($pdata) > 0)
            {
                date_default_timezone_set('Asia/Kolkata'); 
                $today_time =  date('Y-m-d H:i:s');
                $date1 = strtotime($pdata[0]["e_time"]); 
                $date2 = strtotime($today_time); 
                $diff = abs($date2 - $date1); 
                $minutes = $diff/(60);
                if($minutes <= 45)
                {
                    $a = '
                    <div class="card">
                            <div class="card-body">
                                <form action="" method="POST" enctype="multipart/form-data">
                                    <div class="form-group">
                                        <div class="float-right">
                                        An email verification link has been sent to your registered email check INBOX/SPAM. Please click on the link to verify you email. The verification link is active for 45 min.
                                        </div> 
                                    </div>
                                </form>
                            </div>
                        </div>';
                }
            }
            echo static::css();
            echo '<body>';
                echo $_SESSION['menu'];
                echo '
                <div class="container">
                    <div class="container-fluid">
                        <div class="row" style="margin-top:20px;">
                        <div class="col-xl-4"></div>
                        <div class="col-xl-4">
                        '.$a.'
                        </div>
                        <div class="col-xl-4"></div>
                        </div>
                    </div>
                </div>
                ';
            echo '</body>';
            echo static::script();
            if($_SESSION['user_role'] != "")
            {
                $data = Homem::getdata("SELECT * FROM `user_master` WHERE ((`no`=`password`) OR (`mobile`=`password`) OR (`email`=`password`)) AND `id`='$_SESSION[user_id]'");
                if(sizeof($data) != 0)
                {
                    echo '<script>window.location="/Homes/changepassword";</script>';
                }
                $data = Homem::getdata("SELECT * FROM `user_master` WHERE `mobile`='' AND `id`='$_SESSION[user_id]'");
                if(sizeof($data) != 0)
                {
                    echo '<script>window.location="/Homes/changemobile";</script>';
                }
                $data = Homem::getdata("SELECT * FROM `user_master` WHERE `email`='' AND `id`='$_SESSION[user_id]'");
                if(sizeof($data) != 0)
                {
                    echo '<script>window.location="/Homes/changeemail";</script>';
                }
            }
            if(isset($_GET['status']))
            {
                if($_GET['status'] == 1)
                {
                    echo '<script>swal("", "Inserted Successfully", "success");</script>';
                }
                else if($_GET['status'] == 2)
                {
                    echo '<script>swal("", "Updated Successfully", "success");</script>';
                }
                else
                {
                    echo '<script>swal("", "Something went Wrong.. Please try again later..", "error");</script>';
                }
            }
        }
    }
    public static function changeemail()
    {
        if($_SESSION['user_role'] != '')
        {
            echo static::css();
            echo '<body>';
                echo '
                <div class="clearfix"></div>
                <form id="frm_exam" action="/Homes/savechangeemail" method="POST">                
                <div class="container">
                    <div class="container-fluid">
                        <div class="row" style="margin-top:20px;">
                            <div class="col-xl-4"></div>
                            <div class="col-xl-4">
                                <section class="box" style="margin-top: 10px;">
                                    <header class="panel_header">
                                        <h4 class="title pull-left">Change Your Email Here</h4>
                                        <div class="actions panel_actions pull-right">
                                            <a class="fa fa-refresh" onclick="refreshClick()"></a>
                                            <a class="box_toggle fa fa-chevron-down"></a>
                                        </div>
                                    </header>
                                    <div class="content-body">    
                                        <div class="row">
                                            <div class="col-lg-12">
                                                <div class="form-group">                                      
                                                    <input type="email" name="email" id="email" class="form-control" placeholder="Email" required>
                                                </div>
                                            </div>                              
                                        </div>
                                        <div class="row submitbutton" >
                                            <div class="col-md-12">  
                                                <div class="form-group">
                                                    <button id="btn_reg" style="display:block;" class="btn btn-primary pull-right" type="submit" style="background-color: #002366 !important;">Submit</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>                        
                                </section>
                            </div>
                            <div class="col-xl-4"></div>
                        </div>
                    </div>
                </div>
                </form>
                ';
            echo '</body>';
            echo static::script();
            echo '<script>
            </script>';
        }
    }
    public static function userchangeemail()
    {
        if($_SESSION['user_role'] != '')
        {
            echo static::css();
            echo '<body>';
            echo $_SESSION['menu'];
                echo '
                <div class="clearfix"></div>
                <form id="frm_exam" action="/Homes/savechangeemail" method="POST">                
                <div class="container">
                    <div class="container-fluid">
                        <div class="row" style="margin-top:20px;">
                            <div class="col-xl-4"></div>
                            <div class="col-xl-4">
                                <section class="box" style="margin-top: 10px;">
                                    <header class="panel_header">
                                        <h4 class="title pull-left">Change Your Email Here</h4>
                                        <div class="actions panel_actions pull-right">
                                            <a class="fa fa-refresh" onclick="refreshClick()"></a>
                                            <a class="box_toggle fa fa-chevron-down"></a>
                                        </div>
                                    </header>
                                    <div class="content-body">    
                                        <div class="row">
                                            <div class="col-lg-12">
                                                <div class="form-group">                                      
                                                    <input type="email" name="email" id="email" class="form-control" placeholder="Email" required>
                                                </div>
                                            </div>                              
                                        </div>
                                        <div class="row submitbutton" >
                                            <div class="col-md-12">  
                                                <div class="form-group">
                                                    <button id="btn_reg" style="display:block;" class="btn btn-primary pull-right" type="submit" style="background-color: #002366 !important;">Submit</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>                        
                                </section>
                            </div>
                            <div class="col-xl-4"></div>
                        </div>
                    </div>
                </div>
                </form>
                ';
            echo '</body>';
            echo static::script();
            echo '<script>
            </script>';
        }
    }
    public static function savechangeemail()
    {
        if($_SESSION['user_role'] != '')
        {
            if(isset($_POST['email']))
            {
                Homem::insert("UPDATE `user_master` SET `email`='', `v_email`='' WHERE `id`='$_SESSION[user_id]'");
                if(sizeof(Homem::getdata("SELECT * FROM `user_master` WHERE `id`='$_SESSION[user_id]' AND `email`=''")) == 1)
                {
                    if(sizeof(Homem::getdata("SELECT * FROM `user_master` WHERE `email`='$_POST[email]'")) == 0)
                    {
                        date_default_timezone_set('Asia/Kolkata'); 
                        $today_time =  date('Y-m-d H:i:s');
                        Homem::insert("UPDATE `user_master` SET `email`='$_POST[email]' WHERE `id`='$_SESSION[user_id]'");
                        $token = substr(str_shuffle('qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM'), 0, 25);
                        Homem::insert("INSERT INTO `email_token`(`fk_user_id`, `token`, `email_type`, `e_time`, `status`) VALUES ('$_SESSION[user_id]','$token','1','$today_time','1')");
                        $url= $_SERVER['HTTP_HOST'];
                        $tokenurl = 'http://'.$url.'/Homes/emailverification?token='.$token;
                        if($url != 'localhost' && $url != '192.168.1.193')
                        {
                            $estatus = Emails::newuseremailverf($_SESSION['name'], $_POST['email'], $tokenurl);
                        }
                        else
                        {
                            $estatus = Emails::emailverificationapi($_SESSION['name'], $_POST['email'], $tokenurl);
                        }
                        if(sizeof(Homem::getdata("SELECT * FROM `user_master` WHERE `id`='$_SESSION[user_id]' AND `email`='$_POST[email]'")) == 1)
                        {
                            echo '<script>window.location="/Homes/home?status=1";</script>';
                        }
                        else
                        {
                            echo '<script>window.location="/Homes/home?status=0";</script>';
                        }
                    }
                    else
                    {
                        echo '<script>window.location="/Homes/home?status=0";</script>';
                    }
                }
                else
                {
                    echo '<script>window.location="/Homes/home?status=0";</script>';
                }
            }
        }
    }
    public static function emailverification()
    {
        if(isset($_GET['token']))
        {
            if(strlen($_GET['token']) == 25)
            {
                $t_data = Homem::getdata("SELECT * FROM `email_token` WHERE `token`='$_GET[token]' AND `status`='1'");
                if(sizeof($t_data) == 1)
                { 
                    date_default_timezone_set('Asia/Kolkata'); 
                    $today_time =  date('Y-m-d H:i:s');
                    $date1 = strtotime($t_data[0]["e_time"]); 
                    $date2 = strtotime($today_time); 
                    $diff = abs($date2 - $date1); 
                    $minutes = $diff/(60);
                        if($minutes <= 45)
                        {
                            if($t_data[0]["email_type"] == 1)
                            {
                                echo $minutes;
                                $fk_user_id = $t_data[0]["fk_user_id"];
                                Homem::insert("UPDATE `user_master` SET `v_email`='1' WHERE `id`='$fk_user_id'");
                                Homem::insert("UPDATE `email_token` SET `status`='0' WHERE `token`='$_GET[token]'");
                                $status = "<script>swal('Verification Success', 'Please Login to Continue..', 'success');</script>";
                                echo '<script>window.location="/Homes/index?status=1";</script>';  
                            }
                        }
                        else
                        {
                            $status = "<script>swal('Verification Failed..', 'The link expaired due to time.', 'error');setTimeout(function(){ location.href='/'; }, 5000);</script>";
                            echo '<script>window.location="/Homes/index?status=0";</script>';
                        }
                }
                else
                {
                    $status = "<script>swal('Verification Failed..', 'Details not found or Expired Details.', 'error');setTimeout(function(){ location.href='/'; }, 5000);</script>";
                    echo '<script>window.location="/Homes/index?status=0";</script>';
                }
            }
            else
            {
                $status = "<script>swal('Verification Failed..', 'Invalid Detils for verification.', 'error');setTimeout(function(){ location.href='/'; }, 5000);</script>";
                echo '<script>window.location="/Homes/index?status=0";</script>'; 
            }
        }
        else
        {
            $status = "<script>swal('Verification Failed..', 'Something wrong.. Please try again.', 'error');setTimeout(function(){ location.href='/'; }, 5000);</script>";
            echo '<script>window.location="/Homes/index?status=0";</script>';
        }
    }
}