@extends('layouts.app')
@section('title', 'Users Management — HIGHRA CRM')
@section('header', 'Users Management')

@section('content')
<!-- FLASH NOTIFICATIONS -->
@if(session('success'))
    <div class="ok" style="margin-bottom: 16px;">
        ✓ {{ session('success') }}
    </div>
@endif

@if(session('error'))
    <div class="err" style="margin-bottom: 16px;">
        ✕ {{ session('error') }}
    </div>
@endif

@if(isset($errors) && $errors->any())
    <div class="err" style="margin-bottom: 16px;">
        <ul style="margin: 0; padding-left: 18px;">
            @foreach($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<!-- HEADER ACTION ROW -->
<div class="row" style="margin-bottom: 18px; align-items: flex-start;">
    <div>
        <h1 style="margin: 0 0 4px 0;">Users Directory</h1>
        <p style="color: #8e9ab4; margin: 0;">Manage team members, organization hierarchy, access scopes, and security settings.</p>
    </div>
    <div style="display: flex; gap: 8px; flex-wrap: wrap;">
        @if(auth()->user()?->hasPermission('roles.view'))
            <a href="{{ route('roles.index') }}" class="btn btn-secondary">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
                Roles & Permissions
            </a>
        @endif
        @if(auth()->user()?->hasPermission('audit_logs.view'))
            <a href="{{ route('audit.index') }}" class="btn btn-secondary">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/></svg>
                Audit Logs
            </a>
        @endif
        @if(auth()->user()?->hasPermission('users.create'))
            <a href="{{ route('users.create') }}" class="btn">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                Add New User
            </a>
        @endif
    </div>
</div>

<!-- 5 TOP KPI CARDS -->
<div class="dash-kpi-grid" style="grid-template-columns: repeat(5, minmax(0, 1fr)); margin-bottom: 18px;">
    <div class="dash-kpi-card">
        <div class="dash-kpi-title">Total Users</div>
        <div class="dash-kpi-number" style="color: #ffffff;">{{ $stats['total'] }}</div>
        <div class="dash-kpi-sub">All registered accounts</div>
    </div>
    <div class="dash-kpi-card">
        <div class="dash-kpi-title">Administrators</div>
        <div class="dash-kpi-number" style="color: #818cf8;">{{ $stats['admin'] }}</div>
        <div class="dash-kpi-sub">Full system control</div>
    </div>
    <div class="dash-kpi-card">
        <div class="dash-kpi-title">Sales & Operations</div>
        <div class="dash-kpi-number" style="color: #10b981;">{{ $stats['sales'] }}</div>
        <div class="dash-kpi-sub">Field & office executives</div>
    </div>
    <div class="dash-kpi-card">
        <div class="dash-kpi-title">Active Accounts</div>
        <div class="dash-kpi-number" style="color: #38bdf8;">{{ $stats['active'] }}</div>
        <div class="dash-kpi-sub">Online & operational</div>
    </div>
    <div class="dash-kpi-card">
        <div class="dash-kpi-title">Locked / Suspended</div>
        <div class="dash-kpi-number" style="color: #f43f5e;">{{ $stats['locked'] }}</div>
        <div class="dash-kpi-sub">Security locked accounts</div>
    </div>
</div>

<!-- ADVANCED SEARCH & FILTER TOOLBAR -->
<form method="GET" action="{{ route('users') }}" id="userFilterForm">
    <div class="filter-toolbar" style="margin-bottom: 16px;">
        <div class="filter-grid" style="grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));">
            
            <!-- 1. Search Query -->
            <div class="filter-group" style="grid-column: span 2;">
                <label>Search Users</label>
                <input type="text" name="search" value="{{ request('search') }}" placeholder="Search by name, email, employee ID, mobile, designation...">
            </div>

            <!-- 2. Role Filter -->
            <div class="filter-group">
                <label>Role</label>
                <select name="role" onchange="this.form.submit()">
                    <option value="">All Roles</option>
                    @foreach($roles as $r)
                        <option value="{{ $r->slug }}" {{ request('role') == $r->slug ? 'selected' : '' }}>
                            {{ $r->name }}
                        </option>
                    @endforeach
                </select>
            </div>

            <!-- 3. Department Filter -->
            <div class="filter-group">
                <label>Department</label>
                <select name="department" onchange="this.form.submit()">
                    <option value="">All Departments</option>
                    @foreach($departments as $dept)
                        <option value="{{ $dept }}" {{ request('department') == $dept ? 'selected' : '' }}>
                            {{ $dept }}
                        </option>
                    @endforeach
                </select>
            </div>

            <!-- 4. Status Filter -->
            <div class="filter-group">
                <label>Account Status</label>
                <select name="status" onchange="this.form.submit()">
                    <option value="">All Statuses</option>
                    <option value="active" {{ request('status') === 'active' ? 'selected' : '' }}>Active</option>
                    <option value="inactive" {{ request('status') === 'inactive' ? 'selected' : '' }}>Inactive</option>
                    <option value="locked" {{ request('status') === 'locked' ? 'selected' : '' }}>Locked</option>
                </select>
            </div>

            <!-- 5. Date From -->
            <div class="filter-group">
                <label>Joined After</label>
                <input type="date" name="from_date" value="{{ request('from_date') }}">
            </div>

            <!-- 6. Actions -->
            <div class="filter-group">
                <label>&nbsp;</label>
                <div class="filter-actions">
                    <button type="submit" class="btn" style="padding: 7px 12px;">Filter</button>
                    @if(request()->hasAny(['search', 'role', 'department', 'status', 'from_date', 'to_date']))
                        <a href="{{ route('users') }}" class="btn btn-secondary" style="padding: 7px 10px;" title="Reset filters">✕ Reset</a>
                    @endif
                </div>
            </div>

        </div>
    </div>
</form>

<!-- BULK ACTIONS FORM & TABLE PANEL -->
<form method="POST" action="{{ route('users.bulk_action') }}" id="bulkActionForm">
    @csrf

    <!-- BULK ACTIONS BAR (Visible when checkboxes selected) -->
    <div id="bulkActionBar" style="display: none; background: #131d38; border: 1px solid #28375c; border-radius: 8px; padding: 10px 14px; margin-bottom: 14px; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 10px;">
        <div style="display: flex; align-items: center; gap: 10px;">
            <span style="font-weight: 600; color: #818cf8;" id="selectedCountBadge">0 users selected</span>
        </div>
        <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
            <select name="bulk_action" id="bulkActionSelect" onchange="toggleBulkRoleDropdown(this.value)" style="margin: 0; width: auto; font-size: 12px; padding: 5px 8px;">
                <option value="">Choose Bulk Action...</option>
                <option value="activate">✓ Activate Selected</option>
                <option value="deactivate">⊘ Deactivate Selected</option>
                <option value="lock">🔒 Lock Accounts</option>
                <option value="unlock">🔓 Unlock Accounts</option>
                <option value="change_role">👔 Change Role</option>
                <option value="delete">🗑 Delete Selected</option>
            </select>

            <select name="bulk_role" id="bulkRoleSelect" style="display: none; margin: 0; width: auto; font-size: 12px; padding: 5px 8px;">
                <option value="">Select Target Role...</option>
                @foreach($roles as $r)
                    <option value="{{ $r->slug }}">{{ $r->name }}</option>
                @endforeach
            </select>

            <button type="submit" class="btn btn-sm" onclick="return confirmBulkAction()">Apply Action</button>
        </div>
    </div>

    <!-- MAIN USERS DATA TABLE PANEL -->
    <div class="panel" style="margin-top: 0;">
        <div style="margin-bottom: 12px; display: flex; justify-content: space-between; align-items: center;">
            <div>
                <h2 style="font-size: 14px; margin: 0 0 2px 0;">All System Users ({{ $users->total() }})</h2>
                <p style="font-size: 11.5px; color: #8e9ab4; margin: 0;">Showing page {{ $users->currentPage() }} of {{ $users->lastPage() }}</p>
            </div>
            <div style="display: flex; gap: 8px; align-items: center;">
                <span style="font-size: 11.5px; color: #8e9ab4;">Sort by:</span>
                <a href="{{ request()->fullUrlWithQuery(['sort_by' => 'name', 'sort_dir' => (request('sort_dir') === 'asc' ? 'desc' : 'asc')]) }}" class="btn btn-secondary btn-sm" style="padding: 3px 8px; font-size: 11px;">
                    Name {!! request('sort_by') === 'name' ? (request('sort_dir') === 'desc' ? '↓' : '↑') : '' !!}
                </a>
                <a href="{{ request()->fullUrlWithQuery(['sort_by' => 'created_at', 'sort_dir' => (request('sort_dir') === 'asc' ? 'desc' : 'asc')]) }}" class="btn btn-secondary btn-sm" style="padding: 3px 8px; font-size: 11px;">
                    Joined {!! request('sort_by') === 'created_at' ? (request('sort_dir') === 'desc' ? '↓' : '↑') : '' !!}
                </a>
            </div>
        </div>

        <div style="overflow-x: auto;">
            <table style="width: 100%;">
                <thead>
                    <tr>
                        <th style="width: 30px; text-align: center;">
                            <input type="checkbox" id="selectAllCheckbox" onclick="toggleSelectAll(this)" style="margin: 0;">
                        </th>
                        <th>User / Employee</th>
                        <th>Contact Information</th>
                        <th>Department & Designation</th>
                        <th>Role & Scope</th>
                        <th>Status</th>
                        <th>Last Login</th>
                        <th style="text-align: right;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($users as $u)
                        <tr>
                            <!-- Checkbox -->
                            <td style="text-align: center;">
                                <input type="checkbox" name="user_ids[]" value="{{ $u->id }}" class="user-row-checkbox" onclick="updateSelectionCounter()" style="margin: 0;">
                            </td>

                            <!-- User Avatar & Details -->
                            <td>
                                <div style="display: flex; align-items: center; gap: 10px;">
                                    <div style="width: 34px; height: 34px; border-radius: 50%; background: #182442; color: #818cf8; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 12px; border: 1px solid #2d3d6b; flex-shrink: 0;">
                                        {{ strtoupper(substr($u->name, 0, 1)) }}
                                    </div>
                                    <div>
                                        <a href="{{ route('users.show', $u) }}" style="color: #ffffff; font-weight: 600; font-size: 13px; text-decoration: none; display: block;" title="View User Profile">
                                            {{ $u->name }}
                                        </a>
                                        <div style="display: flex; gap: 6px; align-items: center; margin-top: 2px;">
                                            <span style="color: #8e9ab4; font-size: 10.5px; font-family: monospace;">{{ $u->employee_id ?? 'EMP-#'.$u->id }}</span>
                                            @if($u->branch_location)
                                                <span style="color: #64748b; font-size: 10px;">· 📍 {{ $u->branch_location }}</span>
                                            @endif
                                        </div>
                                    </div>
                                </div>
                            </td>

                            <!-- Contact -->
                            <td>
                                <div style="color: #e2e8f0; font-size: 12px;">
                                    <a href="mailto:{{ $u->email }}" style="color: #cbd5e1; text-decoration: none;">✉️ {{ $u->email }}</a>
                                </div>
                                @if($u->mobile)
                                    <div style="color: #8e9ab4; font-size: 11px; margin-top: 2px;">
                                        <a href="tel:{{ $u->mobile }}" style="color: #94a3b8; text-decoration: none;">📞 {{ $u->mobile }}</a>
                                    </div>
                                @endif
                            </td>

                            <!-- Department & Designation -->
                            <td>
                                <strong style="color: #f1f5f9; display: block; font-size: 12px;">{{ $u->designation ?: 'Staff' }}</strong>
                                <span style="color: #8e9ab4; font-size: 11px;">🏢 {{ $u->department ?: 'Operations' }}</span>
                                @if($u->manager)
                                    <div style="color: #64748b; font-size: 10px; margin-top: 2px;">
                                        Reports to: <a href="{{ route('users.show', $u->manager) }}" style="color: #a5b4fc; text-decoration: none;">{{ $u->manager->name }}</a>
                                    </div>
                                @endif
                            </td>

                            <!-- Role & Access Scope -->
                            <td>
                                @php
                                    $roleSlug = strtolower($u->role);
                                    $badgeClass = match($roleSlug) {
                                        'super-admin', 'admin' => 'badge-admin',
                                        'manager' => 'badge-manager',
                                        'sales' => 'badge-sales',
                                        'telecaller' => 'badge-telecaller',
                                        'support' => 'badge-support',
                                        'finance' => 'badge-finance',
                                        'marketing' => 'badge-marketing',
                                        default => 'badge-custom'
                                    };
                                @endphp
                                <div>
                                    <span class="badge {{ $badgeClass }}">
                                        {{ $u->roleModel?->name ?? ucfirst($u->role) }}
                                    </span>
                                </div>
                                <small style="display: block; color: #8e9ab4; font-size: 10px; margin-top: 3px; text-transform: uppercase;">
                                    Scope: {{ $u->access_scope ?? 'all' }} records
                                </small>
                            </td>

                            <!-- Status -->
                            <td>
                                @if($u->is_locked)
                                    <span class="badge" style="background: #450a0a; color: #fca5a5; border: 1px solid #7f1d1d;">🔒 Locked</span>
                                @elseif($u->active)
                                    <span class="badge badge-active">✓ Active</span>
                                @else
                                    <span class="badge badge-inactive">⊘ Inactive</span>
                                @endif

                                @if($u->two_factor_enabled)
                                    <span title="2FA Enabled" style="display: block; font-size: 9.5px; color: #34d399; margin-top: 2px;">🛡️ 2FA On</span>
                                @endif
                            </td>

                            <!-- Last Login -->
                            <td>
                                @if($u->last_login_at)
                                    <span style="color: #cbd5e1; font-size: 11.5px; display: block;">{{ $u->last_login_at->diffForHumans() }}</span>
                                    <small style="color: #64748b; font-size: 10px; font-family: monospace;">IP: {{ $u->last_login_ip ?? '127.0.0.1' }}</small>
                                @else
                                    <span style="color: #64748b; font-size: 11px;">Never logged in</span>
                                @endif
                            </td>

                            <!-- Actions -->
                            <td style="text-align: right;">
                                <div style="display: inline-flex; gap: 4px;">
                                    <!-- View Profile -->
                                    <a href="{{ route('users.show', $u) }}" class="btn btn-secondary btn-sm" style="padding: 4px 8px;" title="View Complete Profile & Permissions">
                                        View
                                    </a>

                                    @if(auth()->user()?->hasPermission('users.edit'))
                                        <!-- Edit -->
                                        <a href="{{ route('users.edit', $u) }}" class="btn btn-secondary btn-sm" style="padding: 4px 8px;" title="Edit User">
                                            Edit
                                        </a>

                                        <!-- Quick Actions Dropdown Button -->
                                        <button type="button" class="btn btn-secondary btn-sm" style="padding: 4px 6px;" onclick="openQuickActionModal({{ json_encode($u) }})" title="More Actions">
                                            •••
                                        </button>
                                    @endif
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="8" style="text-align: center; padding: 50px; color: #64748b;">
                                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#475569" stroke-width="1.5" style="margin-bottom: 8px;"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
                                <div>No users found matching your filters.</div>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <!-- PAGINATION FOOTER -->
        <div class="pagination-wrapper">
            <div class="pagination-left">
                <span>Showing {{ $users->firstItem() ?? 0 }} to {{ $users->lastItem() ?? 0 }} of {{ $users->total() }} users</span>
                <div class="entries-select-wrapper">
                    <label for="per_page_select" style="margin:0; font-size:11.5px; color:#8e9ab4;">Show:</label>
                    <select id="per_page_select" onchange="applyPerPage(this.value)">
                        <option value="10" {{ ($perPageInput ?? '20') == '10' ? 'selected' : '' }}>10</option>
                        <option value="20" {{ ($perPageInput ?? '20') == '20' ? 'selected' : '' }}>20</option>
                        <option value="50" {{ ($perPageInput ?? '20') == '50' ? 'selected' : '' }}>50</option>
                        <option value="all" {{ ($perPageInput ?? '20') == 'all' ? 'selected' : '' }}>All</option>
                    </select>
                </div>
            </div>
            <div>
                {{ $users->links() }}
            </div>
        </div>
    </div>
</form>

<!-- QUICK ACTIONS MODAL -->
<div id="quickActionModal" class="modal-backdrop">
    <div class="modal" style="max-width: 440px;">
        <div class="modal-header">
            <h3 id="quickModalUserName">User Actions</h3>
            <button class="modal-close" onclick="closeModal('quickActionModal')">&times;</button>
        </div>
        <div style="padding: 10px 0; display: flex; flex-direction: column; gap: 10px;">
            <!-- Reset Password Trigger -->
            <button type="button" class="btn btn-secondary" style="justify-content: flex-start; padding: 10px 14px;" onclick="triggerPasswordResetFromQuick()">
                🔑 Reset Account Password
            </button>

            <!-- Toggle Status Trigger -->
            <form id="quickToggleStatusForm" method="POST" action="">
                @csrf
                @method('PATCH')
                <button type="submit" class="btn btn-secondary" style="width: 100%; justify-content: flex-start; padding: 10px 14px;" id="quickToggleStatusBtn">
                    ⊘ Deactivate Account
                </button>
            </form>

            <!-- Toggle Lock Trigger -->
            <form id="quickToggleLockForm" method="POST" action="">
                @csrf
                @method('PATCH')
                <button type="submit" class="btn btn-secondary" style="width: 100%; justify-content: flex-start; padding: 10px 14px;" id="quickToggleLockBtn">
                    🔒 Lock / Unlock Account
                </button>
            </form>

            <!-- Delete User Trigger -->
            <form id="quickDeleteForm" method="POST" action="" onsubmit="return confirm('Are you sure you want to permanently delete this user account? This action cannot be undone.');">
                @csrf
                @method('DELETE')
                <button type="submit" class="btn btn-danger" style="width: 100%; justify-content: flex-start; padding: 10px 14px;">
                    🗑 Delete User Permanently
                </button>
            </form>
        </div>
    </div>
</div>

<!-- RESET PASSWORD MODAL -->
<div id="resetPasswordModal" class="modal-backdrop">
    <div class="modal" style="max-width: 420px;">
        <div class="modal-header">
            <h3>Reset User Password</h3>
            <button class="modal-close" onclick="closeModal('resetPasswordModal')">&times;</button>
        </div>
        <form id="resetPasswordForm" method="POST" action="">
            @csrf
            <p style="font-size: 12px; color: #8e9ab4; margin: 0 0 12px 0;" id="resetPasswordNotice">
                Set a new temporary or permanent password for this account.
            </p>
            <label>New Password * (Min 6 characters)</label>
            <input type="password" name="new_password" required placeholder="Enter new password" minlength="6">

            <div class="modal-actions">
                <button type="button" class="btn btn-secondary" onclick="closeModal('resetPasswordModal')">Cancel</button>
                <button type="submit" class="btn">Update Password</button>
            </div>
        </form>
    </div>
</div>

<script>
let currentSelectedUser = null;

function openModal(id) {
    document.getElementById(id).classList.add('show');
}

function closeModal(id) {
    document.getElementById(id).classList.remove('show');
}

function openQuickActionModal(user) {
    currentSelectedUser = user;
    document.getElementById('quickModalUserName').textContent = user.name + ' — Actions';
    document.getElementById('quickToggleStatusForm').action = '/users/' + user.id + '/toggle';
    document.getElementById('quickToggleLockForm').action = '/users/' + user.id + '/lock';
    document.getElementById('quickDeleteForm').action = '/users/' + user.id;

    document.getElementById('quickToggleStatusBtn').textContent = user.active ? '⊘ Deactivate Account' : '✓ Activate Account';
    document.getElementById('quickToggleLockBtn').textContent = user.is_locked ? '🔓 Unlock Account' : '🔒 Lock Account';

    openModal('quickActionModal');
}

function triggerPasswordResetFromQuick() {
    closeModal('quickActionModal');
    if (!currentSelectedUser) return;
    document.getElementById('resetPasswordForm').action = '/users/' + currentSelectedUser.id + '/reset-password';
    document.getElementById('resetPasswordNotice').textContent = 'Set a new password for ' + currentSelectedUser.name + ' (' + currentSelectedUser.email + ').';
    openModal('resetPasswordModal');
}

// Bulk Selection
function toggleSelectAll(master) {
    const checkboxes = document.querySelectorAll('.user-row-checkbox');
    checkboxes.forEach(cb => cb.checked = master.checked);
    updateSelectionCounter();
}

function updateSelectionCounter() {
    const checked = document.querySelectorAll('.user-row-checkbox:checked');
    const bar = document.getElementById('bulkActionBar');
    const badge = document.getElementById('selectedCountBadge');

    if (checked.length > 0) {
        bar.style.display = 'flex';
        badge.textContent = checked.length + ' ' + (checked.length === 1 ? 'user' : 'users') + ' selected';
    } else {
        bar.style.display = 'none';
        document.getElementById('selectAllCheckbox').checked = false;
    }
}

function toggleBulkRoleDropdown(action) {
    const roleSelect = document.getElementById('bulkRoleSelect');
    if (action === 'change_role') {
        roleSelect.style.display = 'inline-block';
        roleSelect.required = true;
    } else {
        roleSelect.style.display = 'none';
        roleSelect.required = false;
    }
}

function confirmBulkAction() {
    const action = document.getElementById('bulkActionSelect').value;
    if (!action) {
        alert('Please choose an action first.');
        return false;
    }
    const count = document.querySelectorAll('.user-row-checkbox:checked').length;
    if (action === 'delete') {
        return confirm('Are you sure you want to permanently delete ' + count + ' selected users?');
    }
    return confirm('Apply ' + action + ' to ' + count + ' selected users?');
}

function applyPerPage(val) {
    const url = new URL(window.location.href);
    url.searchParams.set('per_page', val);
    url.searchParams.delete('page');
    window.location.href = url.toString();
}

window.addEventListener('click', function(e) {
    if (e.target.classList.contains('modal-backdrop')) {
        e.target.classList.remove('show');
    }
});
</script>
@endsection
