

<?php $__env->startSection('title', 'Settings'); ?>

<?php $__env->startSection('content'); ?>
<div class="page-header">
    <h1>Settings</h1>
</div>

<div class="tabs" style="margin-bottom: 1.5rem; border-bottom: 2px solid var(--border-color); display: flex; gap: 2rem;">
    <button class="tab-link active" onclick="openTab(event, 'general')" style="background: none; border: none; padding: 0.5rem 0; color: var(--text-primary); font-weight: 600; cursor: pointer; border-bottom: 2px solid var(--primary);">General</button>
    <button class="tab-link" onclick="openTab(event, 'roles')" style="background: none; border: none; padding: 0.5rem 0; color: var(--text-muted); cursor: pointer;">Roles & Permissions</button>
    <button class="tab-link" onclick="openTab(event, 'audit')" style="background: none; border: none; padding: 0.5rem 0; color: var(--text-muted); cursor: pointer;">Audit Logs</button>
</div>

<!-- General Settings -->
<div id="general" class="tab-content" style="display: <?php echo e(request('tab') == 'general' || !request('tab') ? 'block' : 'none'); ?>;">
    <div class="card">
        <h3>General Application Settings</h3>
        <p class="text-muted">Configure core system parameters.</p>
        
        <form action="<?php echo e(route('settings.update')); ?>" method="POST">
            <?php echo csrf_field(); ?>
            
            <div class="form-group">
                <label>Organization Name</label>
                <?php if (\Illuminate\Support\Facades\Blade::check('role', 'Super Admin')): ?>
                    <select name="organization_name" class="form-control">
                        <?php $__currentLoopData = $organizations; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $org): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($org->name); ?>" <?php echo e(($settings['organization_name'] ?? 'ATAPE Tanzania') == $org->name ? 'selected' : ''); ?>>
                                <?php echo e($org->name); ?>

                            </option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                    <small class="text-muted">Select the organization context for this instance.</small>
                <?php else: ?>
                    <input type="text" class="form-control" value="<?php echo e($settings['organization_name'] ?? 'ATAPE Tanzania'); ?>" readonly style="background-color: var(--bg-secondary);">
                    <input type="hidden" name="organization_name" value="<?php echo e($settings['organization_name'] ?? 'ATAPE Tanzania'); ?>">
                <?php endif; ?>
            </div>

            <div class="form-row">
                 <div class="form-group">
                    <label>Fiscal Year Start</label>
                    <select name="fiscal_year_start" class="form-control">
                        <?php $__currentLoopData = ['January', 'July', 'October']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $month): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($month); ?>" <?php echo e(($settings['fiscal_year_start'] ?? 'January') == $month ? 'selected' : ''); ?>><?php echo e($month); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Currency Symbol</label>
                    <input type="text" name="currency_symbol" class="form-control" value="<?php echo e($settings['currency_symbol'] ?? 'TZS'); ?>">
                </div>
            </div>

            <div class="form-actions">
                <button type="submit" class="btn btn-primary">Save Settings</button>
            </div>
        </form>
    </div>
</div>

