@extends('layouts.dashboard.superadminapp')

@section('title', 'User Details')

@section('styles')
<style>
    /* Compact Page Header */
    .page-header {
        background: linear-gradient(135deg, #fff 0%, #f8f9fc 100%);
        border-radius: 8px;
        padding: 0.5rem 1rem;
        margin-bottom: 0.75rem;
        box-shadow: 0 1px 5px rgba(0, 0, 0, 0.04);
    }
    .page-header h1 {
        font-size: 1rem;
        font-weight: 600;
        color: #2d3748;
        margin: 0;
    }

    /* DateTime Display */
    .datetime-display { gap: 0.5rem; }
    .date-box, .time-box {
        display: flex;
        align-items: center;
        gap: 0.35rem;
        background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
        padding: 0.35rem 0.65rem;
        border-radius: 6px;
        border: 1px solid #e2e8f0;
        font-size: 0.75rem;
        color: #475569;
        font-weight: 500;
    }
    .date-box i, .time-box i { color: #4e73df; font-size: 0.7rem; }
    .time-box {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        color: #fff;
        border: none;
        min-width: 85px;
        justify-content: center;
    }
    .time-box i { color: rgba(255,255,255,0.8); }
    .time-box .display-time {
        font-family: 'Courier New', monospace;
        font-weight: 600;
        letter-spacing: 0.5px;
    }

    /* Clickable Dashboard Cards */
    .dashboard-card {
        border: none;
        border-radius: 8px;
        transition: all 0.2s ease;
        overflow: hidden;
        cursor: pointer;
        text-decoration: none;
        display: block;
    }
    .dashboard-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12) !important;
        text-decoration: none;
    }

    /* Compact KPI Cards */
    .kpi-card {
        border-radius: 8px;
        color: #fff;
        position: relative;
        overflow: hidden;
        padding: 0.75rem 1rem !important;
    }
    .kpi-card .kpi-icon {
        font-size: 2rem;
        opacity: 0.25;
        position: absolute;
        right: 0.75rem;
        top: 50%;
        transform: translateY(-50%);
    }
    .kpi-card .kpi-value {
        font-size: 1.5rem;
        font-weight: 700;
        margin-bottom: 0.1rem;
        line-height: 1.2;
    }
    .kpi-card .kpi-label {
        font-size: 0.7rem;
        text-transform: uppercase;
        letter-spacing: 0.3px;
        opacity: 0.9;
    }
    .kpi-card .kpi-info {
        font-size: 0.65rem;
        margin-top: 0.25rem;
        opacity: 0.8;
    }

    /* Gradient backgrounds */
    .bg-gradient-primary { background: linear-gradient(135deg, #4e73df 0%, #224abe 100%); }
    .bg-gradient-success { background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%); }
    .bg-gradient-warning { background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%); }
    .bg-gradient-danger { background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%); }
    .bg-gradient-info { background: linear-gradient(135deg, #36b9cc 0%, #258391 100%); }

    /* Compact Cards */
    .compact-card {
        border: none;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        margin-bottom: 0.75rem;
    }
    .compact-card .card-header {
        background: transparent;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        padding: 0.6rem 1rem;
        border-radius: 8px 8px 0 0;
    }
    .compact-card .card-body { padding: 1rem; }
    .compact-card .card-header h6 { font-size: 0.85rem; margin: 0; }

    /* Enhanced DataTable Styling */
    .datatable-card .card-header {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        border-radius: 8px 8px 0 0;
        padding: 0.6rem 1rem;
    }
    .datatable-card .card-header h6 {
        color: #fff;
        font-size: 0.85rem;
        margin: 0;
    }

    /* DataTable Container */
    #userTable_wrapper {
        padding: 0;
    }
    #userTable_wrapper .row:first-child {
        background: #f8f9fc;
        padding: 0.75rem 1rem;
        margin: 0;
        border-bottom: 1px solid #e3e6f0;
    }
    #userTable_wrapper .row:last-child {
        background: #f8f9fc;
        padding: 0.75rem 1rem;
        margin: 0;
        border-top: 1px solid #e3e6f0;
    }

    /* DataTable Search & Length */
    .dataTables_filter input {
        border: 1px solid #d1d3e2;
        border-radius: 6px;
        padding: 0.4rem 0.75rem;
        font-size: 0.8rem;
        transition: border-color 0.2s, box-shadow 0.2s;
    }
    .dataTables_filter input:focus {
        border-color: #4e73df;
        box-shadow: 0 0 0 0.2rem rgba(78, 115, 223, 0.15);
        outline: none;
    }
    .dataTables_length select {
        border: 1px solid #d1d3e2;
        border-radius: 6px;
        padding: 0.4rem 0.5rem;
        font-size: 0.8rem;
    }
    .dataTables_length label, .dataTables_filter label {
        font-size: 0.8rem;
        color: #5a5c69;
        margin-bottom: 0;
    }

    /* DataTable Info & Pagination */
    .dataTables_info {
        font-size: 0.75rem;
        color: #6c757d;
        padding-top: 0.5rem;
    }
    .dataTables_paginate {
        padding-top: 0.25rem;
    }
    .dataTables_paginate .paginate_button {
        padding: 0.35rem 0.65rem !important;
        margin: 0 2px !important;
        border-radius: 6px !important;
        border: 1px solid #d1d3e2 !important;
        background: #fff !important;
        color: #5a5c69 !important;
        font-size: 0.75rem !important;
        transition: all 0.2s !important;
    }
    .dataTables_paginate .paginate_button:hover {
        background: #4e73df !important;
        border-color: #4e73df !important;
        color: #fff !important;
    }
    .dataTables_paginate .paginate_button.current {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%) !important;
        border-color: #4e73df !important;
        color: #fff !important;
        font-weight: 600;
    }
    .dataTables_paginate .paginate_button.disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }

    /* Table Styling */
    #userTable {
        border-collapse: separate;
        border-spacing: 0;
        width: 100% !important;
    }
    #userTable thead th {
        background: linear-gradient(135deg, #f8f9fc 0%, #eaecf4 100%);
        border: none;
        border-bottom: 2px solid #e3e6f0;
        padding: 0.75rem 0.5rem;
        font-size: 0.75rem;
        font-weight: 700;
        color: #4e73df;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }
    #userTable tbody td {
        padding: 0.6rem 0.5rem;
        font-size: 0.8rem;
        border: none;
        border-bottom: 1px solid #e9ecef;
        vertical-align: middle;
    }
    #userTable tbody tr {
        transition: all 0.15s ease;
    }
    #userTable tbody tr:hover {
        background-color: #f0f4ff !important;
    }
    #userTable tbody tr:nth-child(even) {
        background-color: #fafbfc;
    }

    /* Role Badges */
    .role-badge {
        padding: 0.35rem 0.6rem;
        border-radius: 20px;
        font-size: 0.65rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }
    .role-badge.superadmin { background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%); color: #fff; }
    .role-badge.admin { background: linear-gradient(135deg, #4e73df 0%, #224abe 100%); color: #fff; }
    .role-badge.manager { background: linear-gradient(135deg, #36b9cc 0%, #258391 100%); color: #fff; }

    /* Status Badges */
    .status-badge {
        padding: 0.3rem 0.6rem;
        border-radius: 20px;
        font-size: 0.65rem;
        font-weight: 600;
    }
    .status-badge.active { background: #d4edda; color: #155724; }
    .status-badge.inactive { background: #f8d7da; color: #721c24; }

    /* Action Buttons */
    .action-btn {
        width: 30px;
        height: 30px;
        padding: 0;
        border-radius: 6px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-size: 0.75rem;
        transition: all 0.2s;
        border: none;
        margin: 0 2px;
    }
    .action-btn:hover { transform: scale(1.1); }
    .action-btn.edit-btn { background: #fff3cd; color: #856404; }
    .action-btn.edit-btn:hover { background: #f6c23e; color: #fff; }
    .action-btn.toggle-btn { background: #e8f5e9; color: #2e7d32; }
    .action-btn.toggle-btn:hover { background: #1cc88a; color: #fff; }
    .action-btn.toggle-btn.inactive { background: #f5f5f5; color: #9e9e9e; }
    .action-btn.toggle-btn.inactive:hover { background: #858796; color: #fff; }
    .action-btn.delete-btn { background: #ffebee; color: #c62828; }
    .action-btn.delete-btn:hover { background: #e74a3b; color: #fff; }
    .action-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none !important; }

    /* User Avatar */
    .user-avatar {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        color: #fff;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        font-size: 0.7rem;
        margin-right: 0.5rem;
    }
    .user-info { display: flex; align-items: center; }
    .user-name { font-weight: 600; color: #333; }
    .user-email { font-size: 0.7rem; color: #6c757d; }

    /* Add User Button */
    .add-btn {
        background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);
        border: none;
        padding: 0.4rem 1rem;
        border-radius: 6px;
        font-size: 0.8rem;
        font-weight: 600;
        color: #fff;
        transition: all 0.2s;
    }
    .add-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(28, 200, 138, 0.3);
        color: #fff;
    }

    /* Enhanced Modal Styling */
    #userModal .modal-content,
    #deleteUserModal .modal-content {
        border: none;
        border-radius: 10px;
        overflow: hidden;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
    }
    #userModal .modal-header.primary-header,
    #deleteUserModal .modal-header.danger-header {
        display: flex !important;
        align-items: center;
        justify-content: space-between;
        min-height: 45px;
    }
    #userModal .modal-header.primary-header {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%) !important;
        padding: 0.6rem 1rem !important;
        border-bottom: 2px solid rgba(255,255,255,0.2) !important;
    }
    #deleteUserModal .modal-header.danger-header {
        background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%) !important;
        padding: 0.6rem 1rem !important;
        border-bottom: 2px solid rgba(255,255,255,0.2) !important;
    }
    #userModal .modal-header .close,
    #deleteUserModal .modal-header .close {
        opacity: 1;
        text-shadow: none;
        padding: 0;
        margin: 0;
        width: 26px;
        height: 26px;
        border-radius: 50%;
        background: rgba(255,255,255,0.2);
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.2s;
        color: #fff;
        font-size: 1.2rem;
        line-height: 1;
    }
    #userModal .modal-header .close:hover,
    #deleteUserModal .modal-header .close:hover {
        background: rgba(255,255,255,0.35);
        transform: rotate(90deg);
    }
    #userModal .modal-title,
    #deleteUserModal .modal-title {
        font-size: 0.9rem;
        font-weight: 600;
        color: #fff !important;
    }
    #userModal .modal-body {
        padding: 0.85rem 1rem !important;
        background: #fff;
    }
    #deleteUserModal .modal-body {
        padding: 1rem !important;
        background: #fff;
    }
    #userModal .modal-footer,
    #deleteUserModal .modal-footer {
        background: #f8f9fc;
        border-top: 1px solid #e3e6f0;
        padding: 0.6rem 1rem;
        display: flex;
        justify-content: flex-end;
        gap: 0.5rem;
    }
    #deleteUserModal .modal-footer {
        justify-content: center;
    }
    #userModal .modal-footer .btn,
    #deleteUserModal .modal-footer .btn {
        border-radius: 5px;
        padding: 0.45rem 1rem;
        font-weight: 600;
        font-size: 0.8rem;
        transition: all 0.2s;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        min-width: 95px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 0.3rem;
        height: 34px;
    }
    #userModal .modal-footer .btn:hover,
    #deleteUserModal .modal-footer .btn:hover {
        transform: translateY(-1px);
        box-shadow: 0 3px 8px rgba(0,0,0,0.15);
    }
    #userModal .modal-footer .btn-secondary,
    #deleteUserModal .modal-footer .btn-secondary {
        background: linear-gradient(135deg, #6c757d 0%, #545b62 100%);
        border: none;
        color: #fff;
    }
    #userModal .modal-footer .btn-primary {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        border: none;
        color: #fff;
    }
    #deleteUserModal .modal-footer .btn-danger {
        background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%);
        border: none;
        color: #fff;
    }

    /* Compact Form Styling */
    #userModal .form-group-modern {
        margin-bottom: 0.6rem;
    }
    #userModal .form-label {
        font-size: 0.8rem;
        font-weight: 600;
        color: #495057;
        margin-bottom: 0.25rem;
        display: flex;
        align-items: center;
        gap: 0.25rem;
    }
    #userModal .form-label i {
        font-size: 0.75rem;
    }
    #userModal .form-control-modern {
        border: 1px solid #d1d3e2;
        border-radius: 5px;
        padding: 0.4rem 0.65rem;
        font-size: 0.85rem;
        height: auto !important;
        min-height: 36px;
        transition: all 0.2s;
        background: #fff;
    }
    #userModal .form-control-modern:hover {
        border-color: #b8bcc5;
    }
    #userModal .form-control-modern:focus {
        border-color: #4e73df;
        box-shadow: 0 0 0 2px rgba(78, 115, 223, 0.15);
        background: #fff;
    }
    #userModal .form-control-modern::placeholder {
        color: #adb5bd;
        font-size: 0.82rem;
    }
    #userModal .row {
        margin-bottom: 0;
    }
    #userModal .row > [class*="col-"] {
        padding-left: 8px;
        padding-right: 8px;
    }

    /* Compact Input Group */
    #userModal .input-group {
        height: 36px;
    }
    #userModal .input-group .form-control-modern {
        border-right: none;
        height: 36px !important;
        min-height: 36px;
    }
    #userModal .input-group .input-group-append {
        height: 36px;
    }
    #userModal .input-group .input-group-append .btn {
        border: 1px solid #d1d3e2;
        border-left: none;
        background: #f8f9fc;
        color: #6c757d;
        padding: 0 0.6rem;
        height: 36px;
        display: flex;
        align-items: center;
        border-radius: 0 5px 5px 0 !important;
    }
    #userModal .input-group .input-group-append .btn:hover {
        background: #4e73df;
        color: #fff;
        border-color: #4e73df;
    }
    #userModal .input-group:focus-within .input-group-append .btn {
        border-color: #4e73df;
    }
    #userModal #pass-hint {
        font-size: 0.7rem;
        margin-top: 0.2rem;
    }

    /* Form Error Alert */
    #formErrors {
        border-radius: 5px;
        border: none;
        background: #fff5f5;
        border-left: 3px solid #e74a3b;
        padding: 0.5rem 0.75rem;
        margin-bottom: 0.6rem;
    }
    #formErrors ul { margin-bottom: 0; font-size: 0.8rem; }

    /* Delete Modal Enhancement */
    .delete-modal-icon {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background: linear-gradient(135deg, #fff5f5 0%, #fee8e7 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 0.6rem;
        border: 2px solid #f8d7da;
    }
    .delete-modal-icon i {
        font-size: 1.3rem;
        color: #e74a3b;
    }
    .delete-user-name {
        background: #f8f9fc;
        padding: 0.4rem 0.8rem;
        border-radius: 5px;
        border: 1px dashed #d1d3e2;
        display: inline-block;
        font-size: 0.85rem;
    }
    #deleteUserModal .modal-body p {
        margin-bottom: 0.5rem;
        font-size: 0.85rem;
    }
    #deleteUserModal .modal-body p.text-muted {
        font-size: 0.75rem;
    }

    /* Enhanced Toast Notification */
    .custom-toast {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        min-width: 280px;
        max-width: 350px;
        border-radius: 8px;
        box-shadow: 0 8px 24px rgba(0,0,0,0.2);
        border: none;
        animation: slideInRight 0.3s ease;
    }
    @keyframes slideInRight {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    .custom-toast .toast-body {
        padding: 0.65rem 1rem;
        font-size: 0.85rem;
        font-weight: 500;
        display: flex;
        align-items: center;
    }
    .custom-toast .toast-body i {
        margin-right: 0.5rem;
    }
    .custom-toast .close {
        color: rgba(255,255,255,0.8);
        opacity: 1;
        text-shadow: none;
    }
    .custom-toast .close:hover {
        color: #fff;
    }
    .custom-toast.bg-success {
        background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%) !important;
    }
    .custom-toast.bg-danger {
        background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%) !important;
    }

    /* Modal Animation Enhancement */
    .modal.fade .modal-dialog {
        transform: scale(0.9) translateY(-20px);
        transition: transform 0.2s ease;
    }
    .modal.show .modal-dialog {
        transform: scale(1) translateY(0);
    }

    /* Compact row margins */
    .row.mb-4 { margin-bottom: 0.75rem !important; }
    .col-xl-3.mb-3, .col-md-6.mb-3 { margin-bottom: 0.5rem !important; }

    /* Quick Actions */
    .quick-link-card {
        background: #fff;
        border-radius: 8px;
        padding: 0.75rem;
        text-align: center;
        transition: all 0.2s;
        border: 1px solid rgba(0, 0, 0, 0.05);
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
    }
    .quick-link-card:hover {
        border-color: #4e73df;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(78, 115, 223, 0.15);
    }
    .quick-link-card i { font-size: 1.25rem; margin-bottom: 0.25rem; }
    .quick-link-card .link-title { font-weight: 600; color: #333; font-size: 0.7rem; }

    /* Responsive */
    @media (max-width: 768px) {
        .kpi-card .kpi-value { font-size: 1.25rem; }
        .page-header { flex-direction: column; gap: 0.5rem; }
    }
</style>
@endsection

@section('content')
<div class="container-fluid">

    <!-- Page Header -->
    <div class="page-header d-flex align-items-center justify-content-between flex-wrap">
        <h1><i class="fas fa-users-cog mr-2 text-primary"></i>UEPL | User Management</h1>
        <div class="datetime-display d-flex align-items-center">
            <div class="date-box">
                <i class="far fa-calendar-alt"></i>
                <span id="day">{{ now()->format('l') }}</span>,
                <span id="daynum">{{ now()->format('d') }}</span>
                <span id="month">{{ now()->format('F') }}</span>
                <span id="year">{{ now()->format('Y') }}</span>
            </div>
            <div class="time-box">
                <i class="far fa-clock"></i>
                <span class="display-time"></span>
            </div>
        </div>
    </div>

    <!-- KPI Cards Row -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-3">
            <div class="dashboard-card">
                <div class="kpi-card bg-gradient-primary shadow">
                    <i class="fas fa-users kpi-icon"></i>
                    <div class="kpi-value" id="totalUsers">0</div>
                    <div class="kpi-label">Total Users</div>
                    <div class="kpi-info"><i class="fas fa-database mr-1"></i> All registered users</div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <div class="dashboard-card">
                <div class="kpi-card bg-gradient-success shadow">
                    <i class="fas fa-user-check kpi-icon"></i>
                    <div class="kpi-value" id="activeUsers">0</div>
                    <div class="kpi-label">Active Users</div>
                    <div class="kpi-info"><i class="fas fa-check-circle mr-1"></i> Currently active</div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <div class="dashboard-card">
                <div class="kpi-card bg-gradient-warning shadow">
                    <i class="fas fa-user-shield kpi-icon"></i>
                    <div class="kpi-value" id="superadminCount">0</div>
                    <div class="kpi-label">Super Admins</div>
                    <div class="kpi-info"><i class="fas fa-crown mr-1"></i> Full access users</div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <div class="dashboard-card">
                <div class="kpi-card bg-gradient-danger shadow">
                    <i class="fas fa-user-times kpi-icon"></i>
                    <div class="kpi-value" id="inactiveUsers">0</div>
                    <div class="kpi-label">Inactive Users</div>
                    <div class="kpi-info"><i class="fas fa-ban mr-1"></i> Deactivated accounts</div>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="compact-card card shadow mb-3">
        <div class="card-header d-flex align-items-center justify-content-between">
            <h6 class="m-0 font-weight-bold text-info">
                <i class="fas fa-bolt mr-2"></i>Quick Actions
            </h6>
        </div>
        <div class="card-body py-2">
            <div class="row">
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="javascript:void(0)" class="text-decoration-none" id="quickAddUser">
                        <div class="quick-link-card">
                            <i class="fas fa-user-plus text-success"></i>
                            <div class="link-title">Add User</div>
                        </div>
                    </a>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.employee.employeedetails') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-id-badge text-primary"></i>
                            <div class="link-title">Employees</div>
                        </div>
                    </a>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.profile.index') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-user-circle text-info"></i>
                            <div class="link-title">My Profile</div>
                        </div>
                    </a>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.dashboard.dashboard') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-tachometer-alt text-warning"></i>
                            <div class="link-title">Dashboard</div>
                        </div>
                    </a>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.report.employeereport') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-chart-bar text-danger"></i>
                            <div class="link-title">Reports</div>
                        </div>
                    </a>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.employee.index') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-clipboard-list text-secondary"></i>
                            <div class="link-title">Attendance</div>
                        </div>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Users DataTable Card -->
    <div class="compact-card card datatable-card shadow">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h6 class="m-0 font-weight-bold">
                <i class="fas fa-table mr-2"></i> Users Directory
            </h6>
            <button class="add-btn" id="addUserBtn" title="Add New User">
                <i class="fas fa-plus mr-1"></i> Add User
            </button>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0" id="userTable">
                    <thead>
                        <tr class="text-center">
                            <th width="5%">Sl.No</th>
                            <th width="22%">User</th>
                            <th width="20%">Email</th>
                            <th width="12%">Role</th>
                            <th width="10%">Status</th>
                            <th width="13%">Created</th>
                            <th width="18%">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Loaded by AJAX -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>

<!-- Add/Edit User Modal -->
<div class="modal fade" id="userModal" tabindex="-1" aria-labelledby="userModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <!-- Header -->
            <div class="modal-header primary-header">
                <h6 class="modal-title mb-0" id="userModalLabel">
                    <i class="fas fa-user-plus mr-2" id="modalIcon"></i>Add New User
                </h6>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span>&times;</span>
                </button>
            </div>

            <form id="userForm">
                @csrf
                <input type="hidden" name="user_id" id="user_id">
                <div class="modal-body">
                    <!-- Error Alert -->
                    <div id="formErrors" class="alert alert-danger d-none" role="alert">
                        <small><i class="fas fa-exclamation-triangle mr-1"></i><strong>Error:</strong></small>
                        <ul class="mb-0 pl-3 small" id="errorList"></ul>
                    </div>

                    <!-- Name & Email Row -->
                    <div class="row">
                        <div class="col-md-6 form-group-modern">
                            <label class="form-label"><i class="fas fa-user text-primary"></i> Name <span class="text-danger">*</span></label>
                            <input name="name" id="name" class="form-control form-control-modern" placeholder="Enter full name" required>
                        </div>
                        <div class="col-md-6 form-group-modern">
                            <label class="form-label"><i class="fas fa-envelope text-primary"></i> Email <span class="text-danger">*</span></label>
                            <input name="email" id="email" type="email" class="form-control form-control-modern" placeholder="user@example.com" required>
                        </div>
                    </div>

                    <!-- Password Row -->
                    <div class="row">
                        <div class="col-12 form-group-modern">
                            <label class="form-label"><i class="fas fa-lock text-primary"></i> Password <span id="pass-req" class="text-danger">*</span></label>
                            <div class="input-group">
                                <input name="password" id="password" type="password" class="form-control form-control-modern" placeholder="Min 8 characters">
                                <div class="input-group-append">
                                    <button class="btn toggle-password" type="button">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </div>
                            </div>
                            <small class="text-muted d-block" id="pass-hint"><i class="fas fa-info-circle mr-1"></i>Required for new users</small>
                        </div>
                    </div>

                    <!-- Role & Status Row -->
                    <div class="row">
                        <div class="col-md-6 form-group-modern">
                            <label class="form-label"><i class="fas fa-user-tag text-primary"></i> Role <span class="text-danger">*</span></label>
                            <select name="role" id="role" class="form-control form-control-modern" required>
                                <option value="">-- Select Role --</option>
                                <option value="superadmin">Super Admin</option>
                                <option value="admin">Admin</option>
                                <option value="manager">Manager</option>
                            </select>
                        </div>
                        <div class="col-md-6 form-group-modern">
                            <label class="form-label"><i class="fas fa-toggle-on text-primary"></i> Status</label>
                            <select name="status" id="status" class="form-control form-control-modern">
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- Footer -->
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        <i class="fas fa-times"></i>
                        <span>Cancel</span>
                    </button>
                    <button type="submit" class="btn btn-primary" id="saveUserBtn">
                        <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                        <i class="fas fa-check btn-icon"></i>
                        <span class="btn-text">Save</span>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteUserModal" tabindex="-1" aria-labelledby="deleteUserLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content">
            <div class="modal-header danger-header">
                <h6 class="modal-title mb-0" id="deleteUserLabel">
                    <i class="fas fa-exclamation-triangle mr-2"></i>Confirm Delete
                </h6>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body text-center">
                <div class="delete-modal-icon">
                    <i class="fas fa-user-times"></i>
                </div>
                <p class="text-dark">Are you sure you want to delete?</p>
                <div class="delete-user-name">
                    <i class="fas fa-user mr-1 text-muted"></i>
                    <span class="font-weight-bold" id="deleteUserName"></span>
                </div>
                <p class="text-muted mt-2 mb-0"><small><i class="fas fa-exclamation-circle mr-1"></i>This action cannot be undone.</small></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">
                    <i class="fas fa-times"></i>
                    <span>Cancel</span>
                </button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">
                    <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                    <i class="fas fa-trash-alt btn-icon"></i>
                    <span class="btn-text">Delete</span>
                </button>
            </div>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script>
$(document).ready(function() {
    var currentUserId = {{ auth()->id() }};
    var usersData = [];

    // Dynamic Date/Time
    function updateDateTime() {
        const now = new Date();
        const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
        const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

        document.getElementById('day').textContent = days[now.getDay()];
        document.getElementById('daynum').textContent = now.getDate();
        document.getElementById('month').textContent = months[now.getMonth()];
        document.getElementById('year').textContent = now.getFullYear();

        const timeStr = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
        document.querySelector('.display-time').textContent = timeStr;
    }
    updateDateTime();
    setInterval(updateDateTime, 1000);

    // Get user initials for avatar
    function getInitials(name) {
        return name.split(' ').map(n => n[0]).join('').toUpperCase().substring(0, 2);
    }

    // Load users function
    function loadUsers() {
        if ($.fn.DataTable.isDataTable('#userTable')) {
            $('#userTable').DataTable().clear().destroy();
        }
        $('#userTable tbody').empty();

        $.get('{{ route('superadmin.users.list') }}', function(res) {
            usersData = res.data;
            let rows = '';

            $.each(res.data, function(i, user) {
                var isCurrentUser = user.id == currentUserId;
                var initials = getInitials(user.name);

                // Role badge
                var roleBadges = {
                    'superadmin': '<span class="role-badge superadmin"><i class="fas fa-crown mr-1"></i>Super Admin</span>',
                    'admin': '<span class="role-badge admin"><i class="fas fa-user-cog mr-1"></i>Admin</span>',
                    'manager': '<span class="role-badge manager"><i class="fas fa-user-tie mr-1"></i>Manager</span>'
                };
                var roleBadge = roleBadges[user.role] || '<span class="role-badge">' + user.role + '</span>';

                // Status badge
                var statusBadge = user.status === 'active'
                    ? '<span class="status-badge active"><i class="fas fa-check-circle mr-1"></i>Active</span>'
                    : '<span class="status-badge inactive"><i class="fas fa-times-circle mr-1"></i>Inactive</span>';

                // Status toggle button
                var statusBtn = '';
                if (!isCurrentUser) {
                    var isActive = user.status === 'active';
                    var statusClass = isActive ? '' : 'inactive';
                    var statusIcon = isActive ? 'fa-toggle-on' : 'fa-toggle-off';
                    var statusTitle = isActive ? 'Deactivate User' : 'Activate User';
                    statusBtn = `<button class="action-btn toggle-btn ${statusClass} toggleStatusBtn" title="${statusTitle}" data-id="${user.id}"><i class="fas ${statusIcon}"></i></button>`;
                }

                // Delete button
                var deleteDisabled = isCurrentUser ? 'disabled' : '';
                var deleteTitle = isCurrentUser ? 'Cannot delete your own account' : 'Delete User';

                rows += `<tr class="text-center">
                    <td class="font-weight-bold text-muted">${i + 1}</td>
                    <td class="text-left">
                        <div class="user-info">
                            <div class="user-avatar">${initials}</div>
                            <div>
                                <div class="user-name">${user.name}</div>
                            </div>
                        </div>
                    </td>
                    <td class="text-left"><small>${user.email}</small></td>
                    <td>${roleBadge}</td>
                    <td>${statusBadge}</td>
                    <td><small class="text-muted">${user.created_at}</small></td>
                    <td>
                        <button class="action-btn edit-btn editUserBtn" title="Edit User"
                            data-id="${user.id}"
                            data-name="${user.name}"
                            data-email="${user.email}"
                            data-role="${user.role}"
                            data-status="${user.status}">
                            <i class="fas fa-edit"></i>
                        </button>
                        ${statusBtn}
                        <button class="action-btn delete-btn deleteUserBtn" title="${deleteTitle}"
                            data-id="${user.id}"
                            data-name="${user.name}"
                            ${deleteDisabled}>
                            <i class="fas fa-trash-alt"></i>
                        </button>
                    </td>
                </tr>`;
            });

            $('#userTable tbody').html(rows);
            updateSummaryCards();

            // Initialize DataTable with enhanced options
            $('#userTable').DataTable({
                pageLength: 10,
                lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                order: [[0, 'asc']],
                columnDefs: [
                    { orderable: false, targets: [6] },
                    { className: 'align-middle', targets: '_all' }
                ],
                language: {
                    search: '<i class="fas fa-search text-muted mr-1"></i>',
                    searchPlaceholder: 'Search users...',
                    lengthMenu: 'Show _MENU_ entries',
                    info: 'Showing _START_ to _END_ of _TOTAL_ users',
                    infoEmpty: 'No users found',
                    infoFiltered: '(filtered from _MAX_ total)',
                    paginate: {
                        first: '<i class="fas fa-angle-double-left"></i>',
                        last: '<i class="fas fa-angle-double-right"></i>',
                        next: '<i class="fas fa-angle-right"></i>',
                        previous: '<i class="fas fa-angle-left"></i>'
                    },
                    emptyTable: '<div class="text-center py-4"><i class="fas fa-users fa-3x text-muted mb-3"></i><p class="text-muted">No users found</p></div>'
                },
                dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>rtip'
            });
        }).fail(function(err) {
            console.error('Failed to load users:', err);
            showToast('error', 'Failed to load users. Please refresh the page.');
        });
    }

    // Initial load
    loadUsers();

    // Update summary cards
    function updateSummaryCards() {
        var total = usersData.length;
        var active = usersData.filter(u => u.status === 'active').length;
        var inactive = usersData.filter(u => u.status === 'inactive').length;
        var superadmins = usersData.filter(u => u.role === 'superadmin').length;

        $('#totalUsers').text(total);
        $('#activeUsers').text(active);
        $('#inactiveUsers').text(inactive);
        $('#superadminCount').text(superadmins);
    }

    // Toggle password visibility
    $('.toggle-password').on('click', function() {
        var input = $(this).closest('.input-group').find('input');
        var icon = $(this).find('i');
        if (input.attr('type') === 'password') {
            input.attr('type', 'text');
            icon.removeClass('fa-eye').addClass('fa-eye-slash');
        } else {
            input.attr('type', 'password');
            icon.removeClass('fa-eye-slash').addClass('fa-eye');
        }
    });

    // Reset form and show modal for adding
    function openAddModal() {
        $('#userForm')[0].reset();
        $('#user_id').val('');
        $('#formErrors').addClass('d-none');
        $('#modalIcon').removeClass('fa-user-edit').addClass('fa-user-plus');
        $('#userModalLabel').html('<i class="fas fa-user-plus mr-2" id="modalIcon"></i>Add New User');
        $('#pass-req').show();
        $('#pass-hint').text('Required for new users');
        $('#password').attr('required', true);
        $('#status').val('active');
        $('#userModal').modal('show');
    }

    $('#addUserBtn').on('click', openAddModal);
    $('#quickAddUser').on('click', openAddModal);

    // Edit User - populate form
    $('#userTable').on('click', '.editUserBtn', function() {
        $('#userForm')[0].reset();
        $('#formErrors').addClass('d-none');

        $('#user_id').val($(this).data('id'));
        $('#name').val($(this).data('name'));
        $('#email').val($(this).data('email'));
        $('#role').val($(this).data('role'));
        $('#status').val($(this).data('status') || 'active');

        $('#modalIcon').removeClass('fa-user-plus').addClass('fa-user-edit');
        $('#userModalLabel').html('<i class="fas fa-user-edit mr-2" id="modalIcon"></i>Edit User');
        $('#pass-req').hide();
        $('#pass-hint').text('Leave blank to keep current password');
        $('#password').attr('required', false);
        $('#userModal').modal('show');
    });

    // Save User (Add or Update)
    $('#userForm').submit(function(e) {
        e.preventDefault();

        var $btn = $('#saveUserBtn');
        var $spinner = $btn.find('.spinner-border');
        var $text = $btn.find('.btn-text');
        var $icon = $btn.find('.btn-icon');

        $btn.prop('disabled', true);
        $spinner.removeClass('d-none');
        $icon.addClass('d-none');
        $text.text('Saving...');

        var user_id = $('#user_id').val();
        var url = user_id
            ? "{{ url('superadmin/users/update') }}/" + user_id
            : "{{ route('superadmin.users.store') }}";

        $.ajax({
            url: url,
            type: 'POST',
            data: $(this).serialize(),
            success: function(res) {
                $('#userModal').modal('hide');
                loadUsers();
                showToast('success', res.message || 'User saved successfully!');
            },
            error: function(err) {
                var errors = err.responseJSON?.errors || {};
                var message = err.responseJSON?.message || 'An error occurred';

                if (Object.keys(errors).length > 0) {
                    var errorHtml = '';
                    $.each(errors, function(field, messages) {
                        $.each(messages, function(i, msg) {
                            errorHtml += '<li>' + msg + '</li>';
                        });
                    });
                    $('#errorList').html(errorHtml);
                    $('#formErrors').removeClass('d-none');
                } else {
                    showToast('error', message);
                }
            },
            complete: function() {
                $btn.prop('disabled', false);
                $spinner.addClass('d-none');
                $icon.removeClass('d-none');
                $text.text('Save');
            }
        });
    });

    // Toggle Status
    $('#userTable').on('click', '.toggleStatusBtn', function() {
        var userId = $(this).data('id');
        var $btn = $(this);
        $btn.prop('disabled', true);

        $.ajax({
            url: "{{ url('superadmin/users/toggle-status') }}/" + userId,
            type: 'POST',
            data: { '_token': '{{ csrf_token() }}' },
            success: function(res) {
                loadUsers();
                showToast('success', res.message);
            },
            error: function(err) {
                showToast('error', err.responseJSON?.message || 'Failed to update status');
                $btn.prop('disabled', false);
            }
        });
    });

    // Delete User - show confirmation
    var deleteUserId = null;
    $('#userTable').on('click', '.deleteUserBtn', function() {
        if ($(this).prop('disabled')) return;

        deleteUserId = $(this).data('id');
        $('#deleteUserName').text($(this).data('name'));
        $('#deleteUserModal').modal('show');
    });

    // Confirm Delete
    $('#confirmDeleteBtn').on('click', function() {
        if (!deleteUserId) return;

        var $btn = $(this);
        var $spinner = $btn.find('.spinner-border');
        var $text = $btn.find('.btn-text');
        var $icon = $btn.find('.btn-icon');

        $btn.prop('disabled', true);
        $spinner.removeClass('d-none');
        $icon.addClass('d-none');
        $text.text('Deleting...');

        $.ajax({
            url: "{{ url('superadmin/users/delete') }}/" + deleteUserId,
            type: 'DELETE',
            data: { '_token': '{{ csrf_token() }}' },
            success: function(res) {
                $('#deleteUserModal').modal('hide');
                loadUsers();
                showToast('success', res.message || 'User deleted successfully!');
            },
            error: function(err) {
                showToast('error', err.responseJSON?.message || 'Failed to delete user');
            },
            complete: function() {
                $btn.prop('disabled', false);
                $spinner.addClass('d-none');
                $icon.removeClass('d-none');
                $text.text('Delete');
                deleteUserId = null;
            }
        });
    });

    // Toast notification helper
    function showToast(type, message) {
        // Remove any existing toasts
        $('.custom-toast').remove();

        var bgClass = type === 'success' ? 'bg-success' : 'bg-danger';
        var icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
        var title = type === 'success' ? 'Success' : 'Error';

        var toastHtml = `
            <div class="toast custom-toast ${bgClass} text-white" role="alert" aria-live="assertive" aria-atomic="true" data-delay="3500">
                <div class="toast-body">
                    <i class="fas ${icon}"></i>
                    <span class="flex-grow-1">${message}</span>
                    <button type="button" class="close ml-2" data-dismiss="toast" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </div>
        `;

        var $toast = $(toastHtml);
        $('body').append($toast);
        $toast.toast('show');

        $toast.on('hidden.bs.toast', function() {
            $(this).remove();
        });
    }
});
</script>
@endsection
