<?php

session_start();

ob_start();

include "db.php";



function redirect($url) {

    header("Location: $url");

    exit();

}



// Auto-login if cookies are set

if (isset($_COOKIE['uuu']) && isset($_COOKIE['ppp']) && isset($_COOKIE['eee'])) {

    $ucontact = $_COOKIE['uuu'];

    $uemail = $_COOKIE['eee'];

    $upass = $_COOKIE['ppp'];

    $udisplay = 'disable';



    $stmt = $con->prepare("SELECT * FROM users WHERE ucontact = ? OR uemail = ? AND udisplay != ?");

    $stmt->bind_param("sss", $ucontact, $uemail, $udisplay);

    $stmt->execute();

    $result = $stmt->get_result();

    $l_rows = $result->fetch_assoc();



    if ($l_rows && $upass == $l_rows['upass']) {

        $_SESSION["uid"] = $l_rows['uid'];

        $_SESSION["utype"] = $l_rows['utype'];

        $_SESSION["uname"] = $l_rows['uname'];

        $_SESSION["uemail"] = $l_rows['uemail'];

        $_SESSION["ucontact"] = $l_rows['ucontact'];

        $_SESSION["uref"] = $l_rows['uref'];

        $_SESSION["uref_code"] = $l_rows['uref_code'];

        // redirectUser($l_rows['utype']);

    }

}



if(isset($_GET["otp"]) && !empty($_SESSION["otp"])){

    echo $otp = $_SESSION["otp"];

}

?>

<?php

if (isset($_POST['login_button'])) {

    $otp = $_POST['otp'];



    if ($otp == $_SESSION['otp']) {

        // Set cookies

        setcookie("uuu", $_SESSION["uphone"], time() + (86400 * 7), "/");

        setcookie("eee", $_SESSION["uemail"], time() + (86400 * 7), "/");

        setcookie("ppp", $_SESSION["upass"], time() + (86400 * 7), "/");



        // Redirect or trigger modal based on user type

        if ($_SESSION["utype"] == 'master_admin') {

            header("Location: user1/");

            exit();

        }

        if ($_SESSION["utype"] == 'Employee') {

            header("Location: user2/");

            exit();

        }

        if ($_SESSION["utype"] == 'Associate') {

            header("Location: user3/");

            exit();

        }

        if ($_SESSION["utype"] == 'Sub Associate') {

            header("Location: user4/");

            exit();

        }

        if ($_SESSION["utype"] == 'Student') {

            header("Location: user5/");

            exit();

        }

        

    } else {

        echo '<script>alert("Invalid OTP.");</script>';

    }

}



ob_end_flush();

?>



<!doctype html>

<html lang="en">



<head>

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="./assets/css/bootstrap.css">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" />

    <link rel="stylesheet" href="./assets/css/style.css">

    <link href="./assets/image/favicon.ico" rel="icon">

    <title>Pice Educare</title>

</head>

<style>

.forgot-btn a:hover {

    text-decoration: none !important;

    border-bottom: none !important;

}

</style>