<!-- Roles & Permissions -->
<div id="roles" class="tab-content" style="display: <?php echo e(request('tab') == 'roles' ? 'block' : 'none'); ?>;">
    <div class="card">
        <div class="card-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
            <div>
                <h3>User Roles</h3>
                <p class="text-muted">Manage access levels and permissions.</p>
            </div>
            <a href="<?php echo e(route('roles.create')); ?>" class="btn btn-primary">+ Add New Role</a>
        </div>
        
        <table class="table" style="width: 100%; border-collapse: separate; border-spacing: 0 0.5rem;">
            <thead>
                <tr>
                    <th style="border:none; padding-left: 1rem;">Role Details</th>
                    <th style="border:none;">Access Scope</th>
                    <th style="border:none;">Users</th>
                    <th style="border:none; text-align: right; padding-right: 1rem;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php $__currentLoopData = \Spatie\Permission\Models\Role::all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $role): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <tr style="background: var(--bg-tertiary); box-shadow: 0 2px 4px rgba(0,0,0,0.05); border-radius: 8px;">
                    <td style="padding: 1.5rem 1rem; border-radius: 8px 0 0 8px;">
                        <span style="display: block; font-weight: 600; font-size: 1.1rem; color: var(--text-primary); margin-bottom: 0.25rem;">
                            <?php echo e($role->name); ?>

                        </span>
                        <span class="text-muted" style="font-size: 0.85rem;">
                            ID: <?php echo e($role->id); ?>

                        </span>
                    </td>
                    <td style="padding: 1rem;">
                        <?php if($role->name === 'Super Admin'): ?>
                            <span class="badge badge-success">Full System Access</span>
                        <?php else: ?>
                            <div style="display: flex; flex-wrap: wrap; gap: 0.5rem;">
                                <?php
                                    $groups = $role->permissions->groupBy(function($item) {
                                        return explode('.', $item->name)[0];
                                    })->keys();
                                ?>
                                
                                <?php if($groups->count() > 0): ?>
                                    <?php $__currentLoopData = $groups->take(4); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $group): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <span class="badge badge-secondary" style="text-transform: capitalize;"><?php echo e($group); ?></span>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    <?php if($groups->count() > 4): ?>
                                        <span class="text-muted" style="font-size: 0.85rem; align-self: center;">+<?php echo e($groups->count() - 4); ?> more</span>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="text-muted">No specific permissions</span>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </td>
                    <td style="padding: 1rem;">
                        <div style="display: flex; align-items: center; gap: 0.5rem;">
                            <span style="font-size: 1.2rem;">👥</span>
                            <span style="font-weight: 600;"><?php echo e($role->users()->count()); ?></span>
                        </div>
                    </td>
                    <td style="text-align: right; padding-right: 1rem; border-radius: 0 8px 8px 0;">
                        <a href="<?php echo e(route('roles.edit', $role)); ?>" class="btn btn-secondary">
                            Manage Permissions
                        </a>
                    </td>
                </tr>
                <tr style="height: 0.5rem;"></tr> <!-- Spacer -->
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Audit Logs -->
<div id="audit" class="tab-content" style="display: <?php echo e(request('tab') == 'audit' ? 'block' : 'none'); ?>;">
     <div class="card">
        <h3>System Audit Logs</h3>
        <p class="text-muted" style="margin-bottom: 1rem;">Track all system activities and data changes.</p>
        
        <table class="data-table">
            <thead>
                <tr>
                    <th>Date & Time</th>
                    <th>User</th>
                    <th>Action</th>
                    <th>Module / Record</th>
                    <th>Details</th>
                </tr>
            </thead>
            <tbody>
                <?php $__empty_1 = true; $__currentLoopData = $auditLogs; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $log): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                <tr>
                    <td>
                        <div style="font-weight: 500;"><?php echo e($log->created_at->format('M d, Y')); ?></div>
                        <div class="text-muted" style="font-size: 0.8rem;"><?php echo e($log->created_at->format('H:i:s')); ?></div>
                    </td>
                    <td>
                        <div style="display: flex; align-items: center; gap: 0.5rem;">
                            <div class="avatar-circle-sm" style="width: 24px; height: 24px; bg-color: var(--primary); border-radius: 50%;"></div>
                            <?php echo e($log->user->full_name ?? 'System'); ?>

                        </div>
                        <div class="text-muted" style="font-size: 0.75rem;">IP: <?php echo e($log->ip_address); ?></div>
                    </td>
                    <td>
                        <?php
                            $badgeClass = match($log->action) {
                                'Create' => 'badge-success',
                                'Update' => 'badge-info',
                                'Delete' => 'badge-danger',
                                default => 'badge-secondary'
                            };
                        ?>
                        <span class="badge <?php echo e($badgeClass); ?>"><?php echo e($log->action); ?></span>
                    </td>
                    <td>
                        <span style="font-family: monospace;"><?php echo e($log->table_name); ?> #<?php echo e($log->record_id); ?></span>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-secondary" onclick='viewAuditDetails(<?php echo json_encode($log, 15, 512) ?>)'>
                            View Changes 👁️
                        </button>
                    </td>
                </tr>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                <tr>
                    <td colspan="5" class="empty-state">No audit logs found.</td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
        <div class="pagination-wrapper">
            <?php echo e($auditLogs->appends(['tab' => 'audit'])->links()); ?>

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

