<?php
session_start();
require 'includes/config.php'; 

require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

function sendLoginNotification($toEmail, $userName, $subject, $ipAddress, $deviceInfo, $loginTime) {
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host = 'smtp.zoho.com';
        $mail->SMTPAuth = true;
        $mail->Username = '';
        $mail->Password = 'jDtUaFAJ01M4';  // Zoho App Password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = 465;

        $mail->setFrom('', 'Login');
        $mail->addAddress($toEmail, $userName);
        $mail->isHTML(true);
        $mail->Subject = $subject;

        $message = "
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; background-color: #f9f9f9; padding: 20px; }
                .container { background-color: #fff; padding: 20px; border-radius: 8px; }
                h2 { color: #333; }
                p { font-size: 15px; }
                .info { background: #f2f2f2; padding: 10px; margin-top: 10px; border-radius: 5px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <h2>Login Alert</h2>
                <p>User <strong>$userName</strong> just logged in with the following details:</p>
                <div class='info'>
                    <p><strong>IP Address:</strong> $ipAddress</p>
                    <p><strong>Device:</strong> $deviceInfo</p>
                    <p><strong>Time:</strong> $loginTime</p>
                </div>
                <p>If this wasn't you, please take immediate action.</p>
            </div>
        </body>
        </html>";

        $mail->Body = $message;
        $mail->send();
    } catch (Exception $e) {
        // Log to file
        file_put_contents('mail_error.log', date('Y-m-d H:i:s') . ' - Mail Error: ' . $mail->ErrorInfo . PHP_EOL, FILE_APPEND);
        // Optional: also show the error for debugging (disable in production)
        echo '<pre>Mailer Error: ' . $mail->ErrorInfo . '</pre>';
    }
}


// Login Logic
if (isset($_POST['submit'])) {
    if (!empty($_POST['email']) && !empty($_POST['password'])) {
        $email = trim($_POST['email']);
        $password = trim($_POST['password']);

        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $stmt = $conn->prepare("SELECT * FROM users WHERE email = :email");
            $stmt->execute(['email' => $email]);

            if ($stmt->rowCount() > 0) {
                $user = $stmt->fetch(PDO::FETCH_ASSOC);
                if (password_verify($password, $user['password'])) {
                    unset($user['password']);
                    $_SESSION = $user;

                  
                    $ip = $_SERVER['REMOTE_ADDR'];
                    $device = $_SERVER['HTTP_USER_AGENT'];
                    $time = date('Y-m-d H:i:s');

                    
                    sendLoginNotification(
                        '', 
                        $user['name'] ?? 'User',
                        'Login Alert: Sensitive Account Accessed',
                        $ip,
                        $device,
                        $time
                    );

                    header("Location: index.php");
                    exit();
                } else {
                    $errors[] = "Wrong email or password!";
                }
            } else {
                $errors[] = "Wrong email or password!";
            }
        } else {
            $errors[] = "Invalid email format!";
        }
    } else {
        $errors[] = "Email and password are required!";
    }
}
?>
<?php
$stmt = $conn->query("SELECT * FROM companies ORDER BY id DESC LIMIT 1");
$company = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html lang="en">
   
<head>
      <!-- Required meta tags -->
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <title>Login</title>
      <!-- Favicon -->
      <link rel="shortcut icon" href="images/favicon.ico" />
      <!-- Bootstrap CSS -->
      <link rel="stylesheet" href="css/bootstrap.min.css">
      <!-- Typography CSS -->
      <link rel="stylesheet" href="css/typography.css">
      <!-- Style CSS -->
      <link rel="stylesheet" href="css/style.css">
      <!-- Responsive CSS -->
      <link rel="stylesheet" href="css/responsive.css">
   </head>
   <body>
      <!-- loader Start -->
      <div id="loading">
         <div id="loading-center">
         </div>
      </div>
      <!-- loader END -->
        <!-- Sign in Start -->
        <section class="sign-in-page">
            <div class="container bg-white mt-5 p-0">
                <div class="row no-gutters">
                    <div class="col-sm-6 align-self-center">
                        <div class="sign-in-from">
                            <h1 class="mb-0 dark-signin">Sign in</h1>
                            <p>Enter your email address and password to access admin panel.</p>
                            <form method="POST" class="login" action="<?php echo $_SERVER['PHP_SELF']; ?>">
                            <?php
        if (isset($errors) && count($errors) > 0) {
            foreach ($errors as $error_msg) {
                echo '<div class="error" style="color:red; padding-left:2.2em; padding-top:0.5em; font-weight:bold; font-size:16px; letter-spacing:1px; margin-left:-0em;">' . $error_msg . '</div>';
            }
        }
        ?>
                                <div class="form-group">
                                    <label for="exampleInputEmail1">Email address</label>
                                    <input type="email" class="form-control mb-0" name="email" id="exampleInputEmail1" placeholder="Enter email">
                                </div>
                                <div class="form-group">
                                    <label for="exampleInputPassword1">Password</label>
                                    <!-- <a href="#" class="float-right">Forgot password?</a> -->
                                    <input type="password" class="form-control mb-0"  name="password" id="exampleInputPassword1" placeholder="Password">
                                </div>
                                <div class="d-inline-block w-100">
                                    <div class="custom-control custom-checkbox d-inline-block mt-2 pt-1">
                                        <input type="checkbox" class="custom-control-input" id="customCheck1">
                                        <label class="custom-control-label" for="customCheck1">Remember Me</label>
                                    </div>
                                    <button type="submit" name="submit" class="btn btn-primary float-right">Sign in</button>
                                </div>
                                <div class="sign-info">
                                    <!-- <span class="dark-color d-inline-block line-height-2">Don't have an account? <a href="#">Sign up</a></span> -->
                                    <ul class="iq-social-media">
                                        <li><a href="#"><i class="ri-facebook-box-line"></i></a></li>
                                        <li><a href="#"><i class="ri-twitter-line"></i></a></li>
                                        <li><a href="#"><i class="ri-instagram-line"></i></a></li>
                                    </ul>
                                </div>
                            </form>
                        </div>
                    </div>
                    <div class="col-sm-6 text-center">
                        <div class="sign-in-detail text-white">
                            <!-- <a class="sign-in-logo mb-5" href="#"><img src="images/logo-white.png" class="img-fluid" alt="logo"></a> -->
                            <div class="slick-slider11" data-autoplay="true" data-loop="true" data-nav="false" data-dots="true" data-items="1" data-items-laptop="1" data-items-tab="1" data-items-mobile="1" data-items-mobile-sm="1" data-margin="0">
                                <div class="item">
                                    <img src="<?= htmlspecialchars($company['logo']) ?>" class="img-fluid mb-4" alt="logo">
                                    <h4 class="mb-1 text-white">Manage your orders</h4>
                                    <p>It is a long established fact that a reader will be distracted by the readable content.</p>
                                </div>
                                <div class="item">
                                    <img src="<?= htmlspecialchars($company['logo']) ?>" class="img-fluid mb-4" alt="logo">
                                    <h4 class="mb-1 text-white">Manage your orders</h4>
                                    <p>It is a long established fact that a reader will be distracted by the readable content.</p>
                                </div>
                                <div class="item">
                                    <img src="<?= htmlspecialchars($company['logo']) ?>" class="img-fluid mb-4" alt="logo">
                                    <h4 class="mb-1 text-white">Manage your orders</h4>
                                    <p>It is a long established fact that a reader will be distracted by the readable content.</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
        <!-- Sign in END -->
      <!-- Optional JavaScript -->
      <!-- jQuery first, then Popper.js, then Bootstrap JS -->
      <script src="js/jquery.min.js"></script>
      <script src="js/popper.min.js"></script>
      <script src="js/bootstrap.min.js"></script>
      <!-- Appear JavaScript -->
      <script src="js/jquery.appear.js"></script>
      <!-- Countdown JavaScript -->
      <script src="js/countdown.min.js"></script>
      <!-- Counterup JavaScript -->
      <script src="js/waypoints.min.js"></script>
      <script src="js/jquery.counterup.min.js"></script>
      <!-- Wow JavaScript -->
      <script src="js/wow.min.js"></script>
      <!-- Apexcharts JavaScript -->
      <script src="js/apexcharts.js"></script>
      <!-- Slick JavaScript -->
      <script src="js/slick.min.js"></script>
      <!-- Select2 JavaScript -->
      <script src="js/select2.min.js"></script>
      <!-- Owl Carousel JavaScript -->
      <script src="js/owl.carousel.min.js"></script>
      <!-- Magnific Popup JavaScript -->
      <script src="js/jquery.magnific-popup.min.js"></script>
      <!-- Smooth Scrollbar JavaScript -->
      <script src="js/smooth-scrollbar.js"></script>
      <!-- Chart Custom JavaScript -->
      <script src="js/chart-custom.js"></script>
      <!-- Custom JavaScript -->
      <script src="js/custom.js"></script>
   </body>

</html>