<?php
session_start();
include('../../includes/config.php');
include __DIR__ . '/../../includes/header.php';
include __DIR__ . '/../../includes/sidebar.php';
include __DIR__ . '/../../includes/footer.php';

if (!isset($_SESSION['role_id'])) {
    header("Location: ../../index.php");
    exit();
}

$user_id = $_SESSION['user_id'];

function e($str) {
    return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}

function formatTimeAgo($timestamp) {
    if (!$timestamp) return 'N/A';
    $time = strtotime($timestamp);
    $diff = time() - $time;

    if ($diff < 60) return "Just now";
    elseif ($diff < 3600) return floor($diff / 60) . " min ago";
    elseif ($diff < 86400) return floor($diff / 3600) . " hrs ago";
    elseif ($diff < 604800) return floor($diff / 86400) . " days ago";
    else return date("M d, Y H:i", $time);
}

// Fetch all users excluding current user
$query = "
    SELECT u.id, u.first_name, u.last_name, u.username, u.email, u.phone_number, u.role_id, u.store_id, u.profile_picture,
           u.last_activity, u.last_seen,
           u.last_logged_in, u.last_logged_out,
           r.role_name, s.store_name
    FROM users u
    LEFT JOIN roles r ON u.role_id = r.id
    LEFT JOIN stores s ON u.store_id = s.id
    WHERE u.id != ?
    ORDER BY u.first_name, u.last_name
";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$users = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Users List - Digital POS</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
        body, html {
            margin: 0; padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: url('../../images/profile.jpg') no-repeat center center fixed;
            background-size: cover;
            color: white;
            min-height: 100vh;
            overflow-x: hidden;
        }
        .overlay {
            position: fixed;
            top: 0; left: 0;
            width: 100%; height: 100%;
            background: rgba(0,0,0,0.6);
            z-index: -1;
        }
        main.content {
            margin-left: 200px;
            margin-top: 70px;
            padding: 30px 40px;
            backdrop-filter: blur(15px);
            background: rgba(255,255,255,0.05);
            min-height: calc(100vh - 70px);
            border-radius: 20px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.5);
        }
        .container {
            max-width: 1100px;
            margin: auto;
            background: rgba(255,255,255,0.12);
            border-radius: 20px;
            padding: 30px 40px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.4);
        }
        h2 {
            text-align: center;
            margin-bottom: 25px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            background: rgba(0,0,0,0.4);
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 0 12px rgba(0,0,0,0.7);
            color: white;
            font-size: 0.9rem;
        }
        thead {
            background: rgba(255,111,0,0.85);
        }
        thead th {
            padding: 12px 15px;
            text-align: left;
            font-weight: 700;
        }
        tbody tr:hover {
            background: rgba(255,111,0,0.15);
        }
        tbody td {
            padding: 12px 15px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        .btn-message {
            background: #ff6f00;
            color: white;
            padding: 7px 14px;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            font-size: 0.9rem;
        }
        .btn-message:hover {
            background: #e65c00;
        }
        .status-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 6px;
        }
        .online-dot { background-color: #28a745; }
        .offline-dot { background-color: #bbb; }

        @media (max-width: 768px) {
            main.content {
                margin-left: 0;
                margin-top: 120px;
                padding: 20px;
            }
            .container {
                padding: 20px;
            }
        }
    </style>
</head>
<body>

<div class="overlay"></div>

<main class="content">
    <div class="container">
        <h2>Users List</h2>

        <?php if (empty($users)): ?>
            <p>No other users found.</p>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th>Profile</th>
                        <th>Full Name</th>
                        <th>Username</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Role</th>
                        <th>Store</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $u):
                        $logged_in_ts = strtotime($u['last_logged_in']);
                        $logged_out_ts = $u['last_logged_out'] ? strtotime($u['last_logged_out']) : null;

                        // User is online if no logout time or logout is earlier than last login
                        $isOnline = !$logged_out_ts || $logged_out_ts < $logged_in_ts;
                    ?>
                    <tr>
                        <td>
                            <img src="../../uploads/<?= e($u['profile_picture'] ?: 'default.png') ?>"
                                 alt="Profile"
                                 style="width: 38px; height: 38px; border-radius: 50%; object-fit: cover; border: 2px solid #ff6f00;">
                        </td>
                        <td><?= e($u['first_name'] . ' ' . $u['last_name']) ?></td>
                        <td>
                            <a href="profile.php?id=<?= $u['id'] ?>" style="color:#ff6f00; font-weight: 600;">
                                <?= e($u['username']) ?>
                            </a>
                        </td>
                        <td><?= e($u['email']) ?></td>
                        <td><?= e($u['phone_number'] ?? '-') ?></td>
                        <td><?= e($u['role_name'] ?? '-') ?></td>
                        <td><?= e($u['store_name'] ?? '-') ?></td>
                        <td>
                            <span class="status-dot <?= $isOnline ? 'online-dot' : 'offline-dot' ?>"></span>
                            <?= $isOnline ? 'Online' : 'Last logged out: ' . e(date('M d, Y H:i', $logged_out_ts)) ?>
                        </td>
                        <td>
                            <button class="btn-message"
                                data-user-id="<?= $u['id'] ?>"
                                data-user-name="<?= e($u['first_name'] . ' ' . $u['last_name']) ?>">
                                💬 Message
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
</main>

<!-- Dynamic Modal Container -->
<div id="messageModalContainer"></div>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const modalContainer = document.getElementById('messageModalContainer');

    document.querySelectorAll('.btn-message').forEach(button => {
        button.addEventListener('click', () => {
            const userId = button.getAttribute('data-user-id');
            fetch('../shared/messaging/message_user.php?recipient_id=' + encodeURIComponent(userId))
                .then(res => res.text())
                .then(html => {
                    modalContainer.innerHTML = html;
                });
        });
    });

    document.addEventListener('click', function (e) {
        if (e.target.classList.contains('close')) {
            const modal = document.getElementById('messageModal');
            if (modal) modal.style.display = 'none';
        }
    });

    document.addEventListener('keydown', function (e) {
        if (e.key === "Escape") {
            const modal = document.getElementById('messageModal');
            if (modal && modal.style.display === 'block') {
                modal.style.display = 'none';
            }
        }
    });
});
</script>

</body>
</html>
