<?php
$fullName = htmlspecialchars(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
$initials = strtoupper(substr($user['first_name'] ?? 'U', 0, 1) . substr($user['last_name'] ?? '', 0, 1));
$pageTitle = $fullName;
$breadcrumb = [
    ['label' => 'Users', 'url' => APP_URL . '/users'],
    ['label' => $pageTitle, 'url' => null]
];
ob_start();

$typeClass = 'bg-gray-100 text-gray-800';
$typeLabel = 'Unknown';
if (($user['entity_type'] ?? '') === 'org_user') { $typeClass = 'bg-blue-100 text-blue-800'; $typeLabel = 'Org User'; }
if (($user['entity_type'] ?? '') === 'contractor_user') { $typeClass = 'bg-green-100 text-green-800'; $typeLabel = 'Contractor User'; }
if (($user['entity_type'] ?? '') === 'supplier_user') { $typeClass = 'bg-purple-100 text-purple-800'; $typeLabel = 'Supplier User'; }
if (($user['is_super_admin'] ?? false)) { $typeClass = 'bg-red-100 text-red-800'; $typeLabel = 'Super Admin'; }

$isActive = !empty($user['is_active']);
?>
<div class="mb-6 flex flex-col md:flex-row md:items-center justify-between">
    <div class="flex items-center gap-4">
        <h1 class="text-2xl font-bold text-gray-900"><?= $pageTitle ?></h1>
        <span class="px-3 py-1 text-xs font-semibold rounded-full <?= $typeClass ?>"><?= $typeLabel ?></span>
        <span class="px-3 py-1 text-xs font-semibold rounded-full <?= $isActive ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800' ?>">
            <?= $isActive ? 'Active' : 'Inactive' ?>
        </span>
    </div>
    <div class="mt-4 md:mt-0 flex gap-2">
        <form action="<?= APP_URL ?>/users/<?= $user['id'] ?>/toggle-active" method="POST">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION[CSRF_TOKEN_NAME] ?? '') ?>">
            <button type="submit" class="bg-gray-100 hover:bg-gray-200 text-gray-800 border border-gray-300 font-bold py-2 px-4 rounded shadow">
                <?= $isActive ? 'Disable User' : 'Enable User' ?>
            </button>
        </form>
        <a href="<?= APP_URL ?>/users/<?= $user['id'] ?>/edit" class="bg-[#0A3A6B] hover:bg-blue-700 text-white font-bold py-2 px-4 rounded shadow">Edit User</a>
    </div>
</div>

<!-- Header Card -->
<div class="bg-white rounded-lg shadow p-6 mb-6">
    <div class="flex items-start md:items-center gap-6">
        <div class="h-24 w-24 rounded-full bg-[#0A3A6B] text-white flex items-center justify-center font-bold text-3xl shadow">
            <?= $initials ?>
        </div>
        <div>
            <h2 class="text-2xl font-bold text-gray-900"><?= $fullName ?></h2>
            <p class="text-gray-500 mb-2"><?= htmlspecialchars($user['email'] ?? '') ?></p>
            <div class="flex flex-wrap gap-4 text-sm text-gray-500">
                <div class="flex items-center gap-1">
                    <svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                    Last login: <?= htmlspecialchars($user['last_login_at'] ?? 'Never') ?>
                </div>
                <div class="flex items-center gap-1">
                    <svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" /></svg>
                    Member since: <?= htmlspecialchars($user['created_at'] ?? 'Unknown') ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Tabs -->
