@extends('layouts.app')

@section('title', 'Expenses Report')
@section('header', 'Expenses Report')

@section('content')
<style>
    .stat-card {
        background: white;
        border-radius: 12px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        transition: transform 0.3s;
    }
    .stat-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 5px 20px rgba(0,0,0,0.1);
    }
    .stat-icon {
        width: 50px;
        height: 50px;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        margin-bottom: 15px;
    }
    .stat-value {
        font-size: 28px;
        font-weight: bold;
        margin-bottom: 5px;
    }
    .stat-label {
        color: #6c757d;
        font-size: 14px;
    }
    .category-list {
        max-height: 200px;
        overflow-y: auto;
    }
</style>

<div class="row mb-4">
    <div class="col-md-4">
        <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white;">
                <i class="fas fa-chart-line"></i>
            </div>
            <div class="stat-value">${{ number_format($totalExpenses ?? 0, 2) }}</div>
            <div class="stat-label">Total Expenses</div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white;">
                <i class="fas fa-tags"></i>
            </div>
            <div class="stat-value">{{ count($expensesByCategory ?? []) }}</div>
            <div class="stat-label">Categories Used</div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                <i class="fas fa-receipt"></i>
            </div>
            <div class="stat-value">{{ $expenses->count() ?? 0 }}</div>
            <div class="stat-label">Total Transactions</div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <div class="d-flex justify-content-between align-items-center">
            <h5 class="mb-0">
                <i class="fas fa-list me-2"></i>Expenses Report
            </h5>
            <div>
                <button id="exportExcelBtn" class="btn btn-success">
                    <i class="fas fa-file-excel"></i> Export to Excel
                </button>
            </div>
        </div>
        <hr>
        <form method="GET" action="{{ route('reports.expenses') }}" class="row mt-3" id="reportForm">
            <div class="col-md-3">
                <label>Start Date</label>
                <input type="date" name="start_date" id="start_date" class="form-control" value="{{ request('start_date', $startDate ?? date('Y-m-d', strtotime('first day of this month'))) }}">
            </div>
            <div class="col-md-3">
                <label>End Date</label>
                <input type="date" name="end_date" id="end_date" class="form-control" value="{{ request('end_date', $endDate ?? date('Y-m-d')) }}">
            </div>
            <div class="col-md-3">
                <label>Category</label>
                <select name="category_id" id="category_id" class="form-control">
                    <option value="">All Categories</option>
                    @foreach($categories ?? [] as $category)
                    <option value="{{ $category->id }}" {{ request('category_id') == $category->id ? 'selected' : '' }}>
                        {{ $category->name }}
                    </option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-3">
                <label>&nbsp;</label>
                <div class="d-flex gap-2">
                    <button type="submit" class="btn btn-primary form-control">
                        <i class="fas fa-search"></i> Generate Report
                    </button>
                    <a href="{{ route('reports.expenses') }}" class="btn btn-secondary form-control">
                        <i class="fas fa-undo"></i> Reset
                    </a>
                </div>
            </div>
        </form>
    </div>
    <div class="card-body">
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="alert alert-danger">
                    <strong>Total Expenses</strong><br>
                    <h3>${{ number_format($totalExpenses ?? 0, 2) }}</h3>
                </div>
            </div>
            <div class="col-md-6">
                <div class="alert alert-info">
                    <strong>Expenses by Category</strong>
                    <ul class="mt-2 mb-0 category-list">
                        @foreach($expensesByCategory ?? [] as $categoryName => $amount)
                            <li><strong>{{ $categoryName }}</strong>: ${{ number_format($amount, 2) }}</li>
                        @endforeach
                    </ul>
                </div>
            </div>
        </div>
        
        <div class="table-responsive">
            <table class="table table-bordered table-striped table-hover" id="expensesTable">
                <thead class="table-dark">
                    <tr>
                        <th>Expense No</th>
                        <th>Title</th>
                        <th>Category</th>
                        <th>Date</th>
                        <th>Amount</th>
                        <th>Created By</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($expenses ?? [] as $expense)
                    <tr>
                        <td>{{ $expense->expense_no ?? 'N/A' }}</a>
                        <td>{{ $expense->title ?? 'N/A' }}</a>
                        <td>{{ $expense->category->name ?? 'N/A' }}</a>
                        <td>{{ $expense->expense_date }}</a>
                        <td class="text-end">${{ number_format($expense->amount ?? 0, 2) }}</a>
                        <td>{{ $expense->user->name ?? 'N/A' }}</a>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="6" class="text-center">No expenses found</a>
                    </tr>
                    @endforelse
                </tbody>
                <tfoot class="table-secondary">
                    <tr>
                        <th colspan="4" class="text-end">Total:</th>
                        <th class="text-end" id="footerTotal">${{ number_format($totalExpenses ?? 0, 2) }}</th>
                        <th></th>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>

