<?php
session_start();
ob_start();
include "db.php";

function redirect($url) {
    header("Location: $url");
    exit();
}

if (isset($_COOKIE['uuu']) && isset($_COOKIE['ppp'])) {
    $uphone = $_COOKIE['uuu'];
    $upass = $_COOKIE['ppp'];

    $stmt = $con->prepare("SELECT * FROM users WHERE uphone = ?");
    $stmt->bind_param("s", $uphone);
    $stmt->execute();
    $result = $stmt->get_result();
    $l_rows = $result->fetch_assoc();

    if ($l_rows) {
        if ($upass == $l_rows['upass']) {
            $_SESSION["uid"] = $l_rows['uid'];
            $_SESSION["utype"] = $l_rows['utype'];
            $_SESSION["uname"] = $l_rows['uname'];
            $_SESSION["uref"] = $l_rows['uref'];
            $_SESSION["class"] = $l_rows['sclass'];
            $_SESSION["uref_code"] = $l_rows['uref_code'];

            switch ($l_rows['utype']) {
                case 'master_admin':
                    redirect('user1/');
                    break;
                case 'Admin':
                    redirect('user2/');
                    break;
                case 'Teacher':
                    redirect('user3/');
                    break;
                case 'Student':
                    redirect('user4/');
                    break;
                case 'Member':
                    redirect('user_member/');
                    break;
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css">
    <link rel="stylesheet" href="/style.css">
    <title>Login</title>
    <style>
    /* sign in FORM */
    #logreg-forms {
        width: 412px;
        margin: 10vh auto;
        background-color: #f3f3f3;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
        transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
    }

    #logreg-forms form {
        width: 100%;
        max-width: 410px;
        padding: 15px;
        margin: auto;
    }

    #logreg-forms .form-control {
        position: relative;
        box-sizing: border-box;
        height: auto;
        padding: 10px;
        font-size: 16px;
    }

    #logreg-forms .form-control:focus {
        z-index: 2;
    }

    #logreg-forms .form-signin input[type="email"] {
        margin-bottom: -1px;
        border-bottom-right-radius: 0;
        border-bottom-left-radius: 0;
    }

    #logreg-forms .form-signin input[type="password"] {
        border-top-left-radius: 0;
        border-top-right-radius: 0;
    }

    #logreg-forms .social-login {
        width: 390px;
        margin: 0 auto;
        margin-bottom: 14px;
    }

    #logreg-forms .social-btn {
        font-weight: 100;
        color: white;
        width: 190px;
        font-size: 0.9rem;
    }

    #logreg-forms a {
        display: block;
        padding-top: 10px;
        color: lightseagreen;
    }

    #logreg-form .lines {
        width: 200px;
        border: 1px solid red;
    }

    #logreg-forms button[type="submit"] {
        margin-top: 10px;
    }

    #logreg-forms .facebook-btn {
        background-color: #3C589C;
    }

    #logreg-forms .google-btn {
        background-color: #DF4B3B;
    }

    #logreg-forms .form-reset,
    #logreg-forms .form-signup {
        display: none;
    }

    #logreg-forms .form-signup .social-btn {
        width: 210px;
    }

    #logreg-forms .form-signup input {
        margin-bottom: 2px;
    }

    .form-signup .social-login {
        width: 210px !important;
        margin: 0 auto;
    }

    /* Mobile */
    @media screen and (max-width:500px) {
        #logreg-forms {
            width: 300px;
        }

        #logreg-forms .social-login {
            width: 200px;
            margin: 0 auto;
            margin-bottom: 10px;
        }

        #logreg-forms .social-btn {
            font-size: 1.3rem;
            font-weight: 100;
            color: white;
            width: 200px;
            height: 56px;
        }

        #logreg-forms .social-btn:nth-child(1) {
            margin-bottom: 5px;
        }

        #logreg-forms .social-btn span {
            display: none;
        }

        #logreg-forms .facebook-btn:after {
            content: 'Facebook';
        }

        #logreg-forms .google-btn:after {
            content: 'Google+';
        }
    }
    </style>
</head>