<script>
function viewAuditDetails(log) {
    let content = `
        <div class="text-left">
            <div class="d-flex justify-content-between align-items-center mb-4 p-3 rounded" style="background: var(--bg-secondary);">
                <div>
                    <div class="text-muted small text-uppercase font-weight-bold mb-1">Performed By</div>
                    <div class="d-flex align-items-center">
                        <div class="avatar-circle-sm mr-2" style="width:24px;height:24px;background:var(--primary);"></div>
                        <span class="font-weight-bold">${log.user ? log.user.first_name + ' ' + log.user.last_name : 'System'}</span>
                    </div>
                </div>
                <div class="text-right">
                    <div class="text-muted small text-uppercase font-weight-bold mb-1">Timestamp</div>
                    <div class="font-family-monospace">${new Date(log.created_at).toLocaleString()}</div>
                </div>
            </div>

            <div class="mb-4 text-center">
                 <span class="badge ${log.action === 'Delete' ? 'badge-danger' : (log.action === 'Create' ? 'badge-success' : 'badge-info')} px-3 py-2" style="font-size: 0.9rem;">
                    ${log.action} Action
                 </span>
                 <div class="mt-2 text-muted small">
                    Target: <span class="text-white font-weight-bold">${log.table_name} #${log.record_id}</span>
                 </div>
            </div>
    `;

    if (log.action === 'Update' && log.old_values && log.new_values) {
        content += `
            <div class="row no-gutters border rounded overflow-hidden" style="border-color: var(--border-color);">
                <div class="col-6 bg-dark-subtle border-right" style="border-color: var(--border-color);">
                    <div class="p-2 text-center text-muted small text-uppercase border-bottom" style="background: rgba(255, 255, 255, 0.05); border-color: var(--border-color);">Previous State</div>
                    <div class="p-3">
        `;
        
        // Loop for Old Values (Left Column)
        let hasChanges = false;
        for (const [key, newValue] of Object.entries(log.new_values)) {
            const oldValue = log.old_values[key] !== undefined ? log.old_values[key] : '-';
            if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) {
                hasChanges = true;
                content += `
                    <div class="mb-3">
                         <div class="text-muted x-small text-uppercase mb-1">${key.replace(/_/g, ' ')}</div>
                         <div class="p-2 rounded border border-danger-subtle text-danger bg-danger-soft font-family-monospace small">
                            ${String(oldValue)}
                         </div>
                    </div>
                `;
            }
        }
        if(!hasChanges) content += `<div class="text-muted text-center py-2">No changes</div>`;
        
        content += `
                    </div>
                </div>
                <div class="col-6">
                    <div class="p-2 text-center text-muted small text-uppercase border-bottom" style="background: rgba(255, 255, 255, 0.05); border-color: var(--border-color);">New State</div>
                    <div class="p-3">
        `;

        // Loop for New Values (Right Column)
        for (const [key, newValue] of Object.entries(log.new_values)) {
            const oldValue = log.old_values[key] !== undefined ? log.old_values[key] : '-';
            if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) {
                content += `
                    <div class="mb-3">
                         <div class="text-muted x-small text-uppercase mb-1">${key.replace(/_/g, ' ')}</div>
                         <div class="p-2 rounded border border-success-subtle text-success bg-success-soft font-family-monospace small">
                            ${String(newValue)}
                         </div>
                    </div>
                `;
            }
        }
        if(!hasChanges) content += `<div class="text-muted text-center py-2">No changes</div>`;

        content += `
                    </div>
                </div>
            </div>
        `;
    } else if ((log.action === 'Create' && log.new_values) || (log.action === 'Delete' && log.old_values)) {
        const data = log.action === 'Create' ? log.new_values : log.old_values;
        const colorClass = log.action === 'Create' ? 'success' : 'danger';
        
        content += `
            <div class="border rounded p-0 overflow-hidden" style="border-color: var(--border-color);">
                <div class="p-2 text-center text-${colorClass} bg-${colorClass}-soft small text-uppercase font-weight-bold border-bottom" style="border-color: var(--border-color);">
                    ${log.action === 'Create' ? 'Record Attributes' : 'Archived Data'}
                </div>
                <div class="p-3" style="background: var(--bg-tertiary); max-height: 400px; overflow-y: auto;">
                    <div class="d-flex flex-wrap">
        `;
        
        for (const [key, value] of Object.entries(data)) {
            // Skip uninteresting fields
            if(['updated_at', 'deleted_at'].includes(key)) continue;
            
            content += `
                <div class="w-50 mb-3 pr-2">
                    <div class="text-muted x-small text-uppercase mb-1">${key.replace(/_/g, ' ')}</div>
                    <div class="font-family-monospace small text-white">${value !== null ? value : '<span class="text-muted font-italic">null</span>'}</div>
                </div>
            `;
        }
        
        content += `
                    </div>
                </div>
            </div>
        `;
    } else {
        content += `<div class="text-center py-5 text-muted bg-light rounded">No detailed changes available for this log entry.</div>`;
    }

    content += `</div>`;
    
    // Add custom styles for this modal if not present
    if (!document.getElementById('audit-modal-styles')) {
        const style = document.createElement('style');
        style.id = 'audit-modal-styles';
        style.innerHTML = `
            .bg-danger-soft { background: rgba(229, 62, 62, 0.1) !important; }
            .bg-success-soft { background: rgba(72, 187, 120, 0.1) !important; }
            .bg-dark-subtle { background: rgba(0, 0, 0, 0.2); }
            .border-danger-subtle { border-color: rgba(229, 62, 62, 0.3) !important; }
            .border-success-subtle { border-color: rgba(72, 187, 120, 0.3) !important; }
            .x-small { font-size: 0.75rem; letter-spacing: 0.5px; }
        `;
        document.head.appendChild(style);
    }

    Swal.fire({
        html: content, // No title in SweetAlert, customized in HTML
        width: '800px',
        showCloseButton: true,
        showConfirmButton: false,
        background: '#1a1f2c',
        color: '#ffffff',
        customClass: {
            popup: 'audit-modal-popup',
            content: 'p-0 text-left'
        },
        backdrop: `rgba(0,0,0,0.7) left top no-repeat`
    });
}