<script>
$(document).ready(function() {
    // Initialize DataTable
    var table = $('#expensesTable').DataTable({
        pageLength: 25,
        responsive: true,
        order: [[3, 'desc']],
        language: {
            search: "Search:",
            lengthMenu: "Show _MENU_ entries",
            info: "Showing _START_ to _END_ of _TOTAL_ entries",
            paginate: {
                first: "First",
                last: "Last",
                next: "Next",
                previous: "Previous"
            }
        }
    });
    
    // Export to Excel
    $('#exportExcelBtn').click(function(e) {
        e.preventDefault();
        
        try {
            // Get total from footer
            let totalExpenses = parseFloat($('#footerTotal').text().replace('$', '').replace(/,/g, '')) || 0;
            let rowCount = $('#expensesTable tbody tr:visible').length;
            
            // Get expenses by category for summary
            let expensesByCategory = [];
            @foreach($expensesByCategory ?? [] as $categoryName => $amount)
                expensesByCategory.push({category: '{{ $categoryName }}', amount: {{ $amount }}});
            @endforeach
            
            // Get table data
            let data = [];
            let headers = [];
            
            // Get headers (all columns)
            $('#expensesTable thead th').each(function() {
                headers.push($(this).text().trim());
            });
            data.push(headers);
            
            // Get visible rows data
            $('#expensesTable tbody tr:visible').each(function() {
                let row = [];
                $(this).find('td').each(function() {
                    let text = $(this).text().trim();
                    // Remove any HTML tags
                    text = text.replace(/<[^>]*>/g, '');
                    row.push(text);
                });
                if (row.length > 0) {
                    data.push(row);
                }
            });
            
            // Add empty row for spacing
            data.push(['']);
            
            // Add summary section
            data.push(['EXPENSES REPORT SUMMARY']);
            data.push(['Total Expenses:', '$' + totalExpenses.toFixed(2)]);
            data.push(['Total Transactions:', rowCount.toString()]);
            data.push(['Average Expense:', '$' + (rowCount > 0 ? (totalExpenses / rowCount).toFixed(2) : '0.00')]);
            data.push(['']);
            data.push(['EXPENSES BY CATEGORY']);
            data.push(['Category', 'Amount']);
            @foreach($expensesByCategory ?? [] as $categoryName => $amount)
                data.push(['{{ $categoryName }}', '${{ number_format($amount, 2) }}']);
            @endforeach
            data.push(['']);
            data.push(['Report Period:', $('#start_date').val() || 'All Time', $('#end_date').val() ? ' to ' + $('#end_date').val() : '']);
            data.push(['Generated On:', new Date().toLocaleString()]);
            
            // Create worksheet
            let ws = XLSX.utils.aoa_to_sheet(data);
            let wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Expenses Report');
            
            // Set column widths
            ws['!cols'] = [
                {wch:15},  // Expense No
                {wch:30},  // Title
                {wch:20},  // Category
                {wch:15},  // Date
                {wch:15},  // Amount
                {wch:20}   // Created By
            ];
            
            // Save file
            let fileName = 'expenses_report_' + new Date().toISOString().slice(0,19).replace(/:/g, '-') + '.xlsx';
            XLSX.writeFile(wb, fileName);
            
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: 'Export completed successfully!',
                timer: 2000,
                showConfirmButton: false
            });
        } catch (error) {
            console.error('Export error:', error);
            Swal.fire('Error!', 'Failed to export: ' + error.message, 'error');
        }
    });
});
</script>
@endpush
@endsection