<body>
    <?php
    if (isset($_GET["pass"]) && $_GET["pass"] == "recovered") {
        echo '
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
                <span class="sr-only">Close</span>
            </button>
            <strong>Great!</strong> Account recovery password has been sent to your mobile number
        </div>
        ';
    }
    ?>

    <div id="logreg-forms">
        <form class="form-signin btn btn-dark" method="post">
            <h1 class="h3 mb-3 font-weight-normal" style="text-align: center"> Sign in</h1>
            <input type="text" maxlength="10" name="uphone" id="inputEmail" class="form-control mb-2"
                placeholder="Mobile Number" required="" autofocus="" onkeypress='validate(event)'>

            <input type="password" name="upass" id="inputPassword" class="form-control" placeholder="Password"
                required="">

            <button class="btn btn-success btn-block" type="submit" name="login_button"><i
                    class="fas fa-sign-in-alt"></i> Sign in</button>

            <a href="#" id="forgot_pswd">Forgot password?</a>
            <hr>
        </form>

        <form method="post" class="form-reset">
            <input type="text" id="resetEmail" class="form-control" placeholder="Mobile Number" name="uphone"
                required="" autofocus="">

            <button class="btn btn-primary btn-block" type="submit" name="reset_pass">Reset Password</button>

            <a href="#" id="cancel_reset"><i class="fas fa-angle-left"></i> Back</a>
        </form>
        <br>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    <script src="/script.js"></script>
    <script>
    function toggleResetPswd(e) {
        e.preventDefault();
        $('#logreg-forms .form-signin').toggle()
        $('#logreg-forms .form-reset').toggle()
    }

    function validate(evt) {
        var theEvent = evt || window.event;
        var key = theEvent.type === 'paste' ? event.clipboardData.getData('text/plain') : String.fromCharCode(theEvent
            .keyCode || theEvent.which);
        if (!/^[0-9]+$/.test(key)) {
            theEvent.returnValue = false;
            if (theEvent.preventDefault) theEvent.preventDefault();
        }
    }

    $(function() {
        $('#logreg-forms #forgot_pswd').click(toggleResetPswd);
        $('#logreg-forms #cancel_reset').click(toggleResetPswd);
    });
    </script>

</body>

</html>

<?php
if (isset($_POST['login_button'])) {
    $uphone = mysqli_real_escape_string($con, strip_tags($_POST['uphone']));
    $upass = mysqli_real_escape_string($con, strip_tags($_POST['upass']));

    $stmt = $con->prepare("SELECT uid, uname, uphone, upass, utype, sclass, uref, uref_code FROM users WHERE uphone = ?");
    $stmt->bind_param("s", $uphone);
    $stmt->execute();
    $result = $stmt->get_result();
    $l_rows = $result->fetch_assoc();

    if ($l_rows && $upass == $l_rows['upass']) {
        setcookie("uuu", $uphone, time() + (86400 * 7), "/");
        setcookie("ppp", $upass, time() + (86400 * 7), "/");

        $_SESSION["uid"] = $l_rows['uid'];
        $_SESSION["utype"] = $l_rows['utype'];
        $_SESSION["uname"] = $l_rows['uname'];
        $_SESSION["uref"] = $l_rows['uref'];
        $_SESSION["class"] = $l_rows['sclass'];
        $_SESSION["uref_code"] = $l_rows['uref_code'];

        switch ($l_rows['utype']) {
            case 'master_admin':
                redirect('user1/');
                break;
            case 'Admin':
                redirect('user2/');
                break;
            case 'Teacher':
                redirect('user3/');
                break;
            case 'Student':
                redirect('user4/');
                break;
            case 'Member':
                redirect('user_member/');
                break;
        }
    } else {
        echo '<script>alert("Wrong Password or No account Found");</script>';
    }
}

if (isset($_POST['reset_pass'])) {
    $uphone = mysqli_real_escape_string($con, strip_tags($_POST['uphone']));

    $stmt = $con->prepare("SELECT uphone, upass FROM users WHERE uphone = ?");
    $stmt->bind_param("s", $uphone);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $sms_msg = "Your Userid & Password: ";
        while ($l_rows = $result->fetch_assoc()) {
            $sms_msg .= $l_rows['uphone'] . " => " . $l_rows['upass'] . " // ";
        }

        // Sending SMS through API
        $api_key = '45899D6EF8D236';
        $from = 'DIGIXT';
        $contacts = $uphone;
        $message = urlencode($sms_msg);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "http://manage.sambsms.com/app/smsapi/index.php");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "key=$api_key&campaign=0&routeid=7&type=text&contacts=$contacts&senderid=$from&msg=$message");
        curl_exec($ch);
        curl_close($ch);

        redirect("index.php?pass=recovered");
    } else {
        echo '<script>alert("Your account Not Found");</script>';
    }
}

ob_end_flush();
?>