<?php
session_start();
require 'db.php';

if (isset($_SESSION['user_id']) && isset($_SESSION['log_id'])) {
    $user_id = $_SESSION['user_id'];
    $log_id = $_SESSION['log_id'];

    // Fetch username for email
    $user_row = $conn->query("SELECT username FROM users WHERE id = $user_id")->fetch_assoc();
    $username = $user_row['username'] ?? 'Unknown';

    // Capture IP, browser, and time
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'Unknown IP';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
    $time = date('Y-m-d H:i:s');

    // Optional: approximate location via IP
    $location = '';
    $ip_info = @file_get_contents("http://ip-api.com/json/{$ip}");
    if ($ip_info) {
        $ip_data = json_decode($ip_info,true);
        if($ip_data['status'] === 'success'){
            $location = "{$ip_data['city']}, {$ip_data['regionName']}, {$ip_data['country']}";
        }
    }

    // ------------------ SEND LOGOUT EMAIL ------------------
    $to = "giantplusmw@gmail.com,rams.investments@gmail.com";
    $subject = "POS Logout Alert - {$username}";
    $message = "
    <h3>User Logout Alert</h3>
    <table border='1' cellpadding='5'>
        <tr><td><b>Username</b></td><td>{$username}</td></tr>
        <tr><td><b>IP Address</b></td><td>{$ip}</td></tr>
        <tr><td><b>Location</b></td><td>{$location}</td></tr>
        <tr><td><b>Browser / Device</b></td><td>{$user_agent}</td></tr>
        <tr><td><b>Logout Time</b></td><td>{$time}</td></tr>
    </table>
    ";
    $headers  = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8\r\n";
    $headers .= "From: cloud@gianterp.space\r\n";

    @mail($to, $subject, $message, $headers);

    // ------------------ UPDATE LOGOUT TIME IN DB ------------------
    $stmt = $conn->prepare("UPDATE user_logs SET logout_time = NOW() WHERE id = ?");
    $stmt->bind_param('i', $log_id);
    $stmt->execute();
}

// Clear session
session_destroy();

// Redirect to login page
header('Location: login.php');
exit;
?>
