@extends('layouts.app')

@section('title', 'Dashboard')

@section('content')
<div class="dashboard">
    <div class="page-header">
        <h1>Welcome, {{ $user->first_name }}!</h1>
        <p class="text-muted">{{ $user->organization?->name ?? 'No Organization' }} | {{ $user->getRoleNames()->first() ?? 'No Role' }}</p>
    </div>

    <div class="stats-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 1.5rem; margin-bottom: 2rem;">
        
        <!-- Members Card -->
        <div class="stat-card" style="background: linear-gradient(135deg, #1a202c 0%, #2d3748 100%); padding: 1.5rem; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); border: 1px solid rgba(255,255,255,0.05); position: relative; overflow: hidden;">
            <div style="position: absolute; top: -10px; right: -10px; font-size: 5rem; opacity: 0.05; transform: rotate(15deg);">👥</div>
            <div class="stat-icon" style="font-size: 2rem; margin-bottom: 0.5rem; color: #4fd1c5;">👥</div>
            <div class="stat-content">
                <h3 style="font-size: 1.8rem; font-weight: 700; margin: 0; color: #fff;">{{ number_format($totalMembers) }}</h3>
                <span style="color: #a0aec0; font-size: 0.9rem; text-transform: uppercase; letter-spacing: 0.5px;">Active Members</span>
            </div>
            @if($recentMembers->count() > 0)
            <div class="mt-3 pt-3 border-top d-flex justify-content-between align-items-center" style="border-color: rgba(255,255,255,0.1) !important; font-size: 0.8rem; color: #718096;">
                <span>Latest: {{ $recentMembers->first()->first_name }}</span>
                @if(isset($orgFinancials))
                <button onclick="viewFinancialBreakdown('members')" style="background: rgba(255,255,255,0.1); border: none; color: #fff; padding: 2px 8px; border-radius: 4px; cursor: pointer; font-size: 0.75rem;">View Breakdown</button>
                @endif
            </div>
            @endif
        </div>

        <!-- Income Card -->
        <div class="stat-card" style="background: linear-gradient(135deg, #1a202c 0%, #22543d 100%); padding: 1.5rem; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); border: 1px solid rgba(255,255,255,0.05); position: relative; overflow: hidden;">
            <div style="position: absolute; top: -10px; right: -10px; font-size: 5rem; opacity: 0.05; transform: rotate(15deg);">💰</div>
            <div class="stat-icon" style="font-size: 2rem; margin-bottom: 0.5rem; color: #48bb78;">💰</div>
            <div class="stat-content">
                <h3 style="font-size: 1.8rem; font-weight: 700; margin: 0; color: #fff;">{{ number_format($totalIncome) }}</h3>
                <span style="color: #9ae6b4; font-size: 0.9rem; text-transform: uppercase; letter-spacing: 0.5px;">Total Income</span>
            </div>
            <div class="mt-3 pt-3 border-top d-flex justify-content-between align-items-center" style="border-color: rgba(255,255,255,0.1) !important; font-size: 0.8rem; color: #9ae6b4;">
                <span>All recorded credits</span>
                @if(isset($orgFinancials))
                <button onclick="viewFinancialBreakdown('income')" style="background: rgba(255,255,255,0.1); border: none; color: #fff; padding: 2px 8px; border-radius: 4px; cursor: pointer; font-size: 0.75rem;">View Details</button>
                @endif
            </div>
        </div>

        <!-- Expense Card -->
        <div class="stat-card" style="background: linear-gradient(135deg, #1a202c 0%, #742a2a 100%); padding: 1.5rem; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); border: 1px solid rgba(255,255,255,0.05); position: relative; overflow: hidden;">
            <div style="position: absolute; top: -10px; right: -10px; font-size: 5rem; opacity: 0.05; transform: rotate(15deg);">💸</div>
            <div class="stat-icon" style="font-size: 2rem; margin-bottom: 0.5rem; color: #f56565;">💸</div>
            <div class="stat-content">
                <h3 style="font-size: 1.8rem; font-weight: 700; margin: 0; color: #fff;">{{ number_format($totalExpense) }}</h3>
                <span style="color: #feb2b2; font-size: 0.9rem; text-transform: uppercase; letter-spacing: 0.5px;">Total Expenses</span>
            </div>
             <div class="mt-3 pt-3 border-top d-flex justify-content-between align-items-center" style="border-color: rgba(255,255,255,0.1) !important; font-size: 0.8rem; color: #feb2b2;">
                <span>All approved debits</span>
                @if(isset($orgFinancials))
                <button onclick="viewFinancialBreakdown('expense')" style="background: rgba(255,255,255,0.1); border: none; color: #fff; padding: 2px 8px; border-radius: 4px; cursor: pointer; font-size: 0.75rem;">View Details</button>
                @endif
            </div>
        </div>

        <!-- Pending Approvals Card -->
        @if($pendingApprovals > 0)
        <a href="{{ route('transactions.pending') }}" class="stat-card" style="text-decoration: none; background: linear-gradient(135deg, #744210 0%, #975a16 100%); padding: 1.5rem; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); border: 1px solid rgba(255,255,255,0.05); position: relative; overflow: hidden; transition: transform 0.2s;">
            <div style="position: absolute; top: -10px; right: -10px; font-size: 5rem; opacity: 0.1; transform: rotate(15deg);">⚠️</div>
            <div class="stat-icon" style="font-size: 2rem; margin-bottom: 0.5rem; color: #fbd38d;">⚠️</div>
            <div class="stat-content">
                <h3 style="font-size: 1.8rem; font-weight: 700; margin: 0; color: #fff;">{{ $pendingApprovals }}</h3>
                <span style="color: #feebc8; font-size: 0.9rem; text-transform: uppercase; letter-spacing: 0.5px; font-weight: bold;">Approvals Needed</span>
            </div>
            <div class="mt-3 pt-3 border-top" style="border-color: rgba(255,255,255,0.1) !important; font-size: 0.8rem; color: #fff;">
                Review Pending Items &rarr;
            </div>
        </a>
        @else
        <div class="stat-card" style="background: linear-gradient(135deg, #1a202c 0%, #2d3748 100%); padding: 1.5rem; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); border: 1px solid rgba(255,255,255,0.05);">
            <div class="stat-icon" style="font-size: 2rem; margin-bottom: 0.5rem; color: #4fd1c5;">✅</div>
             <div class="stat-content">
                <h3 style="font-size: 1.8rem; font-weight: 700; margin: 0; color: #fff;">0</h3>
                <span style="color: #a0aec0; font-size: 0.9rem; text-transform: uppercase; letter-spacing: 0.5px;">Pending Actions</span>
            </div>
             <div class="mt-3 pt-3 border-top" style="border-color: rgba(255,255,255,0.1) !important; font-size: 0.8rem; color: #718096;">
                You are all caught up!
            </div>
        </div>
        @endif
    </div>

    <div class="row" style="display: flex; gap: 2rem; flex-wrap: wrap;">
        <!-- Quick Actions -->
        <div class="col-md-4" style="flex: 1; min-width: 300px;">
             <div class="card" style="height: 100%;">
                 <h3 style="margin-bottom: 1.5rem; font-size: 1.25rem;">Quick Actions</h3>
                 <div class="action-grid" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 1rem;">
                    @can('members.create')
                    <a href="{{ route('members.create') }}" class="action-card" style="display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 1.5rem; background: var(--bg-secondary); border-radius: 8px; text-decoration: none; color: var(--text-primary); transition: background 0.2s;">
                        <span class="action-icon" style="font-size: 1.5rem; margin-bottom: 0.5rem;">👤</span>
                        <span style="font-size: 0.9rem;">Add Member</span>
                    </a>
                    @endcan
                    @can('finance.create')
                    <a href="{{ route('transactions.create') }}" class="action-card" style="display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 1.5rem; background: var(--bg-secondary); border-radius: 8px; text-decoration: none; color: var(--text-primary); transition: background 0.2s;">
                        <span class="action-icon" style="font-size: 1.5rem; margin-bottom: 0.5rem;">💸</span>
                        <span style="font-size: 0.9rem;">New Expense</span>
                    </a>
                    <a href="{{ route('contributions.create') }}" class="action-card" style="display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 1.5rem; background: var(--bg-secondary); border-radius: 8px; text-decoration: none; color: var(--text-primary); transition: background 0.2s;">
                        <span class="action-icon" style="font-size: 1.5rem; margin-bottom: 0.5rem;">💳</span>
                        <span style="font-size: 0.9rem;">Record Income</span>
                    </a>
                    @endcan
                    <a href="{{ route('budgets.index') }}" class="action-card" style="display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 1.5rem; background: var(--bg-secondary); border-radius: 8px; text-decoration: none; color: var(--text-primary); transition: background 0.2s;">
                        <span class="action-icon" style="font-size: 1.5rem; margin-bottom: 0.5rem;">📊</span>
                        <span style="font-size: 0.9rem;">Budgets</span>
                    </a>
                 </div>
             </div>
        </div>

        <!-- Recent Activity -->
        <div class="col-md-8" style="flex: 2; min-width: 300px;">
            <div class="card" style="height: 100%;">
                <div class="card-header d-flex justify-content-between align-items-center mb-3">
                    <h3 style="margin: 0; font-size: 1.25rem;">Recent Activity</h3>
                    <a href="{{ route('settings.index', ['tab' => 'audit']) }}" style="font-size: 0.85rem; color: var(--primary);">View All</a>
                </div>
                
                <div class="activity-timeline">
                    @forelse($recentActivity as $log)
                    <div class="activity-item" style="display: flex; gap: 1rem; margin-bottom: 1rem; padding-bottom: 1rem; border-bottom: 1px solid var(--border-color);">
                        <div class="activity-icon" style="width: 32px; height: 32px; border-radius: 50%; background: var(--bg-tertiary); display: flex; align-items: center; justify-content: center; font-size: 1.2rem;">
                            {{ $log->action === 'Create' ? '➕' : ($log->action === 'Delete' ? '🗑️' : '✏️') }}
                        </div>
                        <div class="activity-content" style="flex: 1;">
                            <div style="font-weight: 500; font-size: 0.95rem;">
                                {{ $log->user->full_name ?? 'System' }} 
                                <span class="text-muted" style="font-weight: normal;">{{ strtolower($log->action) }}d a</span> 
                                {{ rtrim($log->table_name, 's') }}
                            </div>
                            <div class="text-muted small" style="margin-top: 0.25rem;">
                                {{ $log->created_at->diffForHumans() }}
                            </div>
                        </div>
                    </div>
                    @empty
                    <div class="text-center text-muted py-4">No recent activity</div>
                    @endforelse
                </div>
            </div>
        </div>
    </div>
