<?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_role = $_SESSION['role_id'];
$user_id = $_SESSION['user_id'];
$viewing_user_id = isset($_GET['id']) ? (int) $_GET['id'] : $user_id;
$is_own_profile = ($viewing_user_id == $user_id);

$query = "
    SELECT u.id, u.username, u.email, u.phone_number, u.role_id, u.store_id, u.profile_picture,
           u.first_name, u.last_name,
           u.last_activity, u.last_seen, u.last_logged_in,
           r.role_name AS role_name,
           s.store_name AS 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 = ?
";

$stmt = $conn->prepare($query);
$stmt->bind_param("i", $viewing_user_id);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$result) {
    echo "User not found.";
    exit;
}

$unread_count = 0;
if ($is_own_profile) {
    $stmt = $conn->prepare("SELECT COUNT(*) AS unread_count FROM messages WHERE receiver_id = ? AND is_read = 0");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $unread_count = $stmt->get_result()->fetch_assoc()['unread_count'] ?? 0;
    $stmt->close();
}

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);
}

$isOnline = false;
if (!$is_own_profile && !empty($result['last_activity'])) {
    $isOnline = strtotime($result['last_activity']) >= (time() - 300);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?= $is_own_profile ? 'Your' : e($result['first_name']) . "'s" ?> Profile - 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: rgb(0, 0, 0);
            z-index: -1;
        }

        main.content {
            margin-left: 200px;
            margin-top: 80px;
            padding: 20px 30px;
            backdrop-filter: blur(15px);
            background: rgba(255,255,255,0.05);
            border-radius: 20px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.5);
        }

        .container {
            display: flex;
            align-items: center;
            justify-content: space-between;
            max-width: 900px;
            margin: auto;
            background: rgba(255,255,255,0.12);
            border-radius: 20px;
            padding: 20px 30px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.4);
            gap: 20px;
        }

        .profile-pic {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid rgba(255,255,255,0.3);
            box-shadow: 0 2px 8px rgba(0,0,0,0.3);
        }

        .info {
            flex-grow: 1;
            font-size: 0.95rem;
            color: #eee;
        }

        .info p {
            margin: 6px 0;
            display: flex;
            justify-content: space-between;
        }

        .online-dot, .offline-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 6px;
        }
        .online-dot { background-color: #28a745; }
        .offline-dot { background-color: #bbb; }

        .action-bar {
            margin-top: 20px;
            display: flex;
            justify-content: center;
            gap: 10px;
            flex-wrap: wrap;
        }

        .action-bar a, .action-bar button {
            background: rgba(255,255,255,0.15);
            border: none;
            color: white;
            padding: 8px 16px;
            font-weight: 600;
            border-radius: 30px;
            cursor: pointer;
            text-decoration: none;
            box-shadow: 0 2px 8px rgba(0,0,0,0.3);
            font-size: 0.9rem;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .badge {
            background: #dc3545;
            color: white;
            border-radius: 50%;
            padding: 4px 8px;
            font-size: 12px;
            margin-left: 6px;
            min-width: 20px;
            text-align: center;
        }

        .success {
            background: #28a745b8;
            color: #e6f7e6;
            border: 1px solid #1f7a1f;
            padding: 10px 15px;
            border-radius: 8px;
            font-weight: 600;
            text-align: center;
            margin-bottom: 15px;
        }

        #messageModal {
            display: none;
            position: fixed;
            top: 10%;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(255, 255, 255, 0.9);
            border-radius: 15px;
            padding: 20px 30px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.4);
            z-index: 2000;
            width: 90%;
            max-width: 480px;
            color: #333;
        }
        #messageModal .close {
            float: right;
            cursor: pointer;
            font-weight: 700;
            font-size: 1.2rem;
            color: #666;
        }

        @media (max-width: 768px) {
            main.content {
                margin-left: 0;
                margin-top: 120px;
                padding: 15px;
                border-radius: 15px;
            }
            .container {
                flex-direction: column;
                align-items: center;
                text-align: center;
            }
            .info p {
                flex-direction: column;
                align-items: flex-start;
            }
            .action-bar {
                flex-direction: column;
                align-items: center;
            }
        }
    </style>
</head>
<body>
<div class="overlay"></div>
<main class="content">
    <?php if (isset($_GET['updated']) && $_GET['updated'] == '1'): ?>
        <div class="success">Profile updated successfully!</div>
    <?php endif; ?>

    <div class="container">
        <img src="../../uploads/<?= e($result['profile_picture'] ?: 'default.png') ?>" class="profile-pic" alt="Profile Picture">
        <div class="info">
            <p><strong>Full Name:</strong> <?= e($result['first_name'] . ' ' . $result['last_name']) ?></p>
            <p><strong>Username:</strong> <?= e($result['username']) ?></p>
            <p><strong>Email:</strong> <?= e($result['email']) ?></p>
            <p><strong>Phone:</strong> <?= e($result['phone_number']) ?></p>
            <p><strong>Role:</strong> <?= e($result['role_name'] ?? 'N/A') ?></p>
            <p><strong>Store:</strong> <?= e($result['store_name'] ?? 'N/A') ?></p>

            <?php if (!$is_own_profile): ?>
                <p><strong>Status:</strong>
                    <span class="<?= $isOnline ? 'online-dot' : 'offline-dot' ?>"></span>
                    <?= $isOnline ? 'Online' : 'Offline' ?>
                </p>
                <p><strong>Last Seen:</strong> <?= e(formatTimeAgo($result['last_seen'])) ?></p>
                <p><strong>Last Active:</strong> <?= e(formatTimeAgo($result['last_activity'])) ?></p>
                <p><strong>Last Login:</strong> <?= e(formatTimeAgo($result['last_logged_in'])) ?></p>
            <?php endif; ?>
        </div>
    </div>

    <div class="action-bar">
        <?php if ($is_own_profile): ?>
            <a href="edit_profile.php">✏️ Edit</a>
            <a href="change_password.php">🔑 Password</a>
            <a href="../shared/messaging/inbox.php">📥 Inbox <?= $unread_count > 0 ? "<span class='badge'>$unread_count</span>" : "" ?></a>
            <a href="../shared/messaging/sent.php">📤 Sent</a>
            <a href="../shared/messaging/compose.php">📝 Compose</a>
        <?php else: ?>
            <button id="messageUserBtn">💬 Message</button>
        <?php endif; ?>
    </div>

    <div id="messageModalContainer"></div>
</main>

<script>
document.addEventListener("DOMContentLoaded", function() {
    const btn = document.getElementById("messageUserBtn");
    if (btn) {
        btn.addEventListener("click", function () {
            fetch('../shared/messaging/message_modal.php?recipient_id=<?= $viewing_user_id ?>')
                .then(res => res.text())
                .then(html => {
                    document.getElementById('messageModalContainer').innerHTML = html;
                    document.getElementById('messageModal').style.display = 'block';
                });
        });
    }

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

function refreshMessageBadge() {
    fetch('/digital_pos/pages/shared/messaging/unread_count.php')
        .then(res => res.json())
        .then(data => {
            const badge = document.querySelector('.badge');
            if (!badge) return;
            if (data.success && data.count > 0) {
                badge.textContent = data.count;
                badge.style.display = 'inline-block';
            } else {
                badge.style.display = 'none';
            }
        })
        .catch(err => console.error('Error fetching unread count:', err));
}
refreshMessageBadge();
setInterval(refreshMessageBadge, 30000);
</script>
</body>
</html>