<body>

    <?php if(isset($_GET["forgot_password"])){?>

    <div class="logo-container text-center mt-3">

        <img src="./assets/image/logo.png" alt="" class="img-fluid p-2"

            style="border-radius: 12px; height: 55px;background: #fff;">

    </div>

    <section class="container">

        <div class="login-container">

            <h2>Forgot Password</h2>

            <form action="" method="POST" id="loginForm">

                <div class="input-box" id="phoneInput">

                    <input type="text" id="contactInput" name="contactInput" required="" autofocus=""

                        oninput="validateInput(this)">

                    <label for="contactInput">Enter Registered Number or Email</label>

                    <span id="errorMessage" style="color: red; font-size: 12px;"></span>

                </div>



                <button type="submit" name="forgetPass">Forgot Password</button>

            </form>

        </div>

    </section>

    <?php } elseif(isset($_GET["otp"])){?>

    <!-- Main Content -->

    <div class="logo-container text-center">

        <img src="./assets/image/logo.png" alt="" class="img-fluid p-2" style="border-radius: 12px; height: 55px;">

    </div>

    <section class="container">

        <div class="login-container">

            <form action="" method="POST" id="loginForm" class="text-center">

                <div class="input-box" id="inputBox">

                    <input type="number" name="otp" required="">

                    <label for="otp">Enter OTP</label>

                </div>



                <button type="submit" name="login_button">Login</button>



                <!-- Resend OTP Button -->

                <button type="button" id="resendOtpButton" style="display: none;">Resend OTP</button>

                <p id="countdownTimer"></p>

            </form>

        </div>

    </section>

    <?php } else{?>

    <!-- Preloader -->

    <div id="preloader">

        <div id="ctn-preloader" class="ctn-preloader">

            <div class="animation-preloader">

                <div class="txt-loading">

                    <span data-text-preloader="P" class="letters-loading">P</span>

                    <span data-text-preloader="I" class="letters-loading">I</span>

                    <span data-text-preloader="C" class="letters-loading">C</span>

                    <span data-text-preloader="E" class="letters-loading">E</span>

                </div>

            </div>

            <div class="loader-section section-left"></div>

            <div class="loader-section section-right"></div>

        </div>

    </div>



    <!-- Main Content -->

    <div class="logo-container text-center">

        <img src="./assets/image/logo.png" alt="" class="img-fluid p-2" style="border-radius: 12px; height: 55px;">

    </div>

    <section class="container">

        <div class="login-container">

            <h2>Login</h2>

            <form action="" method="POST" id="loginForm">

                <!-- Phone input -->

                <div class="input-box" id="phoneInput">

                    <input type="text" id="contactInput" name="contactInput" required="" autofocus=""

                        oninput="validateInput(this)">

                    <label for="contactInput">Enter Registered Number or Email</label>

                    <span id="errorMessage" style="color: red; font-size: 12px;"></span>

                </div>

                <button id="nextBtn" type="button" onclick="showPasswordInput()">Next</button>

                <!-- Password Section -->

                <div id="passwordSection" style="display: none;text-align: center;">

                    <div class="input-box" id="inputBox">

                        <input type="password" name="upass" id="password" required="" style="text-align:center;">

                        <label for="password">Enter Password</label>

                    </div>

                    <div class="forgot-btn">

                        <a href="index.php?forgot_password" class=""> Forgot Password?</a>

                    </div>

                    <button type="submit" name="verify" class="mt-2">Send OTP</button>

                </div>

            </form>

        </div>

    </section>

    <?php }?>



    <!-- Scripts -->

    <script src="./assets/js/bootstrap.js"></script>





    <script>

    function validateInput(input) {

        const value = input.value;

        const errorMessage = document.getElementById('errorMessage');



        // Regular expressions for validation

        const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

        const mobilePattern = /^[0-9]{1,10}$/;



        if (value === "") {

            errorMessage.textContent = "This field is required.";

            return;

        }



        if (emailPattern.test(value) || mobilePattern.test(value)) {

            errorMessage.textContent = ""; // Clear the error message if valid

        } else {

            errorMessage.textContent = "Enter a valid 10-digit number or email.";

        }

    }

    </script>



    <script>

    // Show Password Input Section

    function showPasswordInput() {

        const phoneInput = document.getElementById('contactInput');

        const passwordSection = document.getElementById('passwordSection');



        if (phoneInput.value.trim() !== '') {

            // Hide phone input section and next button

            document.getElementById('phoneInput').style.display = 'none';

            document.getElementById('nextBtn').style.display = 'none';

            // Show password section

            passwordSection.style.display = 'block';

        } else {

            alert('Please enter your registered number.');

        }

    }



    // Preloader Script

    document.addEventListener('DOMContentLoaded', () => {

        setTimeout(() => {

            document.getElementById('preloader').classList.add('loaded');

            setTimeout(() => {

                document.getElementById('preloader').style.display = 'none';

            }, 1000); // Wait for the animation to complete

        }, 3000); // Preloader visible for 3 seconds

    });

    </script>



    <script>

    let countdownTime = 5; // 2 minutes in seconds

    const countdownTimerElement = document.getElementById("countdownTimer");

    const resendOtpButton = document.getElementById("resendOtpButton");



    // Function to start the countdown

    function startCountdown() {

        countdownTimerElement.style.display = "block";

        resendOtpButton.style.display = "none";



        const interval = setInterval(() => {

            if (countdownTime > 0) {

                countdownTime--;

                const minutes = Math.floor(countdownTime / 60);

                const seconds = countdownTime % 60;

                countdownTimerElement.textContent =

                    `You can resend OTP in ${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;

            } else {

                clearInterval(interval);

                countdownTimerElement.style.display = "none";

                resendOtpButton.style.display = "inline-block";



                // Add left: 45px to the element with id="inputBox"

                const inputBoxElement = document.getElementById("inputBox");

                if (inputBoxElement) {

                    inputBoxElement.style.left = "28px";

                }

            }

        }, 1000);

    }



    // Trigger countdown on page load

    window.onload = startCountdown;



    // Handle Resend OTP button click

    resendOtpButton.addEventListener("click", () => {

        countdownTime = 120; // Reset countdown time

        startCountdown(); // Restart countdown



        // Send an AJAX request to resend the OTP

        fetch("resend_otp.php", {

                method: "POST",

                body: JSON.stringify({

                    ucontact: "<?php echo $_SESSION['ucontact']; ?>",

                    upass: "<?php echo $_SESSION['upass']; ?>"

                }),

                headers: {

                    "Content-Type": "application/json"

                }

            })

            .then(response => response.json())

            .then(data => {

                alert(data.message);

            })

            .catch(error => {

                alert("Failed to resend OTP. Please try again.");

                console.error(error);

            });

    });

    </script>



</body>





</html>



<?php

use PHPMailer\PHPMailer\PHPMailer;

use PHPMailer\PHPMailer\Exception;



// Include PHPMailer files

require 'PHPMailer/src/Exception.php';

require 'PHPMailer/src/PHPMailer.php';

require 'PHPMailer/src/SMTP.php';



// Enable error reporting for debugging

ini_set('display_errors', 1);

ini_set('display_startup_errors', 1);

error_reporting(E_ALL);



if (isset($_POST['verify'])) {

    $contactInput = mysqli_real_escape_string($con, strip_tags($_POST['contactInput']));

    $upass = mysqli_real_escape_string($con, strip_tags($_POST['upass']));

    $disable = 'disable';



    // Determine whether the input is a mobile number or email

    if (preg_match('/^[0-9]{1,10}$/', $contactInput)) {

        // Input is a 10-digit mobile number

        $query = "SELECT * FROM users WHERE ucontact = ? AND udisplay != ? AND upass = ?";

    } elseif (filter_var($contactInput, FILTER_VALIDATE_EMAIL)) {

        // Input is a valid email address

        $query = "SELECT * FROM users WHERE uemail = ? AND udisplay != ? AND upass = ?";

    } else {

        // Invalid input

        echo '<script>alert("Enter a valid 10-digit number or email address.");</script>';

        exit;

    }



    // Prepare the SQL query

    $stmt = $con->prepare($query);

    if ($stmt) {

        $stmt->bind_param("sss", $contactInput, $disable, $upass);

        $stmt->execute();

        $result = $stmt->get_result();

        $l_rows = $result->fetch_assoc();

        $stmt->close();



        if ($l_rows) {

            // Verify the password

            if ($upass == $l_rows['upass']) {

                $email = $l_rows['uemail'];

                $uname = $l_rows['uname'];

                $_SESSION["uphone"] = $l_rows['uphone'];

                $_SESSION["ucontact"] = $l_rows['ucontact'];

                $_SESSION["uemail"] = $l_rows['uemail'];

                $_SESSION["upass"] = $l_rows['upass'];

                $_SESSION["utype"] = $l_rows['utype'];

                $_SESSION["uref"] = $l_rows['uref'];

                $_SESSION["uref_code"] = $l_rows['uref_code'];

                $_SESSION["uid"] = $l_rows['uid'];

                $_SESSION["admin_ref"] = $l_rows['admin_ref'];



                // Generate OTP

                $_SESSION["otp"] = $otp = rand(1000, 9999);



                // Initialize PHPMailer

                $mail = new PHPMailer(true);



                try {

                    // SMTP Configuration

                    $mail->isSMTP();

                    $mail->SMTPDebug = 2; // Set 2 for debugging

                    $mail->Host = 'ayushlpo.com';

                    $mail->SMTPAuth = true;

                    $mail->Username = 'contact@ayushlpo.com';

                    $mail->Password = 'cKIcxib89a0R';

                    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

                    $mail->Port = 587; // Common SMTP port for STARTTLS



                    // Email Settings

                    $mail->setFrom('contact@ayushlpo.com', 'Ayush Lpo Application');

                    $mail->addAddress($email, $uname);



                    // Email Content

                    $mail->isHTML(true);

                    $mail->Subject = 'Welcome to Ayush LPO App - Your OTP Inside!';

                    $mail->Body = "

                        <div style='font-family: Arial, sans-serif; line-height: 1.6; color: #333;'>

                            <h3>Hi $uname,</h3>

                            <p>Your login OTP is below. Use this code to securely access your account:</p>

                            <h2 style='color: #007bff;'>$otp</h2>

                            <p>Need help? <a href='https://ayushlpo.com/app' style='color: #007bff;'>Contact us</a>.</p>

                            <hr>

                            <p style='font-size: 12px; color: #666;'>This email was sent to you as part of your Ayush LPO Application login. 

                            If you didn't request this, please ignore it.</p>

                        </div>

                    ";



                    // Send Email

                    $mail->send();



                    // Redirect with success message

                    echo "<script>

                        alert('Login OTP is forwarded to your registered email ID.');

                        window.location = 'index.php?otp';

                    </script>";

                } catch (Exception $e) {

                    error_log("Mailer Error: " . $mail->ErrorInfo);

                    echo "<script>

                        alert('Email could not be sent. Mailer Error: " . addslashes($mail->ErrorInfo) . "');

                        window.location = 'index.php';

                    </script>";

                }

            } else {

                echo "<script>alert('Wrong Password or No account Found');</script>";

            }

        } else {

            echo "<script>alert('No account found with this number or email');</script>";

        }

    } else {

        echo "<script>alert('Database query error');</script>";

    }

}

?>







<?php

// Enable error reporting for debugging

ini_set('display_errors', 1);

ini_set('display_startup_errors', 1);

error_reporting(E_ALL);



if (isset($_POST['forgetPass'])) {

    $contactInput = mysqli_real_escape_string($con, strip_tags($_POST['contactInput']));

    $disable = 'disable';



    // Determine whether the input is a mobile number or email

    if (preg_match('/^[0-9]{1,10}$/', $contactInput)) {

        // Input is a 10-digit mobile number

        $query = "SELECT * FROM users WHERE ucontact = ? AND udisplay != ?";

    } elseif (filter_var($contactInput, FILTER_VALIDATE_EMAIL)) {

        // Input is a valid email address

        $query = "SELECT * FROM users WHERE uemail = ? AND udisplay != ?";

    } else {

        // Invalid input

        echo '<script>alert("Enter a valid 10-digit number or email address.");</script>';

        exit;

    }



    // Prepare the SQL query

    $stmt = $con->prepare($query);

    if ($stmt) {

        $stmt->bind_param("ss", $contactInput, $disable);

        $stmt->execute();

        $result = $stmt->get_result();

        $l_rows = $result->fetch_assoc();

        $stmt->close();



        if ($l_rows) {

            // Verify the password

            if ($l_rows) {

                $email = $l_rows['uemail'];

                $uname = $l_rows['uname'];

                $upass = $l_rows['upass'];



                // Initialize PHPMailer

                $mail = new PHPMailer(true);



                try {

                    // SMTP Configuration

                    $mail->isSMTP();

                    $mail->SMTPDebug = 2; // Set 2 for debugging

                    $mail->Host = 'ayushlpo.com';

                    $mail->SMTPAuth = true;

                    $mail->Username = 'contact@ayushlpo.com';

                    $mail->Password = 'cKIcxib89a0R';

                    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

                    $mail->Port = 587; // Common SMTP port for STARTTLS



                    // Email Settings

                    $mail->setFrom('contact@ayushlpo.com', 'Ayush Lpo Application');

                    $mail->addAddress($email, $uname);



                    // Email Content

                    $mail->isHTML(true);

                    $mail->Subject = 'Welcome to Ayush LPO App - Your Passwprd Inside!';

                    $mail->Body = "

                        <div style='font-family: Arial, sans-serif; line-height: 1.6; color: #333;'>

                            <h3>Hi $uname,</h3>

                            <p>Your login password is below. Use this code to securely access your account:</p>

                            <h2 style='color: #007bff;'>$upass</h2>

                            <p>Need help? <a href='https://ayushlpo.com/app' style='color: #007bff;'>Contact us</a>.</p>

                            <hr>

                            <p style='font-size: 12px; color: #666;'>This email was sent to you as part of your Ayush LPO Application login. 

                            If you didn't request this, please ignore it.</p>

                        </div>

                    ";



                    // Send Email

                    $mail->send();



                    // Redirect with success message

                    echo "<script>

                        alert('Password is forwarded to your registered email ID.');

                        window.location = 'index.php';

                    </script>";

                } catch (Exception $e) {

                    error_log("Mailer Error: " . $mail->ErrorInfo);

                    echo "<script>

                        alert('Email could not be sent. Mailer Error: " . addslashes($mail->ErrorInfo) . "');

                        window.location = 'index.php';

                    </script>";

                }

            } else {

                echo "<script>alert('Wrong Password or No account Found');</script>";

            }

        } else {

            echo "<script>alert('No account found with this number or email');</script>";

        }

    } else {

        echo "<script>alert('Database query error');</script>";

    }

}

?>