@extends('layouts.app')

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h4 class="card-title mb-0">
                        <i class="fas fa-balance-scale text-success me-2"></i>
                        Balance Sheet
                    </h4>
                    <div>
                        <button class="btn btn-outline-primary me-2" onclick="printReport()">
                            <i class="fas fa-print"></i> Print
                        </button>
                        <button class="btn btn-outline-success" onclick="exportReport()">
                            <i class="fas fa-download"></i> Export PDF
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <!-- Report Filters -->
                    <div class="row mb-4">
                        <div class="col-md-4">
                            <label for="report_date" class="form-label">As of Date</label>
                            <input type="date" class="form-control" id="report_date"
                                   value="{{ date('Y-m-d') }}">
                        </div>
                        <div class="col-md-4">
                            <label for="branch_id" class="form-label">Branch</label>
                            <select class="form-control" id="branch_id">
                                <option value="">All Branches</option>
                                <!-- Branch options will be loaded here -->
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">&nbsp;</label>
                            <button class="btn btn-primary w-100" onclick="generateReport()">
                                <i class="fas fa-sync"></i> Generate Report
                            </button>
                        </div>
                    </div>

                    <!-- Balance Sheet Content -->
                    <div id="balance-sheet-content">
                        <div class="row">
                            <!-- Assets -->
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header bg-primary text-white">
                                        <h5 class="mb-0">
                                            <i class="fas fa-coins me-2"></i>
                                            Assets
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div id="assets-section">
                                            <!-- Assets will be loaded here -->
                                            <div class="text-center text-muted">
                                                <i class="fas fa-spinner fa-spin fa-2x"></i>
                                                <p>Loading assets...</p>
                                            </div>
                                        </div>
                                        <hr>
                                        <div class="d-flex justify-content-between fw-bold">
                                            <span>Total Assets</span>
                                            <span id="total-assets">$0.00</span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Liabilities and Equity -->
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header bg-success text-white">
                                        <h5 class="mb-0">
                                            <i class="fas fa-hand-holding-usd me-2"></i>
                                            Liabilities & Equity
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <!-- Liabilities -->
                                        <div id="liabilities-section">
                                            <h6 class="text-muted">Liabilities</h6>
                                            <!-- Liabilities will be loaded here -->
                                            <div class="text-center text-muted">
                                                <i class="fas fa-spinner fa-spin"></i>
                                                <p>Loading liabilities...</p>
                                            </div>
                                        </div>

                                        <hr>

                                        <!-- Equity -->
                                        <div id="equity-section">
                                            <h6 class="text-muted">Equity</h6>
                                            <!-- Equity will be loaded here -->
                                            <div class="text-center text-muted">
                                                <i class="fas fa-spinner fa-spin"></i>
                                                <p>Loading equity...</p>
                                            </div>
                                        </div>

                                        <hr>
                                        <div class="d-flex justify-content-between fw-bold">
                                            <span>Total Liabilities & Equity</span>
                                            <span id="total-liabilities-equity">$0.00</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Balance Check -->
                        <div class="row mt-3">
                            <div class="col-12">
                                <div id="balance-check" class="alert alert-success" style="display: none;">
                                    <i class="fas fa-check-circle"></i>
                                    Balance sheet is balanced.
                                </div>
                                <div id="balance-error" class="alert alert-danger" style="display: none;">
                                    <i class="fas fa-exclamation-triangle"></i>
                                    Balance sheet is not balanced. Please check your entries.
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function generateReport() {
    const reportDate = $('#report_date').val();
    const branchId = $('#branch_id').val();

    // Show loading
    $('#assets-section, #liabilities-section, #equity-section').html(`
        <div class="text-center text-muted">
            <i class="fas fa-spinner fa-spin fa-2x"></i>
            <p>Loading...</p>
        </div>
    `);

    $.ajax({
        url: '{{ route("accounts.reports.balance-sheet") }}',
        method: 'GET',
        data: {
            as_of_date: reportDate,
            branch_id: branchId
        },
        success: function(response) {
            if (response.success) {
                renderBalanceSheet(response.data);
            } else {
                alert('Error generating report: ' + response.message);
            }
        },
        error: function() {
            alert('Error loading balance sheet');
        }
    });
}

function renderBalanceSheet(data) {
    // Render Assets
    let assetsHtml = '';
    data.assets.forEach(asset => {
        assetsHtml += `
            <div class="d-flex justify-content-between">
                <span>${asset.account_name}</span>
                <span>$${parseFloat(asset.balance).toFixed(2)}</span>
            </div>
        `;
    });
    $('#assets-section').html(assetsHtml);

    // Render Liabilities
    let liabilitiesHtml = '';
    data.liabilities.forEach(liability => {
        liabilitiesHtml += `
            <div class="d-flex justify-content-between">
                <span>${liability.account_name}</span>
                <span>$${parseFloat(liability.balance).toFixed(2)}</span>
            </div>
        `;
    });
    $('#liabilities-section').html('<h6 class="text-muted">Liabilities</h6>' + liabilitiesHtml);

    // Render Equity
    let equityHtml = '';
    data.equity.forEach(equity => {
        equityHtml += `
            <div class="d-flex justify-content-between">
                <span>${equity.account_name}</span>
                <span>$${parseFloat(equity.balance).toFixed(2)}</span>
            </div>
        `;
    });
    $('#equity-section').html('<h6 class="text-muted">Equity</h6>' + equityHtml);

    // Update totals
    $('#total-assets').text('$' + parseFloat(data.total_assets).toFixed(2));
    $('#total-liabilities-equity').text('$' + (parseFloat(data.total_liabilities) + parseFloat(data.total_equity)).toFixed(2));

    // Check balance
    const isBalanced = Math.abs(data.total_assets - (data.total_liabilities + data.total_equity)) < 0.01;
    if (isBalanced) {
        $('#balance-check').show();
        $('#balance-error').hide();
    } else {
        $('#balance-check').hide();
        $('#balance-error').show();
    }
}

function printReport() {
    window.print();
}

function exportReport() {
    const reportDate = $('#report_date').val();
    const branchId = $('#branch_id').val();

    window.open('{{ route("accounts.reports.balance-sheet") }}?as_of_date=' + reportDate +
                '&branch_id=' + branchId + '&export=pdf', '_blank');
}

$(document).ready(function() {
    generateReport();
});
</script>

<style>
@media print {
    .card-header button,
    .btn {
        display: none !important;
    }

    .card {
        border: 1px solid #000 !important;
        box-shadow: none !important;
    }

    .card-header {
        background-color: #f8f9fa !important;
        color: #000 !important;
    }
}
</style>
@endsection
