<?php
session_start();
include "connection.php";
include "functions.php";

// Check if login request
if(isset($_POST['email'])) {

    $email = $_POST['email'];
    $password = $_POST['password'];

    // Use prepared statement for security
    $stmt = $conn->prepare("SELECT user_name, user_password, status FROM users WHERE user_email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $res = $stmt->get_result();

    if($res->num_rows === 0){
        echo '<div class="alert alert-danger text-center">Incorrect Email or Password!</div>';
        exit;
    }

    $row = $res->fetch_assoc();
    $username = $row['user_name'];
    $status = $row['status'];
    $hashed_password = $row['user_password']; // if using plain text, just compare $password === $hashed_password

    // Password verification (if plain text, just do $password === $hashed_password)
    if($password !== $hashed_password){
        echo '<div class="alert alert-danger text-center">Incorrect Email or Password!</div>';
        exit;
    }

    if($status !== 'active'){
        echo '<div class="alert alert-danger text-center">Account is not active!</div>';
        exit;
    }

    // Success: set session
    $_SESSION['user_name'] = $username;
    $_SESSION['user_email'] = $email;

    // Get client info
    $date = date('Y-m-d');
    $time = date('h:i:s A');
    $longdate = date('M d, Y');
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $ip = !empty($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_CLIENT_IP'] :
          (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']);

    // Log user login (non-blocking)
    $log_query = $conn->prepare("INSERT INTO logs(username, device, location) VALUES (?, ?, ?)");
    $log_query->bind_param("sss", $username, $user_agent, $ip);
    $log_query->execute();

    // Respond immediately to AJAX
    echo '<div class="alert alert-success text-center">Login Successful!</div>';
    echo '<script>window.setTimeout(function(){window.location.href = "dashboard.php";}, 1000);</script>';

    // Finish request so user sees login instantly
    if (function_exists('fastcgi_finish_request')) {
        fastcgi_finish_request(); // PHP sends response and continues processing
    }

    // Send email AFTER response
    $subject = "Login - {$date}";
    $body = "
    <div style='background: #E4E9F0; padding:10px; font-family:sans-serif'>
        <center><img src='$siteurl/logo.png' width='100'></center>
        <p>Hi <b>$username</b>,</p>
        <p>You logged in at $time on $longdate using $user_agent from IP $ip.</p>
        <p>If this wasn't you, contact support: $adminemail</p>
    </div>";
    sendMail($email, $subject, $body);


}
