<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<?php
$words    = preg_split('/\s+/', trim($user->full_name));
$initials = strtoupper(($words[0][0] ?? '') . ($words[count($words) - 1][0] ?? ''));

// Small icon map for the Permissions tab — this app has no icon field on
// Lookups::$permissionModules itself, so this is a display-only lookup
// local to this view, with a generic fallback for anything unmapped.
$moduleIcons = [
    'dashboard' => 'bi-speedometer2', 'shifts' => 'bi-calendar-week', 'reservations' => 'bi-calendar-check',
    'front_desk_ops' => 'bi-door-open', 'guests' => 'bi-people', 'complaints' => 'bi-exclamation-octagon',
    'rooms' => 'bi-door-closed', 'housekeeping' => 'bi-bucket', 'maintenance' => 'bi-tools',
    'restaurant' => 'bi-cup-hot', 'events' => 'bi-calendar-event', 'billing_finance' => 'bi-cash-coin',
    'reports' => 'bi-graph-up', 'corporate_accounts' => 'bi-building', 'invoicing' => 'bi-receipt',
    'ai_modules' => 'bi-stars', 'staff' => 'bi-person-badge', 'inventory' => 'bi-box-seam',
    'communication' => 'bi-chat-dots', 'campaigns' => 'bi-megaphone', 'activity_log' => 'bi-clock-history',
    'rate_plans' => 'bi-tags', 'expenses' => 'bi-receipt-cutoff', 'services' => 'bi-bag-plus', 'settings' => 'bi-gear',
];

$roleModules = array_filter($lookups->permissionModules, static fn ($meta) => in_array($user->role, $meta['roles'], true));
?>

<nav aria-label="breadcrumb" class="mb-2">
    <ol class="breadcrumb small mb-0">
        <li class="breadcrumb-item"><a href="<?= site_url('users') ?>" class="text-decoration-none">Staff Users</a></li>
        <li class="breadcrumb-item active"><?= esc($user->full_name) ?></li>
    </ol>
</nav>

<div class="d-flex justify-content-between align-items-start mb-3">
    <h1 class="h3 mb-0">Staff Profile</h1>
</div>