<div class="bg-white rounded-lg shadow mb-6">
    <div class="border-b border-gray-200">
        <nav class="flex -mb-px px-6" aria-label="Tabs">
            <button class="tab-button active w-1/3 py-4 px-1 text-center border-b-2 font-medium text-sm text-[#0A3A6B] border-[#0A3A6B]" data-target="tab-profile">Profile</button>
            <button class="tab-button w-1/3 py-4 px-1 text-center border-b-2 font-medium text-sm text-gray-500 border-transparent hover:text-gray-700 hover:border-gray-300" data-target="tab-roles">Roles & Permissions</button>
            <button class="tab-button w-1/3 py-4 px-1 text-center border-b-2 font-medium text-sm text-gray-500 border-transparent hover:text-gray-700 hover:border-gray-300" data-target="tab-activity">Activity</button>
        </nav>
    </div>

    <!-- Tab Contents -->
    <div class="p-6">
        <!-- Profile Tab -->
        <div id="tab-profile" class="tab-content block">
            <h3 class="text-lg font-medium text-gray-900 mb-4 border-b pb-2">User Details</h3>
            <dl class="grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-6">
                <div>
                    <dt class="text-sm font-medium text-gray-500">First Name</dt>
                    <dd class="mt-1 text-sm text-gray-900"><?= htmlspecialchars($user['first_name'] ?? '-') ?></dd>
                </div>
                <div>
                    <dt class="text-sm font-medium text-gray-500">Last Name</dt>
                    <dd class="mt-1 text-sm text-gray-900"><?= htmlspecialchars($user['last_name'] ?? '-') ?></dd>
                </div>
                <div>
                    <dt class="text-sm font-medium text-gray-500">Email Address</dt>
                    <dd class="mt-1 text-sm text-gray-900"><?= htmlspecialchars($user['email'] ?? '-') ?></dd>
                </div>
                <div>
                    <dt class="text-sm font-medium text-gray-500">Phone Number</dt>
                    <dd class="mt-1 text-sm text-gray-900"><?= htmlspecialchars($user['phone'] ?? '-') ?></dd>
                </div>
                <div>
                    <dt class="text-sm font-medium text-gray-500">Locale</dt>
                    <dd class="mt-1 text-sm text-gray-900"><?= htmlspecialchars($user['locale'] ?? 'en_US') ?></dd>
                </div>
                <div>
                    <dt class="text-sm font-medium text-gray-500">Timezone</dt>
                    <dd class="mt-1 text-sm text-gray-900"><?= htmlspecialchars($user['timezone'] ?? 'UTC') ?></dd>
                </div>
                <div>
                    <dt class="text-sm font-medium text-gray-500">Currency</dt>
                    <dd class="mt-1 text-sm text-gray-900"><?= htmlspecialchars($user['currency'] ?? 'USD') ?></dd>
                </div>
            </dl>
            
            <div class="mt-8">
                <h3 class="text-lg font-medium text-gray-900 mb-4 border-b pb-2">Admin Actions</h3>
                <div class="flex flex-wrap gap-4">
                    <form action="<?= APP_URL ?>/users/<?= $user['id'] ?>/reset-password" method="POST" onsubmit="return confirm('Send password reset email to user?');">
                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION[CSRF_TOKEN_NAME] ?? '') ?>">
                        <button type="submit" class="bg-white border border-gray-300 text-gray-700 hover:bg-gray-50 font-medium py-2 px-4 rounded shadow-sm text-sm">Send Password Reset</button>
                    </form>
                    <?php if (!empty($user['2fa_enabled'])): ?>
                    <form action="<?= APP_URL ?>/users/<?= $user['id'] ?>/disable-2fa" method="POST" onsubmit="return confirm('Disable 2FA for this user?');">
                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION[CSRF_TOKEN_NAME] ?? '') ?>">
                        <button type="submit" class="bg-red-50 text-red-700 hover:bg-red-100 border border-red-200 font-medium py-2 px-4 rounded shadow-sm text-sm">Disable 2FA</button>
                    </form>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Roles Tab -->
        <div id="tab-roles" class="tab-content hidden">
            <h3 class="text-lg font-medium text-gray-900 mb-4 border-b pb-2">Assigned Roles</h3>
            <div class="flex flex-wrap gap-2 mb-8">
                <?php if (empty($userRoles)): ?>
                    <p class="text-sm text-gray-500">No roles assigned.</p>
                <?php else: ?>
                    <?php foreach ($userRoles as $role): ?>
                        <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-800">
                            <?= htmlspecialchars($role['name'] ?? 'Role') ?>
                        </span>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <h3 class="text-lg font-medium text-gray-900 mb-4 border-b pb-2">Effective Permissions</h3>
            <div class="overflow-x-auto">
                <table class="min-w-full border-collapse border border-gray-200 text-sm">
                    <thead>
                        <tr class="bg-gray-50">
                            <th class="border border-gray-200 px-4 py-2 text-left font-medium text-gray-700">Module</th>
                            <th class="border border-gray-200 px-4 py-2 text-center font-medium text-gray-700">View</th>
                            <th class="border border-gray-200 px-4 py-2 text-center font-medium text-gray-700">Create</th>
                            <th class="border border-gray-200 px-4 py-2 text-center font-medium text-gray-700">Edit</th>
                            <th class="border border-gray-200 px-4 py-2 text-center font-medium text-gray-700">Delete</th>
                            <th class="border border-gray-200 px-4 py-2 text-center font-medium text-gray-700">Approve</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $modules = ['auth', 'dashboard', 'projects', 'clients', 'contractors', 'suppliers', 'finance', 'reports', 'users', 'settings', 'billing'];
                        $actions = ['view', 'create', 'edit', 'delete', 'approve'];
                        foreach ($modules as $mod): 
                        ?>
                        <tr>
                            <td class="border border-gray-200 px-4 py-2 font-medium capitalize"><?= $mod ?></td>
                            <?php foreach ($actions as $act): ?>
                                <?php 
                                $hasPerm = isset($permissions[$mod]) && in_array($act, $permissions[$mod]);
                                ?>
                                <td class="border border-gray-200 px-4 py-2 text-center">
                                    <?php if ($hasPerm): ?>
                                        <svg class="h-5 w-5 text-green-500 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" /></svg>
                                    <?php else: ?>
                                        <span class="text-gray-300">-</span>
                                    <?php endif; ?>
                                </td>
                            <?php endforeach; ?>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Activity Tab -->
        <div id="tab-activity" class="tab-content hidden">
            <?php if (empty($activities)): ?>
                <p class="text-gray-500 italic text-center py-8">No recent activity found.</p>
            <?php else: ?>
                <div class="flow-root">
                    <ul class="-mb-8">
                        <?php foreach ($activities as $i => $act): ?>
                        <li>
                            <div class="relative pb-8">
                                <?php if ($i !== count($activities) - 1): ?>
                                <span class="absolute top-4 left-4 -ml-px h-full w-0.5 bg-gray-200" aria-hidden="true"></span>
                                <?php endif; ?>
                                <div class="relative flex space-x-3">
                                    <div>
                                        <span class="h-8 w-8 rounded-full bg-gray-100 flex items-center justify-center ring-8 ring-white text-gray-500">
                                            <svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" /></svg>
                                        </span>
                                    </div>
                                    <div class="min-w-0 flex-1 pt-1.5 flex justify-between space-x-4">
                                        <div>
                                            <p class="text-sm text-gray-500"><?= htmlspecialchars($act['description'] ?? '') ?></p>
                                        </div>
                                        <div class="text-right text-sm whitespace-nowrap text-gray-500">
                                            <time><?= htmlspecialchars($act['created_at'] ?? '') ?></time>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const tabs = document.querySelectorAll('.tab-button');
    const contents = document.querySelectorAll('.tab-content');
    
    tabs.forEach(tab => {
        tab.addEventListener('click', () => {
            tabs.forEach(t => {
                t.classList.remove('active', 'text-[#0A3A6B]', 'border-[#0A3A6B]');
                t.classList.add('text-gray-500', 'border-transparent');
            });
            tab.classList.add('active', 'text-[#0A3A6B]', 'border-[#0A3A6B]');
            tab.classList.remove('text-gray-500', 'border-transparent');
            
            contents.forEach(c => c.classList.add('hidden'));
            document.getElementById(tab.dataset.target).classList.remove('hidden');
        });
    });
});
</script>
<?php
$content = ob_get_clean();
require ROOT_PATH . '/modules/shared/views/layouts/main.php';
?>