<?php session_start();
include("../dashboard/includes/config.php");



if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get and sanitize form data
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $password = $_POST['password'];
    $hashed_password = md5($password); 

    

    $check_sql = "SELECT * FROM users WHERE email = '$email' AND password = '$hashed_password'";
    $query = mysqli_query($conn, $check_sql) or die(mysqli_error($conn));
    

    $result = mysqli_fetch_array($query);
    $_SESSION['user_id'] = $result['id'];
    $_SESSION['email_verified'] = $result['email_verified'];
    $_SESSION['registration_complete'] = $result['registration_complete'];
    $first_name = $result['first_name'];
    $login_time = date('Y-m-d H:i:s');
    $mail_subject = "Login Notification";

    if (mysqli_num_rows($query) != 0) {
        //echo mysqli_num_rows($result);
        //$error_messages[] = "User already exists with this email, ID number, or username";

        

        $mail_message = "<!-- Content Section -->
                            <div class='email-content'>
                                <h2 class='greeting'>Hello <span class='user-name'>".$first_name."</span>,</h2>
                                
                                <p class='message'>
                                    We noticed a recent login to your <strong>".$sitename."</strong> account.
                                </p>

                                <!-- Login Details -->
                                <div class='login-details'>
                                    <div class='detail-box' style='background: #e2e3e5; padding: 15px; border-radius: 8px;'>
                                        <strong>Login Time:</strong> ".$login_time."<br>
                                        <strong>Device:</strong> ".$device_type."<br>
                                        <strong>Location:</strong> ".$location."<br>
                                        <strong>IP Address:</strong> ".$ip_address."
                                    </div>
                                </div>

                                <!-- Security Check -->
                                <div class='security-check'>
                                    <h3 style='color: #2c3e50;'>Was This You?</h3>
                                    <p style='color: #6c757d;'>
                                        If this was you, no action is required. If you don't recognize this activity, 
                                        please secure your account immediately.
                                    </p>
                                </div>

                                <!-- Security Actions -->
                                <div class='security-actions'>
                                    <div style='text-align: center;'>
                                        <a href='".$myUrl."/security.php' class='verification-button' style='background: #dc3545;'>
                                            Secure My Account
                                        </a>
                                    </div>
                                </div>

                                <!-- Security Notice -->
                                <div class='security-notice'>
                                    <div class='security-title'>🔒 Security Notice</div>
                                    <div class='security-text'>
                                        Never share your password with anyone. We will never ask for your password via email.
                                    </div>
                                </div>
                            </div>";


        include("../../proccess/mail_sender.php");


        

        if($result['email_verified'] == 0) {

             echo '<script>
                showToast("Please Verify Your Email", "", "Warning");
                window.location.href = "resend-verification.php";
            </script>'; 

        }elseif($result['email_verified'] == 1 && $result['registration_complete'] == 0) {
            echo '<script>
                showToast("Login Successfull!", "Complete Your Registration", "success");
                window.location.href = "complete_profile.php";
            </script>';

        }elseif($result['email_verified'] == 1 && $result['registration_complete'] == 1) {
        

        echo '<script>
                showToast("Login Successfull!", "Redirecting You To Dashboard", "success");
                window.location.href = "dashboard.php";
            </script>';

        }
    }else {

        echo '<script>
                showToast("Error!", "Invalid Username and Passowrd.", "danger");
                $("#pageloader").hide();
                
            </script>';

            // Initialize login attempt counter if not set
            if (!isset($_SESSION['LOGINATT'])) {
                $_SESSION['LOGINATT'] = 0;
            }

            // Increment login attempt
            $_SESSION['LOGINATT'] = $_SESSION['LOGINATT'] + 1;

            $attempt_time = $_SESSION['LOGINATT'];

            if ($_SESSION['LOGINATT'] > 2) {

                $first_name ='User';
                $mail_message = "<!-- Content Section -->
                                    <div class='email-content'>
                                        <h2 class='greeting'>Security Alert <span class='user-name'>Your Account</span>! ⚠️</h2>
                                        
                                        <p class='message'>
                                            We detected a suspicious login attempt on your <strong>".$sitename."</strong> account.
                                        </p>

                                        <!-- Alert Details -->
                                        <div class='alert-section'>
                                            <div class='alert-box' style='background: #f8d7da; padding: 20px; border-radius: 10px; text-align: center;'>
                                                <h3 style='color: #721c24; margin: 0;'>Suspicious Activity Detected</h3>
                                                <p style='color: #721c24; margin: 10px 0;'>
                                                    Login attempt was blocked for your security
                                                </p>
                                            </div>
                                        </div>

                                        <!-- Attempt Details -->
                                        <div class='attempt-details'>
                                            <div class='detail-box' style='background: #e2e3e5; padding: 15px; border-radius: 8px;'>
                                                <strong>Attempt Time:</strong> ".$attempt_time."<br>
                                                <strong>Location:</strong> ".$location."<br>
                                                <strong>IP Address:</strong> ".$ip_address."<br>
                                                <strong>Status:</strong> <span style='color: #dc3545;'>Blocked</span>
                                            </div>
                                        </div>

                                        <!-- Immediate Actions -->
                                        <div class='actions-section'>
                                            <h3 style='color: #2c3e50;'>Immediate Actions Recommended</h3>
                                            <ul style='color: #6c757d;'>
                                                <li>Change your password immediately</li>
                                                <li>Enable two-factor authentication</li>
                                                <li>Review recent account activity</li>
                                            </ul>
                                        </div>

                                        <!-- Security Actions -->
                                        <div class='security-actions'>
                                            <div style='text-align: center;'>
                                                <a href='".$myUrl."/dashboard/change-password.php' class='verification-button' style='background: #dc3545;'>
                                                    Change Password Now
                                                </a>
                                            </div>
                                        </div>

                                        <!-- Support Section -->
                                        <div class='support-section'>
                                            <p class='support-text'>If this wasn't you, contact support immediately</p>
                                            <a href='".$myUrl."/contact.php' class='support-link'>Contact Security Team</a>
                                        </div>
                                    </div>";

                 include("../../proccess/mail_sender.php");
            }

    }

} else {
    echo '<script>
                showToast("Error!", "Invalid request method.", "danger");

            </script>';
    
} 