<div class="row g-3">
    <div class="col-lg-3">
        <div class="card shadow-sm text-center">
            <div class="card-body">
                <span class="badge bg-<?= $user->is_active ? 'success' : 'danger' ?> float-end"><?= $user->is_active ? 'Active' : 'Deactivated' ?></span>
                <form action="<?= site_url('users/' . $user->id . '/photo') ?>" method="post" enctype="multipart/form-data" id="photoForm">
                    <?= csrf_field() ?>
                    <label class="d-inline-block position-relative mb-3" style="cursor: pointer;" title="Change photo">
                        <?php if ($user->photo_path): ?>
                            <img src="<?= site_url('uploads/' . $user->photo_path) ?>" alt="" class="rounded-circle" style="width: 84px; height: 84px; object-fit: cover;">
                        <?php else: ?>
                            <div class="rounded-circle d-flex align-items-center justify-content-center" style="width: 84px; height: 84px; background: color-mix(in srgb, var(--brand) 15%, white); color: var(--brand); font-weight: 700; font-size: 1.6rem;"><?= esc($initials) ?></div>
                        <?php endif; ?>
                        <span class="position-absolute bottom-0 end-0 rounded-circle d-flex align-items-center justify-content-center" style="width: 28px; height: 28px; background: var(--brand); color: #fff; border: 2px solid #fff;"><i class="bi bi-camera-fill small"></i></span>
                        <input type="file" name="photo" accept="image/jpeg,image/png,image/webp" class="d-none" onchange="document.getElementById('photoForm').submit();">
                    </label>
                </form>
                <h2 class="h5 mb-1"><?= esc($user->full_name) ?></h2>
                <span class="badge bg-<?= $lookups->staffRoles[$user->role]['badge'] ?? 'secondary' ?> mb-3"><?= esc($lookups->staffRoles[$user->role]['label'] ?? $user->role) ?></span>
                <div class="text-start small border-top pt-3">
                    <p class="mb-2"><i class="bi bi-envelope text-muted me-2"></i><?= esc($user->email) ?></p>
                    <p class="mb-2"><i class="bi bi-telephone text-muted me-2"></i><?= esc($user->phone ?: '—') ?></p>
                    <p class="mb-0"><i class="bi bi-calendar3 text-muted me-2"></i>Joined <?= esc(date('d M Y', strtotime($user->created_at))) ?></p>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-6">
        <ul class="nav nav-tabs mb-3" id="profileTabs">
            <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#tab-profile">Profile</a></li>
            <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-permissions">Permissions</a></li>
            <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-activity">Activity Log</a></li>
            <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-shifts">Shift Assignments</a></li>
            <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-documents">Documents</a></li>
            <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-salary">Salary History</a></li>
        </ul>

        <div class="tab-content">
            <div class="tab-pane fade show active" id="tab-profile">
                <div class="card shadow-sm mb-3">
                    <div class="card-header">Personal Information</div>
                    <div class="card-body">
                        <div class="row row-cols-2 g-3 small">
                            <div class="col"><span class="text-muted">Full Name</span><br><span class="fw-semibold"><?= esc($user->full_name) ?></span></div>
                            <div class="col"><span class="text-muted">Email Address</span><br><span class="fw-semibold"><?= esc($user->email) ?></span></div>
                            <div class="col"><span class="text-muted">Phone Number</span><br><span class="fw-semibold"><?= esc($user->phone ?: '—') ?></span></div>
                            <div class="col"><span class="text-muted">Date Joined</span><br><span class="fw-semibold"><?= esc(date('d M Y', strtotime($user->created_at))) ?></span></div>
                        </div>
                    </div>
                </div>

                <div class="card shadow-sm mb-3">
                    <div class="card-header">Account Information</div>
                    <div class="card-body">
                        <div class="row row-cols-2 g-3 small">
                            <div class="col"><span class="text-muted">Role</span><br><span class="badge bg-<?= $lookups->staffRoles[$user->role]['badge'] ?? 'secondary' ?>"><?= esc($lookups->staffRoles[$user->role]['label'] ?? $user->role) ?></span></div>
                            <div class="col"><span class="text-muted">Status</span><br><span class="badge bg-<?= $user->is_active ? 'success' : 'danger' ?>"><?= $user->is_active ? 'Active' : 'Deactivated' ?></span></div>
                            <div class="col"><span class="text-muted">Last Login</span><br><span class="fw-semibold"><?= $lastLogin ? esc(date('d M Y, g:i a', strtotime($lastLogin))) : 'Never' ?></span></div>
                            <div class="col">
                                <span class="text-muted">Password</span><br>
                                <span class="fw-semibold">••••••••</span>
                                <form action="<?= site_url('users/' . $user->id . '/reset-password') ?>" method="post" class="d-inline">
                                    <?= csrf_field() ?>
                                    <button type="submit" class="btn btn-link btn-sm p-0 ms-1">Reset Password</button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card shadow-sm mb-3">
                    <div class="card-header">Basic Salary</div>
                    <div class="card-body">
                        <form action="<?= site_url('users/' . $user->id . '/salary') ?>" method="post" class="d-flex align-items-end gap-2">
                            <?= csrf_field() ?>
                            <div>
                                <label class="form-label small text-muted mb-1">Monthly Basic Salary (GHS)</label>
                                <input type="number" step="0.01" min="0" name="basic_salary" value="<?= esc($user->basic_salary ?? '') ?>" class="form-control form-control-sm" style="width: 180px;" placeholder="Not set">
                            </div>
                            <button type="submit" class="btn btn-sm btn-outline-secondary">Save</button>
                        </form>
                        <p class="text-muted small mb-0 mt-2">Used only to pre-fill new payslips when a payroll run is created — see <a href="<?= site_url('payroll') ?>" class="text-decoration-none">Payroll</a>.</p>
                    </div>
                </div>

                <div class="card shadow-sm mb-3">
                    <div class="card-header">Identification &amp; Banking</div>
                    <div class="card-body">
                        <form action="<?= site_url('users/' . $user->id . '/identification') ?>" method="post">
                            <?= csrf_field() ?>
                            <div class="row row-cols-1 row-cols-md-2 g-3 mb-2">
                                <div class="col">
                                    <label class="form-label small text-muted mb-1">Employee ID</label>
                                    <input type="text" name="employee_id" value="<?= esc($user->employee_id ?? '') ?>" class="form-control form-control-sm" placeholder="Not set">
                                </div>
                                <div class="col">
                                    <label class="form-label small text-muted mb-1">SSNIT Number</label>
                                    <input type="text" name="ssnit_number" value="<?= esc($user->ssnit_number ?? '') ?>" class="form-control form-control-sm" placeholder="Not set">
                                </div>
                                <div class="col">
                                    <label class="form-label small text-muted mb-1">Ghana Card Number</label>
                                    <input type="text" name="ghana_card_number" value="<?= esc($user->ghana_card_number ?? '') ?>" class="form-control form-control-sm" placeholder="Not set">
                                </div>
                                <div class="col">
                                    <label class="form-label small text-muted mb-1">Bank Name</label>
                                    <input type="text" name="bank_name" value="<?= esc($user->bank_name ?? '') ?>" class="form-control form-control-sm" placeholder="Not set">
                                </div>
                                <div class="col">
                                    <label class="form-label small text-muted mb-1">Bank Branch</label>
                                    <input type="text" name="bank_branch" value="<?= esc($user->bank_branch ?? '') ?>" class="form-control form-control-sm" placeholder="Not set">
                                </div>
                                <div class="col">
                                    <label class="form-label small text-muted mb-1">Bank Account Number</label>
                                    <input type="text" name="bank_account_number" value="<?= esc($user->bank_account_number ?? '') ?>" class="form-control form-control-sm" placeholder="Not set">
                                </div>
                            </div>
                            <button type="submit" class="btn btn-sm btn-outline-secondary">Save</button>
                        </form>
                        <p class="text-muted small mb-0 mt-2">Shown on the payslip PDF for reference — record-keeping only, salary is never disbursed to this account by MaxYields.</p>
                    </div>
                </div>

                <div class="card shadow-sm">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        Role Permissions Summary
                        <a href="#tab-permissions" data-bs-toggle="tab" class="small text-decoration-none">View all permissions <i class="bi bi-arrow-right"></i></a>
                    </div>
                    <div class="card-body">
                        <div class="row row-cols-2 row-cols-md-4 g-3 small text-center">
                            <?php foreach (array_slice($roleModules, 0, 4, true) as $moduleKey => $meta): ?>
                                <div class="col">
                                    <i class="bi <?= $moduleIcons[$moduleKey] ?? 'bi-check2-square' ?> fs-4 d-block mb-1" style="color: var(--brand);"></i>
                                    <div class="fw-semibold"><?= esc($meta['label']) ?></div>
                                    <div class="text-muted"><?= ($permissions[$moduleKey] ?? true) ? 'Visible' : 'Hidden' ?></div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="tab-permissions">
                <div class="card shadow-sm">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        Modules Visible to <?= esc($lookups->staffRoles[$user->role]['label'] ?? $user->role) ?>
                        <a href="<?= site_url('role-management') ?>" class="btn btn-sm btn-outline-primary">Manage Permissions</a>
                    </div>
                    <div class="card-body">
                        <p class="text-muted small">Permissions are set per role, not per person — every <?= esc($lookups->staffRoles[$user->role]['label'] ?? $user->role) ?> shares this same access.</p>
                        <div class="row row-cols-1 row-cols-md-2 g-2 small">
                            <?php foreach ($roleModules as $moduleKey => $meta): ?>
                                <div class="col d-flex align-items-center justify-content-between border rounded px-3 py-2">
                                    <span><i class="bi <?= $moduleIcons[$moduleKey] ?? 'bi-check2-square' ?> me-2 text-muted"></i><?= esc($meta['label']) ?></span>
                                    <?php if ($permissions[$moduleKey] ?? true): ?>
                                        <span class="badge bg-success-subtle text-success-emphasis">Visible</span>
                                    <?php else: ?>
                                        <span class="badge bg-secondary-subtle text-secondary-emphasis">Hidden</span>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="tab-activity">
                <div class="card shadow-sm">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        Recent Activity
                        <a href="<?= site_url('activity-log?user_id=' . $user->id) ?>" class="small text-decoration-none">View all activity <i class="bi bi-arrow-right"></i></a>
                    </div>
                    <div class="list-group list-group-flush">
                        <?php if (empty($activity)): ?>
                            <div class="list-group-item text-center text-muted py-4 small">No activity recorded yet.</div>
                        <?php endif; ?>
                        <?php foreach ($activity as $entry): ?>
                            <div class="list-group-item small">
                                <div><?= esc($entry->action) ?></div>
                                <div class="text-muted"><?= esc(date('d M Y, g:i a', strtotime($entry->created_at))) ?> · <span class="badge bg-light text-dark border"><?= esc($entry->module) ?></span></div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="tab-shifts">
                <div class="card shadow-sm">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        Upcoming Shifts
                        <a href="<?= site_url('shifts') ?>" class="small text-decoration-none">Full Schedule <i class="bi bi-arrow-right"></i></a>
                    </div>
                    <div class="list-group list-group-flush">
                        <?php if (empty($shifts)): ?>
                            <div class="list-group-item text-center text-muted py-4 small">No upcoming shifts assigned.</div>
                        <?php endif; ?>
                        <?php foreach ($shifts as $shift):
                            $blockMeta = $lookups->shiftBlocks[$shift->shift_block] ?? ['label' => $shift->shift_block, 'badge' => 'secondary'];
                        ?>
                            <div class="list-group-item d-flex justify-content-between align-items-center small">
                                <span><?= esc(date('d M Y (D)', strtotime($shift->shift_date))) ?></span>
                                <span class="badge bg-<?= $blockMeta['badge'] ?>"><?= esc($blockMeta['label']) ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="tab-documents">
                <div class="card shadow-sm mb-3">
                    <div class="card-header">Upload a Document</div>
                    <div class="card-body">
                        <form action="<?= site_url('users/' . $user->id . '/documents') ?>" method="post" enctype="multipart/form-data" class="row g-2 align-items-end">
                            <?= csrf_field() ?>
                            <div class="col-sm-4">
                                <label class="form-label small text-muted mb-1">Document Type</label>
                                <select name="document_type" class="form-select form-select-sm" required>
                                    <?php foreach ($lookups->staffDocumentTypes as $typeKey => $typeMeta): ?>
                                        <option value="<?= esc($typeKey) ?>"><?= esc($typeMeta['label']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-sm-6">
                                <label class="form-label small text-muted mb-1">File (PDF, Word, JPG, or PNG — up to 10MB)</label>
                                <input type="file" name="document" class="form-control form-control-sm" accept=".pdf,.doc,.docx,image/jpeg,image/png" required>
                            </div>
                            <div class="col-sm-2">
                                <button type="submit" class="btn btn-sm btn-primary w-100"><i class="bi bi-upload me-1"></i>Upload</button>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="card shadow-sm">
                    <div class="card-header">Employment Documents</div>
                    <div class="list-group list-group-flush">
                        <?php if (empty($documents)): ?>
                            <div class="list-group-item text-center text-muted py-4 small">No documents uploaded yet.</div>
                        <?php endif; ?>
                        <?php foreach ($documents as $document): ?>
                            <div class="list-group-item d-flex justify-content-between align-items-center small">
                                <div>
                                    <span class="badge bg-light text-dark border me-2"><?= esc($lookups->staffDocumentTypes[$document->document_type]['label'] ?? $document->document_type) ?></span>
                                    <?= esc($document->original_filename) ?>
                                    <div class="text-muted"><?= esc(date('d M Y, g:i a', strtotime($document->created_at))) ?></div>
                                </div>
                                <div class="d-flex align-items-center gap-2">
                                    <a href="<?= site_url('users/' . $user->id . '/documents/' . $document->id . '/download') ?>" class="btn btn-sm btn-outline-secondary"><i class="bi bi-download"></i></a>
                                    <form action="<?= site_url('users/' . $user->id . '/documents/' . $document->id . '/delete') ?>" method="post" onsubmit="return confirm('Delete this document?');">
                                        <?= csrf_field() ?>
                                        <button type="submit" class="btn btn-sm btn-outline-danger"><i class="bi bi-trash"></i></button>
                                    </form>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="tab-salary">
                <div class="card shadow-sm">
                    <div class="card-header">Payslip History</div>
                    <div class="table-responsive">
                        <table class="table mb-0 align-middle small">
                            <thead><tr><th>Pay Period</th><th class="text-end">Basic</th><th class="text-end">Allowances</th><th class="text-end">Deductions</th><th class="text-end">Net Pay</th><th></th></tr></thead>
                            <tbody>
                            <?php if (empty($payslips)): ?>
                                <tr><td colspan="6" class="text-center text-muted py-4">No payslips generated yet.</td></tr>
                            <?php endif; ?>
                            <?php foreach ($payslips as $slip): ?>
                                <tr>
                                    <td class="fw-semibold"><?= esc(date('F Y', strtotime($slip->created_at))) ?></td>
                                    <td class="text-end"><?= format_money($slip->basic_salary) ?></td>
                                    <td class="text-end"><?= format_money($slip->total_allowances) ?></td>
                                    <td class="text-end"><?= format_money($slip->total_deductions) ?></td>
                                    <td class="text-end fw-semibold"><?= format_money($slip->net_pay) ?></td>
                                    <td class="text-end"><a href="<?= site_url('payroll/' . $slip->payroll_run_id . '/payslips/' . $slip->id . '/pdf') ?>" target="_blank" class="btn btn-sm btn-outline-secondary"><i class="bi bi-file-earmark-pdf"></i></a></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-3">
        <div class="card shadow-sm mb-3">
            <div class="card-header">Quick Actions</div>
            <div class="list-group list-group-flush">
                <form action="<?= site_url('users/' . $user->id . '/reset-password') ?>" method="post">
                    <?= csrf_field() ?>
                    <button type="submit" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center small border-0">
                        <span><i class="bi bi-key me-2"></i>Reset Password</span><i class="bi bi-chevron-right text-muted"></i>
                    </button>
                </form>
                <form action="<?= site_url('users/' . $user->id . '/toggle-active') ?>" method="post">
                    <?= csrf_field() ?>
                    <button type="submit" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center small border-0 <?= $user->is_active ? 'text-danger' : 'text-success' ?>" <?= (int) $user->id === (int) session('userId') ? 'disabled' : '' ?>>
                        <span><i class="bi bi-person-<?= $user->is_active ? 'dash' : 'check' ?> me-2"></i><?= $user->is_active ? 'Deactivate Account' : 'Reactivate Account' ?></span><i class="bi bi-chevron-right"></i>
                    </button>
                </form>
                <a href="<?= site_url('activity-log?user_id=' . $user->id) ?>" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center small">
                    <span><i class="bi bi-clock-history me-2"></i>View Activity Log</span><i class="bi bi-chevron-right text-muted"></i>
                </a>
                <a href="<?= site_url('role-management') ?>" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center small">
                    <span><i class="bi bi-shield-lock me-2"></i>Manage Permissions</span><i class="bi bi-chevron-right text-muted"></i>
                </a>
            </div>
        </div>

        <div class="card shadow-sm">
            <div class="card-header">Recent Activity</div>
            <div class="list-group list-group-flush">
                <?php if (empty($activity)): ?>
                    <div class="list-group-item text-center text-muted py-3 small">Nothing yet.</div>
                <?php endif; ?>
                <?php foreach (array_slice($activity, 0, 4) as $entry): ?>
                    <div class="list-group-item small">
                        <div class="fw-semibold"><?= esc($entry->action) ?></div>
                        <div class="text-muted"><?= esc(date('d M Y, g:i a', strtotime($entry->created_at))) ?></div>
                    </div>
                <?php endforeach; ?>
            </div>
            <?php if (! empty($activity)): ?>
            <div class="card-footer bg-white text-center">
                <a href="<?= site_url('activity-log?user_id=' . $user->id) ?>" class="small text-decoration-none">View all activity <i class="bi bi-arrow-right"></i></a>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<?= $this->endSection() ?>
