<?php
require_once '../../core/permissions.php';
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';
require_once '../../core/format.php';
require_once '../../services/analytics/DashboardUserAccessAdminService.php';
require_once '../../services/costs/CostAccess.php';
require_once '../../services/treasury/TreasuryAccess.php';
require_once '../../services/billing/BillingAccess.php';

require_login();
require_permission('admin.users.view');

$page_title = 'Usuarios';
$pdo = db();
$dashboardAccessAdmin = new DashboardUserAccessAdminService($pdo);
$dashboardCatalog = $dashboardAccessAdmin->catalog();
$dashboardRoleDefaults = array();
$costPermissionCatalog = cost_permission_catalog();
$treasuryPermissionCatalog = treasury_permission_catalog();
$billingPermissionCatalog = billing_permission_catalog();
foreach (array('admin','administracion','comercial','operaciones') as $dashboardRole) {
    $dashboardRoleDefaults[$dashboardRole] = $dashboardAccessAdmin->defaultsForRole($dashboardRole);
}
$adminUsersNotice = isset($_SESSION['admin_users_notice']) && is_array($_SESSION['admin_users_notice']) ? $_SESSION['admin_users_notice'] : null;
unset($_SESSION['admin_users_notice']);

$q = isset($_GET['q']) ? trim($_GET['q']) : '';
$role = isset($_GET['role']) ? trim($_GET['role']) : '';
$status = isset($_GET['status']) ? trim($_GET['status']) : '';

$sql = "SELECT * FROM users WHERE 1 = 1";
$params = array();

if ($q !== '') {
    $sql .= " AND (name LIKE ? OR email LIKE ?)";
    $params[] = "%$q%";
    $params[] = "%$q%";
}
if ($role !== '') {
    $sql .= " AND role = ?";
    $params[] = $role;
}
if ($status !== '') {
    $sql .= " AND status = ?";
    $params[] = $status;
}

$sql .= " ORDER BY name ASC, email ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$users = $stmt->fetchAll();

require_once '../../layouts/header.php';
require_once '../../layouts/sidebar.php';
?>