</div>
<style>
.action-card:hover {
    background: var(--bg-tertiary) !important;
    transform: translateY(-2px);
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
</style>

@if(isset($orgFinancials))
<script>
const orgTree = @json($orgFinancials);
let currentBreadcrumbs = [];

function viewFinancialBreakdown(type) {
    // type: 'income', 'expense', 'members'
    let titleStr = '';
    let colorClass = '';
    let valueKey = '';
    
    if(type === 'income') {
        titleStr = 'Income Breakdown';
        colorClass = 'text-success';
        valueKey = 'total_income';
    } else if(type === 'expense') {
        titleStr = 'Expense Breakdown';
        colorClass = 'text-danger';
        valueKey = 'total_expense';
    } else {
        titleStr = 'Member Breakdown';
        colorClass = 'text-info';
        valueKey = 'total_members';
    }

    // Reset breadcrumbs
    currentBreadcrumbs = [{ name: 'All Organizations', nodes: orgTree }];
    
    renderModal(type, titleStr, colorClass, valueKey);
}

function renderModal(type, titleStr, colorClass, valueKey) {
    const currentLevel = currentBreadcrumbs[currentBreadcrumbs.length - 1];
    const nodes = currentLevel.nodes;
    const parentName = currentLevel.name;

    // Calculate total for this level's context (sum of displayed nodes)
    // Note: If displaying children, the sum should ideally match the parent's total.
    const total = nodes.reduce((sum, n) => sum + (n[valueKey] || 0), 0);
    const formattedTotal = type === 'members' ? new Intl.NumberFormat().format(total) : new Intl.NumberFormat().format(total) + ' TZS';

    let content = `
        <div class="text-left">
            <div class="d-flex justify-content-between align-items-center mb-3 p-3 rounded" style="background: var(--bg-secondary);">
                <div>
                     <div class="text-muted small text-uppercase font-weight-bold mb-1">${parentName}</div>
                     <h3 class="m-0 font-weight-bold ${colorClass}">${formattedTotal}</h3>
                </div>
                ${currentBreadcrumbs.length > 1 ? `
                <button onclick="navigateUp('${type}', '${titleStr}', '${colorClass}', '${valueKey}')" class="btn btn-sm btn-outline-secondary text-white border-0" style="background: rgba(255,255,255,0.1);">
                    &larr; Back
                </button>
                ` : ''}
            </div>
            
            <div class="table-responsive rounded border" style="border-color: var(--border-color) !important;">
                <table class="table table-sm mb-0 table-hover">
                    <thead style="background: var(--bg-tertiary);">
                        <tr>
                            <th class="border-0 text-uppercase text-muted small pl-3 py-3">Organization</th>
                            <th class="border-0 text-uppercase text-muted small py-3 text-right pr-3">${type === 'members' ? 'Count' : 'Amount'}</th>
                            <th class="border-0 text-uppercase text-muted small py-3 text-right pr-3">%</th>
                        </tr>
                    </thead>
                    <tbody>
    `;

    // Sort by value desc
    const sortedData = [...nodes].sort((a, b) => (b[valueKey] || 0) - (a[valueKey] || 0));

    sortedData.forEach((node, index) => {
        const val = node[valueKey] || 0;
        if (val > 0 || type === 'members') { // Show members even if 0? Maybe not.
            const percentage = total > 0 ? ((val / total) * 100).toFixed(1) : 0;
            const hasChildren = node.children_list && node.children_list.length > 0;
            
            content += `
                <tr style="cursor: ${hasChildren ? 'pointer' : 'default'};" 
                    onclick="${hasChildren ? `drillDown(${index}, '${type}', '${titleStr}', '${colorClass}', '${valueKey}')` : ''}"
                    title="${hasChildren ? 'Click to drill down' : ''}">
                    <td class="pl-3 py-3 border-top" style="border-color: var(--border-color);">
                        <span class="font-weight-bold ${hasChildren ? 'text-primary' : 'text-white'}">
                            ${node.name} ${hasChildren ? '<small>&#9654;</small>' : ''}
                        </span>
                    </td>
                    <td class="py-3 text-right pr-3 border-top font-family-monospace" style="border-color: var(--border-color);">
                        ${new Intl.NumberFormat().format(val)}
                    </td>
                     <td class="py-3 text-right pr-3 border-top text-muted small" style="border-color: var(--border-color);">
                        ${percentage}%
                    </td>
                </tr>
            `;
        }
    });

    if (sortedData.every(node => (node[valueKey] || 0) == 0)) {
         content += `<tr><td colspan="3" class="text-center py-4 text-muted">No records found.</td></tr>`;
    }

    content += `</tbody></table></div>
        <div class="text-right mt-2"><small class="text-muted">Click highlighted items to view detailed breakdown</small></div>
    </div>`;

    // If modal exists, update it, else create
    if(Swal.isVisible()) {
        Swal.getHtmlContainer().innerHTML = content;
    } else {
        Swal.fire({
            title: titleStr,
            html: content,
            width: '600px',
            showCloseButton: true,
            showConfirmButton: false,
            background: '#1a1f2c',
            color: '#ffffff',
            customClass: {
                content: 'p-0 text-left'
            }
        });
    }
    
    // Bind data to window for drillDown access if needed, or rely on closure
    window._currentSortedData = sortedData; 
}

function drillDown(index, type, titleStr, colorClass, valueKey) {
    const node = window._currentSortedData[index];
    if(node && node.children_list) {
        currentBreadcrumbs.push({ name: node.name, nodes: node.children_list });
        renderModal(type, titleStr, colorClass, valueKey);
    }
}

function navigateUp(type, titleStr, colorClass, valueKey) {
    if(currentBreadcrumbs.length > 1) {
        currentBreadcrumbs.pop();
        renderModal(type, titleStr, colorClass, valueKey);
    }
}
</script>
@endif
@endsection