function openTab(evt, tabName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tab-content");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tab-link");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
        tablinks[i].style.color = "var(--text-muted)";
        tablinks[i].style.borderBottom = "none";
    }
    document.getElementById(tabName).style.display = "block";
    
    // Update active tab visual
    const activeBtn = document.querySelector(`button[onclick="openTab(event, '${tabName}')"]`);
    if(activeBtn) {
        activeBtn.className += " active";
        activeBtn.style.color = "var(--text-primary)";
        activeBtn.style.borderBottom = "2px solid var(--primary)";
    }
    
    // Update URL without reload
    const url = new URL(window.location);
    url.searchParams.set('tab', tabName);
    window.history.pushState({}, '', url);
}

// Set active tab on load based on URL or default
document.addEventListener('DOMContentLoaded', function() {
    const urlParams = new URLSearchParams(window.location.search);
    const tab = urlParams.get('tab') || 'general';
    const activeBtn = document.querySelector(`button[onclick="openTab(event, '${tab}')"]`);
    if(activeBtn) {
        openTab({currentTarget: activeBtn}, tab);
    }
});
</script>

<script>
function openTab(evt, tabName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tab-content");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tab-link");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
        tablinks[i].style.color = "var(--text-muted)";
        tablinks[i].style.borderBottom = "none";
    }
    document.getElementById(tabName).style.display = "block";
    
    // Update active tab visual
    const activeBtn = document.querySelector(`button[onclick="openTab(event, '${tabName}')"]`);
    if(activeBtn) {
        activeBtn.className += " active";
        activeBtn.style.color = "var(--text-primary)";
        activeBtn.style.borderBottom = "2px solid var(--primary)";
    }
    
    // Update URL without reload
    const url = new URL(window.location);
    url.searchParams.set('tab', tabName);
    window.history.pushState({}, '', url);
}

// Set active tab on load based on URL or default
document.addEventListener('DOMContentLoaded', function() {
    const urlParams = new URLSearchParams(window.location.search);
    const tab = urlParams.get('tab') || 'general';
    openTab({currentTarget: document.querySelector(`button[onclick="openTab(event, '${tab}')"]`)}, tab);
});
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Projects\Atape\AtapeMgr\resources\views/settings/index.blade.php ENDPATH**/ ?>