<?php
session_start();
date_default_timezone_set('Asia/Kolkata');
include "config.php";
include('smtp/PHPMailerAutoload.php');

$message = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST['email'];
    $password = md5($_POST['password']);

    // Check if user exists
    $checkUser = "SELECT * FROM users WHERE email='$email'";
    $result = mysqli_query($con, $checkUser);

    if (mysqli_num_rows($result) > 0) {
        // Check if password matches
        $checkUserquery = "SELECT * FROM users WHERE email='$email' AND password='$password'";
        $resultant = mysqli_query($con, $checkUserquery);

        if (mysqli_num_rows($resultant) > 0) {
            $row = mysqli_fetch_assoc($resultant);
            $_SESSION['user'] = $row;

            // Send login alert email
            $to = $row['email'];
            $subject = "Login Alert";
            $loginTime = date('d F Y h:i:s A');
            $title = "🔐 Unrecognized Login Alert";

            $html_body = "<!DOCTYPE html>
            <html>
            <head>
            <title>'.$title.'</title>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    background-color: #f4f4f4;
                    padding: 20px;
                }
                .container {
                    max-width: 600px;
                    margin: auto;
                    background: #fff;
                    padding: 20px;
                    border-radius: 8px;
                    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                }
                .header {
                    background-color: #0275d8;
                    color: white;
                    text-align: center;
                    padding: 12px;
                    font-size: 22px;
                    border-radius: 8px 8px 0 0;
                }
                .content {
                    padding: 20px;
                    text-align: left;
                    line-height: 1.6;
                }
                .alert-box {
                    background: #fff3cd;
                    padding: 15px;
                    border-radius: 5px;
                    margin: 15px 0;
                    border-left: 5px solid #ff9800;
                    font-weight: bold;
                    color: #856404;
                }
                .important {
                    color: #d9534f;
                    font-weight: bold;
                }
                .footer {
                    font-size: 13px;
                    text-align: center;
                    margin-top: 30px;
                    color: gray;
                }
            </style>
            </head>
            <body>
            <div class='container'>
                <div class='header'>🔐 Unrecognized Login Alert</div>
                <div class='content'>
                    <p>Dear <strong>{$row['name']}</strong>,</p>

                    <p>We noticed a login attempt to your account on <strong>{$loginTime} IST</strong>.</p>

                    <p>If this was <strong>you</strong>, no further action is needed and you can ignore this message.</p>

                    <div class='alert-box'>
                        However, if you <strong>did not</strong> attempt to log in, please contact us immediately:<br>
                        <a href='https://wa.me/917043311587?text=Hello%20Er.%20Krunal%20Gamit%2C%20I%20need%20assistance%20regarding%20a%20login%20alert.' target='_blank'>
                        WhatsApp : <strong>📞Er. Krunal Gamit</strong>
                        </a>

                    </div>

                    <p class='important'>⚠️ Beware of phishing attempts. Cybercriminals may try to steal your login details using fake emails or websites.</p>

                    <p>Never enter your personal details on unknown or unverified links.</p>
                </div>
                <div class='footer'>Design and Developed by <strong>Er. Krunal Gamit</strong></div>
            </div>
            </body>
            </html>";


            // Uncomment below to send the email
            // Redirect based on user type
            $ipAddress = $_SERVER['REMOTE_ADDR'];
            addLogs( $row['id'],$row['pid'],$ipAddress);

            if ($row['au'] == 1) {
            echo '<script>
            window.location.href = "dashboard.php";
            </script>';
            } else {
            smtp_mailer($to, $subject, $html_body);
            echo '<script>window.location.href = "main.php";</script>';
            }
            exit();
            } else {
            echo "<script>
            alert('Wrong password!');
            window.location.href = 'index.php';
            </script>";
            exit();
            }
            } else {
            echo "<script>
            alert('User does not exist!');
            window.location.href = 'index.php';
            </script>";
            exit();
            }
            }

            // Email sending function

            function addLogs($uid, $pid, $ipAddress) {
            global $con;

            $timestamp = date('Y-m-d H:i:s');

            $sql = "INSERT INTO logs (uid, pid, ip_address,in_out, time_stamp)
            VALUES ('$uid', '$pid', '$ipAddress','in', '$timestamp')";

            mysqli_query($con, $sql) or die("Log insert failed: " . mysqli_error($con));
            }
            
            
            function smtp_mailer($to,$subject, $msg){  
    $mail = new PHPMailer();  
    $mail->IsSMTP();  
    $mail->SMTPAuth = true;  
    $mail->SMTPSecure = 'ssl';   // SSL for port 465
    $mail->Host = "mail.satyahakikat.in";  
    $mail->Port = 465;          // Correct SMTP port
    $mail->IsHTML(true); 
    $mail->CharSet = 'UTF-8';
    //$mail->SMTPDebug = 2;  

    // Your email login
    $mail->Username = "khakhi@satyahakikat.in";  
    $mail->Password = "Krunal@7997";  

    // Sender email
    $mail->SetFrom("khakhi@satyahakikat.in", "KHAKHI-CYBER-DATA");  

    $mail->Subject = $subject;  
    $mail->Body = $msg;  
    $mail->AddAddress($to);  

    // SSL options  
    $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );

    if(!$mail->Send()){  
        return $mail->ErrorInfo;  
    }else{  
        return true;  
    }  

// return $mail->Send();
}
?>