<main class="app-main" id="admin-users-main">
    <style>
    #admin-users-main.app-main { overflow: hidden !important; display: flex !important; flex-direction: column !important; }
    #admin-users-main .content { flex: 1 1 auto; display: flex; flex-direction: column; overflow: hidden; min-height: 0; }
    #admin-users-main .card-table-container { flex: 1 1 auto; display: flex; flex-direction: column; overflow: hidden; min-height: 0; margin-bottom: 0; }
    #admin-users-main .table-container-scroll { flex: 1 1 auto; overflow-y: auto; overflow-x: auto; min-height: 0; -webkit-overflow-scrolling: touch; }
    #admin-users-main .table-container-scroll thead th { position: sticky; top: 0; z-index: 10; background: var(--surface-2); box-shadow: 0 1px 0 var(--border-subtle); }

    #admin-users-main .product-modal-backdrop { position: fixed !important; inset: 0 !important; display: none; align-items: center !important; justify-content: center !important; padding: 24px !important; overflow: hidden !important; background: rgba(0,0,0,0.68) !important; backdrop-filter: blur(5px) !important; z-index: var(--z-modal, 1050) !important; opacity: 0; transition: opacity 0.2s ease !important; }
    #admin-users-main .product-modal-backdrop.show { display: flex !important; opacity: 1 !important; }
    #admin-users-main .product-modal-box { width: min(900px, calc(100vw - 48px)) !important; max-width: calc(100vw - 48px) !important; height: min(760px, calc(100dvh - 72px)) !important; min-height: min(560px, calc(100dvh - 72px)) !important; max-height: calc(100dvh - 72px) !important; display: flex !important; flex-direction: column !important; overflow: hidden !important; background: var(--surface-1) !important; border: 1px solid var(--border-default) !important; border-radius: var(--radius-xl) !important; box-shadow: var(--shadow-lg) !important; transform: translateY(20px); transition: transform 0.2s ease !important; }
    #admin-users-main .product-modal-backdrop.show .product-modal-box { transform: translateY(0); }
    #admin-users-main .product-modal-header { flex: 0 0 auto !important; min-height: 78px !important; padding: 20px 24px !important; display: flex !important; align-items: flex-start !important; justify-content: space-between !important; gap: 14px !important; border-bottom: 1px solid var(--border-subtle) !important; background: var(--surface-1) !important; }
    #admin-users-main .product-modal-body { flex: 1 1 auto !important; min-height: 0 !important; max-height: none !important; padding: 20px 24px !important; overflow-y: auto !important; overflow-x: hidden !important; -webkit-overflow-scrolling: touch !important; overscroll-behavior: contain !important; }
    #admin-users-main .product-modal-footer { flex: 0 0 auto !important; min-height: 76px !important; height: auto !important; padding: 14px 20px !important; display: flex !important; align-items: center !important; justify-content: space-between !important; gap: 12px !important; flex-wrap: nowrap !important; background: var(--surface-0) !important; border-top: 1px solid var(--border-subtle) !important; border-radius: 0 0 var(--radius-xl) var(--radius-xl) !important; overflow: visible !important; }

    #admin-users-main .action-square-btn { width: 42px !important; min-width: 42px !important; max-width: 42px !important; height: 42px !important; min-height: 42px !important; padding: 0 !important; display: inline-flex !important; align-items: center !important; justify-content: center !important; border-radius: var(--radius-lg) !important; flex: 0 0 42px !important; }
    #admin-users-main .modal-footer-actions-right { display: flex !important; align-items: center !important; justify-content: flex-end !important; gap: 12px !important; flex: 1 1 auto !important; min-width: 0 !important; overflow: visible !important; flex-wrap: nowrap !important; }
    #admin-users-main .product-modal-footer .btn { width: auto !important; min-width: 118px !important; height: 48px !important; min-height: 48px !important; padding: 0 18px !important; display: inline-flex !important; align-items: center !important; justify-content: center !important; gap: 8px !important; flex: 0 0 auto !important; white-space: nowrap !important; text-align: center !important; overflow: visible !important; text-overflow: clip !important; border-radius: var(--radius-lg) !important; }
    #admin-users-main .product-modal-footer .btn-primary { min-width: 156px !important; }
    #admin-users-main .product-modal-footer .btn span { display: inline-flex !important; align-items: center !important; justify-content: center !important; max-width: none !important; overflow: visible !important; text-overflow: clip !important; white-space: nowrap !important; }
    #admin-users-main #form-delete-user { flex: 0 0 auto !important; margin-right: auto !important; }
    #admin-users-main #form-delete-user[style*="display: none"] { display: none !important; }
    #admin-users-main .btn-delete-mobile { width: 48px !important; min-width: 48px !important; max-width: 48px !important; height: 48px !important; min-height: 48px !important; padding: 0 !important; flex: 0 0 48px !important; display: inline-flex !important; align-items: center !important; justify-content: center !important; color: var(--color-error) !important; border-color: rgba(255,77,79,0.58) !important; background: rgba(255,77,79,0.06) !important; }
    #admin-users-main .btn-delete-mobile span { display: none !important; }
    #admin-users-main .btn-delete-mobile svg { margin: 0 !important; color: var(--color-error) !important; stroke: var(--color-error) !important; }
    #admin-users-main .user-permissions-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 20px; background: var(--surface-2); padding: 20px; border-radius: var(--radius-md); border: 1px solid var(--border-default); }
    #admin-users-main .dashboard-access-section { grid-column: 1 / -1; margin-top: var(--space-5); }
    #admin-users-main .dashboard-access-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 12px; }
    #admin-users-main .dashboard-access-heading p { margin: 3px 0 0; color: var(--text-secondary); font-size: .8rem; }
    #admin-users-main .dashboard-access-admin-note { display: none; flex: 0 0 auto; padding: 6px 9px; border-radius: 999px; color: var(--color-success); background: color-mix(in srgb, var(--color-success) 12%, transparent); font-size: .72rem; font-weight: 650; }
    #admin-users-main .dashboard-access-admin-note.is-visible { display: inline-flex; }
    #admin-users-main .dashboard-access-scroll { overflow-x: auto; border: 1px solid var(--border-default); border-radius: var(--radius-md); background: var(--surface-2); }
    #admin-users-main .dashboard-access-matrix { min-width: 620px; }
    #admin-users-main .dashboard-access-row { display: grid; grid-template-columns: minmax(250px, 1fr) repeat(3, minmax(92px, 110px)); align-items: center; min-height: 48px; border-bottom: 1px solid var(--border-subtle); }
    #admin-users-main .dashboard-access-row:last-child { border-bottom: 0; }
    #admin-users-main .dashboard-access-row.is-header { min-height: 40px; background: var(--surface-3); color: var(--text-muted); font-size: .7rem; font-weight: 700; text-transform: uppercase; letter-spacing: .04em; }
    #admin-users-main .dashboard-access-cell { padding: 9px 13px; text-align: center; }
    #admin-users-main .dashboard-access-cell:first-child { text-align: left; }
    #admin-users-main .dashboard-access-name { display: flex; align-items: center; gap: 9px; min-width: 0; }
    #admin-users-main .dashboard-access-name i { width: 17px; height: 17px; flex: 0 0 17px; color: var(--text-muted); }
    #admin-users-main .dashboard-access-name strong { display: block; color: var(--text-primary); font-size: .82rem; }
    #admin-users-main .dashboard-access-name small { display: block; color: var(--text-muted); font-family: var(--font-mono, monospace); font-size: .65rem; }
    #admin-users-main .dashboard-access-check { width: 17px; height: 17px; accent-color: var(--color-primary); cursor: pointer; }
    #admin-users-main .dashboard-access-check:disabled { cursor: not-allowed; opacity: .65; }
    #admin-users-main .cost-access-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px; padding:14px; border:1px solid var(--border-default); border-radius:var(--radius-md); background:var(--surface-2); }
    #admin-users-main .cost-access-option { display:flex; gap:10px; align-items:flex-start; padding:10px; border:1px solid var(--border-subtle); border-radius:var(--radius-md); background:var(--surface-1); cursor:pointer; }
    #admin-users-main .cost-access-option input { width:17px; height:17px; margin-top:2px; accent-color:var(--color-primary); }
    #admin-users-main .cost-access-option strong,#admin-users-main .cost-access-option small { display:block; }
    #admin-users-main .cost-access-option small { margin-top:3px; color:var(--text-muted); font-size:.72rem; }
    @media (max-width: 760px) { #admin-users-main .cost-access-grid { grid-template-columns: 1fr; } }
    #admin-users-main .admin-users-notice { flex: 0 0 auto; display: flex; align-items: center; gap: 9px; margin-bottom: 14px; padding: 11px 13px; border: 1px solid var(--border-default); border-radius: var(--radius-md); font-size: .82rem; }
    #admin-users-main .admin-users-notice i { width: 17px; height: 17px; }
    #admin-users-main .admin-users-notice.is-success { color: var(--color-success); background: color-mix(in srgb, var(--color-success) 10%, var(--surface-1)); border-color: color-mix(in srgb, var(--color-success) 28%, var(--border-default)); }
    #admin-users-main .admin-users-notice.is-error { color: var(--color-error); background: color-mix(in srgb, var(--color-error) 10%, var(--surface-1)); border-color: color-mix(in srgb, var(--color-error) 28%, var(--border-default)); }

    /* ==========================================================================
       FILTROS ADMIN USERS
       ========================================================================== */
    #admin-users-main .admin-user-filter-card {
        flex: 0 0 auto;
        margin-bottom: 16px !important;
        border-radius: var(--radius-xl) !important;
    }

    #admin-users-main .admin-user-filter-card .card-body {
        padding: 14px 16px !important;
    }

    #admin-users-main .admin-user-filters {
        display: grid !important;
        grid-template-columns: minmax(280px, 1fr) minmax(150px, 180px) minmax(150px, 180px) auto auto;
        gap: 10px !important;
        align-items: center !important;
        width: 100% !important;
    }

    #admin-users-main .admin-user-filters .form-field {
        min-width: 0 !important;
        margin: 0 !important;
    }

    #admin-users-main .admin-user-filters .input,
    #admin-users-main .admin-user-filters .select,
    #admin-users-main .admin-user-filters .btn {
        height: 44px !important;
        min-height: 44px !important;
    }

    #admin-users-main .admin-user-filters .select {
        min-width: 0 !important;
        width: 100% !important;
        padding-left: 12px !important;
        padding-right: 34px !important;
        text-overflow: ellipsis !important;
        white-space: nowrap !important;
        overflow: hidden !important;
    }

    #admin-users-main .admin-user-filter-submit,
    #admin-users-main .admin-user-filter-clear {
        min-width: 118px !important;
        justify-content: center !important;
        white-space: nowrap !important;
    }

    #admin-users-main .input-with-icon {
        position: relative;
        width: 100%;
        display: flex;
        align-items: center;
    }

    #admin-users-main .input-with-icon svg {
        position: absolute !important;
        left: 14px !important;
        top: 50% !important;
        transform: translateY(-50%) !important;
        width: 18px !important;
        height: 18px !important;
        color: var(--text-muted) !important;
        pointer-events: none !important;
        z-index: 1;
    }

    #admin-users-main .input-with-icon .input {
        width: 100% !important;
        padding-left: 42px !important;
    }

    /* ==========================================================================
       TABLA USUARIOS - ESCRITORIO
       ========================================================================== */
    #admin-users-main .users-table {
        table-layout: fixed !important;
        width: 100% !important;
        min-width: 0 !important;
    }

    #admin-users-main .users-table .col-user {
        width: 25% !important;
    }

    #admin-users-main .users-table .col-email {
        width: 24% !important;
    }

    #admin-users-main .users-table .col-role {
        width: 16% !important;
    }

    #admin-users-main .users-table .col-status {
        width: 10% !important;
    }

    #admin-users-main .users-table .col-last-login {
        width: 16% !important;
    }

    #admin-users-main .users-table .col-action {
        width: 12% !important;
    }

    #admin-users-main .users-table th,
    #admin-users-main .users-table td {
        min-width: 0 !important;
        vertical-align: middle !important;
    }

    #admin-users-main .users-table .col-email,
    #admin-users-main .users-table .col-last-login {
        white-space: nowrap !important;
        overflow: hidden !important;
        text-overflow: ellipsis !important;
    }

    #admin-users-main .users-table .customer-cell {
        min-width: 0 !important;
        max-width: 100% !important;
    }

    #admin-users-main .users-table .customer-cell-text {
        min-width: 0 !important;
        max-width: 100% !important;
        overflow: hidden !important;
    }

    #admin-users-main .users-table .customer-cell-text strong {
        display: block !important;
        max-width: 100% !important;
        overflow: hidden !important;
        text-overflow: ellipsis !important;
        white-space: nowrap !important;
    }

    #admin-users-main .users-table .col-action .btn {
        width: 40px !important;
        min-width: 40px !important;
        max-width: 40px !important;
        height: 40px !important;
        padding: 0 !important;
        display: inline-flex !important;
        align-items: center !important;
        justify-content: center !important;
    }

    @media (max-width: 760px) {
    /* =========================================================
       Mobile layout: pantalla sin scroll vertical global
       Sólo la tabla debe hacer scroll interno
       ========================================================= */
        #admin-users-main.app-main {
            height: 100dvh !important;
            max-height: 100dvh !important;
            overflow: hidden !important;
            display: flex !important;
            flex-direction: column !important;
        }
    
        #admin-users-main .content {
            flex: 1 1 0 !important;
            min-height: 0 !important;
            height: auto !important;
            max-height: none !important;
            display: flex !important;
            flex-direction: column !important;
            overflow: hidden !important;
            padding-bottom: calc(12px + env(safe-area-inset-bottom)) !important;
        }
    
        /* Header compacto */
        #admin-users-main .page-header {
            flex: 0 0 auto !important;
            display: flex !important;
            flex-direction: row !important;
            flex-wrap: nowrap !important;
            justify-content: space-between !important;
            align-items: flex-start !important;
            margin-bottom: 12px !important;
        }
    
        #admin-users-main .page-header-content {
            flex: 1 1 auto !important;
            min-width: 0 !important;
            padding-right: 12px !important;
        }
    
        #admin-users-main .page-header-content h1 {
            font-size: 1.35rem !important;
            line-height: 1.2 !important;
            margin-bottom: 4px !important;
            word-break: break-word !important;
        }
    
        #admin-users-main .page-header-content p {
            display: none !important;
        }
    
        #admin-users-main .actions-cluster {
            flex: 0 0 auto !important;
            display: flex !important;
            gap: 8px !important;
        }
    
        #admin-users-main .mobile-hidden {
            display: none !important;
        }
    
        #admin-users-main .icon-btn-mobile {
            width: 44px !important;
            height: 44px !important;
            min-width: 44px !important;
            max-width: 44px !important;
            padding: 0 !important;
            display: inline-flex !important;
            align-items: center !important;
            justify-content: center !important;
        }
    
        /* =========================================================
           Filtros móviles
           ========================================================= */
        #admin-users-main .admin-user-filter-card {
            flex: 0 0 auto !important;
            margin-bottom: 12px !important;
        }
    
        #admin-users-main .admin-user-filter-card .card-body {
            padding: 12px !important;
        }
    
        #admin-users-main .admin-user-filters {
            display: grid !important;
            grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) !important;
            gap: 10px !important;
            align-items: stretch !important;
        }
    
        #admin-users-main .admin-user-filter-search,
        #admin-users-main .admin-user-filter-submit,
        #admin-users-main .admin-user-filter-clear {
            grid-column: 1 / -1 !important;
        }
    
        #admin-users-main .admin-user-filter-role,
        #admin-users-main .admin-user-filter-status {
            grid-column: auto !important;
            min-width: 0 !important;
        }
    
        #admin-users-main .admin-user-filters .input,
        #admin-users-main .admin-user-filters .select,
        #admin-users-main .admin-user-filters .btn {
            height: 44px !important;
            min-height: 44px !important;
            font-size: 0.92rem !important;
        }
    
        #admin-users-main .admin-user-filters .select {
            min-width: 0 !important;
            width: 100% !important;
            padding-left: 12px !important;
            padding-right: 32px !important;
            text-overflow: ellipsis !important;
            white-space: nowrap !important;
            overflow: hidden !important;
        }
    
        #admin-users-main .admin-user-filter-submit,
        #admin-users-main .admin-user-filter-clear {
            width: 100% !important;
            min-width: 0 !important;
            justify-content: center !important;
        }
    
        #admin-users-main .admin-user-filter-submit {
            margin-top: 2px !important;
        }
    
        #admin-users-main .admin-user-filter-submit svg,
        #admin-users-main .admin-user-filter-clear svg {
            width: 17px !important;
            height: 17px !important;
        }
    
        /* =========================================================
           Tabla: ocupa alto restante sin crecer la página
           ========================================================= */
        #admin-users-main .card-table-container {
            flex: 1 1 0 !important;
            min-height: 0 !important;
            height: auto !important;
            max-height: none !important;
            display: flex !important;
            flex-direction: column !important;
            overflow: hidden !important;
            margin-bottom: 0 !important;
        }
    
        #admin-users-main .table-container-scroll {
            flex: 1 1 0 !important;
            min-height: 0 !important;
            height: auto !important;
            max-height: none !important;
            overflow-y: auto !important;
            overflow-x: hidden !important;
            -webkit-overflow-scrolling: touch !important;
        }
    
        #admin-users-main .table-mobile-compact {
            width: 100% !important;
            min-width: 100% !important;
            height: auto !important;
            table-layout: fixed !important;
        }
    
        #admin-users-main .col-user {
            width: 55% !important;
        }
    
        #admin-users-main .col-role {
            width: 25% !important;
            padding-left: 4px !important;
            padding-right: 4px !important;
        }
    
        #admin-users-main .col-action {
            width: 20% !important;
        }
    
        /* =========================================================
           Modal usuario móvil
           ========================================================= */
        #admin-users-main .product-modal-backdrop {
            padding: 12px !important;
        }
    
        #admin-users-main .product-modal-box {
            width: calc(100vw - 24px) !important;
            max-width: calc(100vw - 24px) !important;
            height: calc(100dvh - 200px) !important;
            min-height: 0 !important;
            max-height: calc(100dvh - 200px) !important;
            border-radius: 18px !important;
        }
    
        #admin-users-main .product-modal-header {
            min-height: 64px !important;
            padding: 14px !important;
            gap: 10px !important;
        }
    
        #admin-users-main .product-modal-header .h3,
        #admin-users-main .product-modal-header h2 {
            font-size: 1.05rem !important;
            line-height: 1.14 !important;
            margin-bottom: 2px !important;
        }
    
        #admin-users-main .product-modal-header .text-sm {
            font-size: 0.78rem !important;
            line-height: 1.15 !important;
        }
    
        #admin-users-main .product-modal-body {
            padding: 14px !important;
        }
    
        #admin-users-main .form-grid-2 {
            grid-template-columns: 1fr !important;
            gap: 12px !important;
        }
    
        #admin-users-main .user-permissions-grid {
            grid-template-columns: 1fr !important;
            gap: 14px !important;
            padding: 14px !important;
        }

        #admin-users-main .dashboard-access-heading { display: grid; gap: 8px; }
        #admin-users-main .dashboard-access-admin-note { justify-self: start; }
        #admin-users-main .dashboard-access-matrix { min-width: 560px; }
        #admin-users-main .dashboard-access-row { grid-template-columns: minmax(220px, 1fr) repeat(3, 108px); }
    
        #admin-users-main .product-modal-footer {
            min-height: 68px !important;
            padding: 10px 12px calc(10px + env(safe-area-inset-bottom)) !important;
            gap: 10px !important;
        }
    
        #admin-users-main .modal-footer-actions-right {
            gap: 10px !important;
            flex: 1 1 auto !important;
        }
    
        #admin-users-main .product-modal-footer .btn {
            height: 44px !important;
            min-height: 44px !important;
            min-width: 98px !important;
            padding: 0 12px !important;
            font-size: 0.92rem !important;
            flex: 0 1 auto !important;
        }
    
        #admin-users-main .product-modal-footer .btn-primary {
            min-width: 124px !important;
        }
    
        #admin-users-main .btn-delete-mobile {
            width: 44px !important;
            min-width: 44px !important;
            max-width: 44px !important;
            height: 44px !important;
            min-height: 44px !important;
            padding: 0 !important;
            flex: 0 0 44px !important;
        }
    }
    </style>

    <?php require_once '../../layouts/topbar.php'; ?>

    <section class="content">
        <?php if ($adminUsersNotice): ?>
            <div class="admin-users-notice is-<?php echo safe_text($adminUsersNotice['type'] === 'success' ? 'success' : 'error'); ?>" role="status">
                <i data-lucide="<?php echo $adminUsersNotice['type'] === 'success' ? 'circle-check' : 'circle-alert'; ?>"></i>
                <span><?php echo safe_text($adminUsersNotice['message'] ?? ''); ?></span>
            </div>
        <?php endif; ?>
        <div class="page-header">
            <div class="page-header-content">
                <span class="label">Administración</span>
                <h1>Usuarios</h1>
                <p class="text-secondary">Gestiona quién tiene acceso al sistema y sus permisos.</p>
            </div>
            <div class="cluster actions-cluster">
                <?php if (user_can('admin.users.edit')): ?>
                <button type="button" class="btn btn-primary icon-btn-mobile" onclick="openUserModal()" title="Nuevo Usuario">
                    <i data-lucide="plus"></i><span class="mobile-hidden">Nuevo Usuario</span>
                </button>
                <?php endif; ?>
            </div>
        </div>

        <section class="card mb-4 admin-user-filter-card">
            <div class="card-body">
                <form method="GET" class="admin-user-filters" style="margin: 0;">
                    <div class="form-field admin-user-filter-search">
                        <div class="input-with-icon">
                            <i data-lucide="search"></i>
                            <input
                                type="text"
                                name="q"
                                class="input"
                                placeholder="Buscar por nombre o email..."
                                value="<?php echo safe_text($q); ?>"
                                autocomplete="off"
                            >
                        </div>
                    </div>

                    <div class="form-field admin-user-filter-role">
                        <select name="role" class="select" onchange="this.form.submit()">
                            <option value="">Todos los roles</option>
                            <option value="admin" <?php echo $role === 'admin' ? 'selected' : ''; ?>>Admin</option>
                            <option value="administracion" <?php echo $role === 'administracion' ? 'selected' : ''; ?>>Administración</option>
                            <option value="comercial" <?php echo $role === 'comercial' ? 'selected' : ''; ?>>Comercial</option>
                            <option value="operaciones" <?php echo $role === 'operaciones' ? 'selected' : ''; ?>>Operaciones</option>
                        </select>
                    </div>

                    <div class="form-field admin-user-filter-status">
                        <select name="status" class="select" onchange="this.form.submit()">
                            <option value="">Todos los estados</option>
                            <option value="active" <?php echo $status === 'active' ? 'selected' : ''; ?>>Activo</option>
                            <option value="inactive" <?php echo $status === 'inactive' ? 'selected' : ''; ?>>Inactivo</option>
                        </select>
                    </div>

                    <button type="submit" class="btn btn-primary admin-user-filter-submit">
                        <i data-lucide="search"></i>
                        <span>Buscar</span>
                    </button>

                    <?php if ($q !== '' || $role !== '' || $status !== ''): ?>
                        <a href="/modules/admin/users.php" class="btn btn-outline admin-user-filter-clear">
                            <i data-lucide="x"></i>
                            <span>Limpiar</span>
                        </a>
                    <?php endif; ?>
                </form>
            </div>
        </section>

        <section class="card card-table-container">
            <div class="table-wrap table-container-scroll">
                <table class="table table-mobile-compact users-table">
                    <thead>
                        <tr>
                            <th class="col-user">Usuario</th>
                            <th class="col-email mobile-hidden">Email</th>
                            <th class="col-role">Rol</th>
                            <th class="col-status mobile-hidden">Estado</th>
                            <th class="col-last-login mobile-hidden">Último acceso</th>
                            <th class="col-action text-left">Acción</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($users as $user): ?>
                            <?php $initial = mb_substr($user['name'] ?: $user['email'], 0, 1, 'UTF-8'); ?>
                            <tr>
                                <td>
                                    <div class="customer-cell">
                                        <span class="customer-avatar-mini"><?php echo safe_text(strtoupper($initial)); ?></span>
                                        <span class="customer-cell-text">
                                            <strong><?php echo safe_text($user['name'] ?: 'Pendiente'); ?></strong>
                                            <small class="mobile-only"><?php echo safe_text($user['email']); ?></small>
                                        </span>
                                    </div>
                                </td>
                                <td class="col-email mobile-hidden"><?php echo safe_text($user['email']); ?></td>
                                <td class="col-role"><span class="badge"><?php echo safe_text(role_label($user['role'])); ?></span></td>
                                <td class="col-status mobile-hidden">
                                    <span class="badge <?php echo $user['status'] === 'active' ? 'badge-success' : 'badge-error'; ?>">
                                        <?php echo $user['status'] === 'active' ? 'Activo' : 'Inactivo'; ?>
                                    </span>
                                </td>
                                <td class="col-last-login mobile-hidden text-muted text-sm"><?php echo $user['last_login'] ?: '—'; ?></td>
                                <td class="col-action text-left">
                                    <?php if (user_can('admin.users.edit')): ?>
                                        <button class="btn btn-sm btn-outline" onclick="openUserModal(<?php echo $user['id']; ?>)">
                                            <i data-lucide="edit-3"></i>
                                        </button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </section>
    </section>

    <div id="userModal" class="product-modal-backdrop">
        <div class="product-modal-box">
            <div class="product-modal-header">
                <div>
                    <h2 id="modal_title" class="h3">Nuevo Usuario</h2>
                    <span id="modal_subtitle" class="text-secondary text-sm">Autoriza un email para que ingrese al sistema</span>
                </div>
                <button type="button" class="btn btn-outline action-square-btn" onclick="closeUserModal()" title="Cerrar"><i data-lucide="x"></i></button>
            </div>

            <div class="product-modal-body">
                <form id="userForm" action="/modules/admin/user_store.php" method="POST" data-no-spa="true" style="margin:0;">
                    <input type="hidden" name="id" id="modal_user_id">
                    <input type="hidden" name="_csrf_token" value="<?php echo safe_text(csrf_token()); ?>">
                    <input type="hidden" name="dashboard_access_present" value="1">
                    <div class="form-grid">
                        <div class="form-field is-required">
                            <label class="label">Email de Acceso</label>
                            <input class="input" type="email" name="email" id="modal_email" placeholder="usuario@correo.com" required>
                        </div>
                        
                        <div class="form-field">
                            <label class="label">Nombre (Opcional)</label>
                            <input class="input" type="text" name="name" id="modal_name" placeholder="Nombre completo">
                        </div>

                        <div class="form-field">
                            <label class="label">Contraseña de acceso</label>
                            <input class="input" type="text" name="password" id="modal_password" placeholder="Escribe una contraseña (déjalo en blanco si usará Google)">
                        </div>
                        
                        <div class="form-grid-2 grid gap-4" style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                            <div class="form-field is-required">
                                <label class="label">Rol en el Sistema</label>
                                <select class="select" name="role" id="modal_role" required>
                                    <option value="comercial">Comercial</option>
                                    <option value="administracion">Administración</option>
                                    <option value="operaciones">Operaciones</option>
                                    <option value="admin">Admin (Total)</option>
                                </select>
                            </div>
                            <div class="form-field is-required">
                                <label class="label">Estado</label>
                                <select class="select" name="status" id="modal_status" required>
                                    <option value="active">Activo</option>
                                    <option value="inactive">Inactivo</option>
                                </select>
                            </div>
                        </div>

                        <div style="grid-column: 1 / -1; margin-top: var(--space-4);">
                            <label class="label">Permisos de Acceso a Módulos</label>
                            <span class="text-sm text-secondary block mb-3">Selecciona a qué partes del sistema tendrá acceso este usuario. (Los Administradores tienen acceso total por defecto).</span>
                            
                            <div class="user-permissions-grid">
                                <?php 
                                $all_modules = get_system_modules(true);
                                $grouped_modules = [];
                                foreach ($all_modules as $key => $mod) {
                                    $grouped_modules[$mod['section']][$key] = $mod;
                                }
                                
                                foreach ($grouped_modules as $section_name => $mods): 
                                ?>
                                    <div>
                                        <strong style="display: block; margin-bottom: 12px; font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px;">
                                            <?php echo safe_text($section_name); ?>
                                        </strong>
                                        
                                        <?php foreach ($mods as $key => $mod): ?>
                                            <label style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px; cursor: pointer;">
                                                <input type="checkbox" name="permissions[]" value="module.<?php echo $key; ?>" class="perm-checkbox" style="width: 16px; height: 16px;">
                                                <span style="font-size: 0.9rem;"><?php echo safe_text($mod['title']); ?></span>
                                            </label>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <section class="dashboard-access-section" aria-labelledby="dashboardAccessTitle">
                            <div class="dashboard-access-heading">
                                <div>
                                    <label class="label" id="dashboardAccessTitle">Permisos de dashboards</label>
                                    <p>Define qué dashboards puede ver y en cuáles puede configurar metas o exportar información.</p>
                                </div>
                                <span class="dashboard-access-admin-note" id="dashboardAccessAdminNote">Acceso total por rol Admin</span>
                            </div>

                            <div class="dashboard-access-scroll">
                                <div class="dashboard-access-matrix" role="group" aria-label="Matriz de permisos por dashboard">
                                    <div class="dashboard-access-row is-header" aria-hidden="true">
                                        <div class="dashboard-access-cell">Dashboard</div>
                                        <div class="dashboard-access-cell">Ver</div>
                                        <div class="dashboard-access-cell">Configurar</div>
                                        <div class="dashboard-access-cell">Exportar</div>
                                    </div>
                                    <?php foreach ($dashboardCatalog as $dashboardKey => $dashboardItem): ?>
                                        <div class="dashboard-access-row" data-dashboard-row="<?php echo safe_text($dashboardKey); ?>">
                                            <div class="dashboard-access-cell">
                                                <div class="dashboard-access-name">
                                                    <i data-lucide="<?php echo safe_text($dashboardItem['icon']); ?>"></i>
                                                    <span><strong><?php echo safe_text($dashboardItem['label']); ?></strong><small><?php echo safe_text($dashboardItem['id']); ?></small></span>
                                                </div>
                                            </div>
                                            <div class="dashboard-access-cell">
                                                <input class="dashboard-access-check" type="checkbox" name="dashboard_access[<?php echo safe_text($dashboardKey); ?>][view]" value="1" data-dashboard-key="<?php echo safe_text($dashboardKey); ?>" data-dashboard-permission="view" aria-label="Ver dashboard <?php echo safe_text($dashboardItem['label']); ?>">
                                            </div>
                                            <div class="dashboard-access-cell">
                                                <input class="dashboard-access-check" type="checkbox" name="dashboard_access[<?php echo safe_text($dashboardKey); ?>][configure]" value="1" data-dashboard-key="<?php echo safe_text($dashboardKey); ?>" data-dashboard-permission="configure" aria-label="Configurar dashboard <?php echo safe_text($dashboardItem['label']); ?>">
                                            </div>
                                            <div class="dashboard-access-cell">
                                                <input class="dashboard-access-check" type="checkbox" name="dashboard_access[<?php echo safe_text($dashboardKey); ?>][export]" value="1" data-dashboard-key="<?php echo safe_text($dashboardKey); ?>" data-dashboard-permission="export" aria-label="Exportar dashboard <?php echo safe_text($dashboardItem['label']); ?>">
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </section>

                        <section class="dashboard-access-section" aria-labelledby="costAccessTitle">
                            <div class="dashboard-access-heading">
                                <div>
                                    <label class="label" id="costAccessTitle">Permisos de costos</label>
                                    <p>Separa la gestión general, remuneraciones y cierre mensual. El rol Admin mantiene acceso total.</p>
                                </div>
                            </div>
                            <div class="cost-access-grid">
                                <?php foreach ($costPermissionCatalog as $costPermissionKey => $costPermission): ?>
                                    <label class="cost-access-option">
                                        <input type="checkbox" name="permissions[]" value="<?php echo safe_text($costPermissionKey); ?>" class="perm-checkbox cost-permission-check">
                                        <span><strong><?php echo safe_text($costPermission['label']); ?></strong><small><?php echo safe_text($costPermission['description']); ?></small></span>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </section>

                        <section class="dashboard-access-section" aria-labelledby="treasuryAccessTitle">
                            <div class="dashboard-access-heading">
                                <div>
                                    <label class="label" id="treasuryAccessTitle">Permisos de tesorería</label>
                                    <p>Separa consulta, registro, conciliación bancaria y gestión de escenarios. El rol Admin mantiene acceso total.</p>
                                </div>
                            </div>
                            <div class="cost-access-grid">
                                <?php foreach ($treasuryPermissionCatalog as $treasuryPermissionKey => $treasuryPermission): ?>
                                    <label class="cost-access-option">
                                        <input type="checkbox" name="permissions[]" value="<?php echo safe_text($treasuryPermissionKey); ?>" class="perm-checkbox treasury-permission-check">
                                        <span><strong><?php echo safe_text($treasuryPermission['label']); ?></strong><small><?php echo safe_text($treasuryPermission['description']); ?></small></span>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </section>

                        <section class="dashboard-access-section" aria-labelledby="billingAccessTitle">
                            <div class="dashboard-access-heading">
                                <div>
                                    <label class="label" id="billingAccessTitle">Permisos de facturación</label>
                                    <p>La emisión real se asigna por usuario. Los clientes quedan habilitados por sus datos tributarios, sin una lista privada adicional.</p>
                                </div>
                            </div>
                            <div class="cost-access-grid">
                                <?php foreach ($billingPermissionCatalog as $billingPermissionKey => $billingPermission): ?>
                                    <label class="cost-access-option">
                                        <input type="checkbox" name="permissions[]" value="<?php echo safe_text($billingPermissionKey); ?>" class="perm-checkbox billing-permission-check">
                                        <span><strong><?php echo safe_text($billingPermission['label']); ?></strong><small><?php echo safe_text($billingPermission['description']); ?></small></span>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </section>
                    </div>
                </form>
            </div>

            <div class="product-modal-footer" style="justify-content: space-between; align-items: center;">
                <form id="form-delete-user" action="/modules/admin/user_delete.php" method="POST" data-no-spa="true" style="margin:0; display: none;">
                    <input type="hidden" name="id" id="delete_user_id" value="">
                    <input type="hidden" name="_csrf_token" value="<?php echo safe_text(csrf_token()); ?>">
                    <button type="submit" class="btn btn-outline btn-delete-mobile" style="color: var(--color-error); border-color: var(--color-error);" title="Eliminar Usuario" onclick="return confirm('¿Estás seguro de eliminar a este usuario de manera permanente?');">
                        <i data-lucide="trash-2"></i><span class="mobile-hidden">Eliminar</span>
                    </button>
                </form>

                <div class="modal-footer-actions-right">
                    <button type="button" class="btn btn-outline" onclick="closeUserModal()">Cancelar</button>
                    <button type="submit" form="userForm" class="btn btn-primary"><i data-lucide="save"></i><span id="modal_btn_text">Guardar Usuario</span></button>
                </div>
            </div>
        </div>
    </div>

    <script>
    (function () {
        function getUserModal() { return document.getElementById('userModal'); }
        function getUserForm() { return document.getElementById('userForm'); }
        function setValue(id, value) { var el = document.getElementById(id); if (el) el.value = value == null ? '' : value; }
        function setText(id, value) { var el = document.getElementById(id); if (el) el.innerText = value == null ? '' : value; }
        var dashboardRoleDefaults = <?php echo json_encode($dashboardRoleDefaults, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;

        function dashboardAccessInputs() {
            return Array.prototype.slice.call(document.querySelectorAll('#userModal .dashboard-access-check'));
        }

        function setDashboardAccessMatrix(matrix, role) {
            matrix = matrix || {};
            dashboardAccessInputs().forEach(function (checkbox) {
                var key = checkbox.getAttribute('data-dashboard-key');
                var permission = checkbox.getAttribute('data-dashboard-permission');
                checkbox.checked = !!(matrix[key] && matrix[key][permission]);
                checkbox.disabled = false;
            });
            applyDashboardRolePolicy(role);
        }

        function applyDashboardRoleDefaults(role) {
            setDashboardAccessMatrix(dashboardRoleDefaults[role] || {}, role);
        }

        function applyDashboardRolePolicy(role) {
            var isAdmin = role === 'admin';
            var note = document.getElementById('dashboardAccessAdminNote');
            if (note) note.classList.toggle('is-visible', isAdmin);
            dashboardAccessInputs().forEach(function (checkbox) {
                if (isAdmin) checkbox.checked = true;
                checkbox.disabled = isAdmin;
            });
        }

        function enforceDashboardPermissionHierarchy(checkbox) {
            var key = checkbox.getAttribute('data-dashboard-key');
            var permission = checkbox.getAttribute('data-dashboard-permission');
            var row = document.querySelector('#userModal [data-dashboard-row="' + key + '"]');
            if (!row) return;
            var view = row.querySelector('[data-dashboard-permission="view"]');
            var configure = row.querySelector('[data-dashboard-permission="configure"]');
            var exportPermission = row.querySelector('[data-dashboard-permission="export"]');
            if ((permission === 'configure' || permission === 'export') && checkbox.checked && view) view.checked = true;
            if (permission === 'view' && !checkbox.checked) {
                if (configure) configure.checked = false;
                if (exportPermission) exportPermission.checked = false;
            }
        }

        window.openUserModal = function (id) {
            var userModal = getUserModal();
            var uForm = getUserForm();
            if (!userModal || !uForm) return;

            uForm.reset();
            setValue('modal_user_id', id || '');
            var email = document.getElementById('modal_email');
            if (email) email.disabled = false;

            document.querySelectorAll('#userModal .perm-checkbox').forEach(function (cb) { cb.checked = false; });
            applyDashboardRoleDefaults('comercial');

            var isMobile = window.innerWidth <= 760;
            var deleteForm = document.getElementById('form-delete-user');
            var deleteInput = document.getElementById('delete_user_id');

            if (id) {
                setText('modal_title', 'Editar Usuario');
                setText('modal_subtitle', 'Modifica los permisos de acceso');
                uForm.action = '/modules/admin/user_update.php';
                setText('modal_btn_text', isMobile ? 'Actualizar' : 'Actualizar Usuario');
                if (deleteForm) deleteForm.style.display = 'block';
                if (deleteInput) deleteInput.value = id;

                fetch('/modules/admin/user_get.php?id=' + encodeURIComponent(id), { credentials: 'same-origin' })
                    .then(function (res) { return res.json().then(function (data) { if (!res.ok || data.success === false) throw new Error(data.message || 'No fue posible cargar el usuario.'); return data; }); })
                    .then(function (data) {
                        setValue('modal_email', data.email || '');
                        var emailInput = document.getElementById('modal_email');
                        if (emailInput) emailInput.disabled = true;
                        setValue('modal_name', data.name || '');
                        setValue('modal_role', data.role || 'comercial');
                        setValue('modal_status', data.status || 'active');
                        setDashboardAccessMatrix(data.dashboard_access || dashboardRoleDefaults[data.role] || {}, data.role || 'comercial');

                        if (data.module_permissions) {
                            var perms = [];
                            try { perms = JSON.parse(data.module_permissions) || []; } catch (err) { perms = []; }
                            perms.forEach(function (permissionValue) {
                                document.querySelectorAll('#userModal input[name="permissions[]"]').forEach(function (checkbox) {
                                    if (checkbox.value === permissionValue) checkbox.checked = true;
                                });
                            });
                        }
                    })
                    .catch(function (error) {
                        alert(error.message || 'No fue posible cargar el usuario.');
                    });
            } else {
                setText('modal_title', 'Nuevo Usuario');
                setText('modal_subtitle', 'Autoriza un email para que ingrese al sistema');
                uForm.action = '/modules/admin/user_store.php';
                setText('modal_btn_text', isMobile ? 'Guardar' : 'Guardar Usuario');
                if (deleteForm) deleteForm.style.display = 'none';
                if (deleteInput) deleteInput.value = '';
                applyDashboardRoleDefaults('comercial');
            }

            userModal.style.display = 'flex';
            setTimeout(function () { userModal.classList.add('show'); }, 10);
        };

        window.closeUserModal = function () {
            var userModal = getUserModal();
            if (!userModal) return;
            userModal.classList.remove('show');
            setTimeout(function () { userModal.style.display = 'none'; }, 200);
        };

        if (!window.__ICY_USERS_MODAL_CLICK_BOUND) {
            document.addEventListener('click', function (e) {
                var userModal = getUserModal();
                if (userModal && e.target === userModal) window.closeUserModal();
            });
            window.__ICY_USERS_MODAL_CLICK_BOUND = true;
        }

        var roleSelect = document.getElementById('modal_role');
        if (roleSelect) {
            roleSelect.addEventListener('change', function () { applyDashboardRoleDefaults(roleSelect.value); });
        }
        dashboardAccessInputs().forEach(function (checkbox) {
            checkbox.addEventListener('change', function () { enforceDashboardPermissionHierarchy(checkbox); });
        });
    })();
    </script>
</main>

<?php require_once '../../layouts/footer.php'; ?>
