@extends('layouts.nav')

@section('title', 'Age Analysis Report')

@section('content')

<div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-gray-800">Age Analysis Report</h1>
</div>

<div class="card shadow mb-4">
    <!-- Display Errors (if any) -->
    @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <!-- Report Filters -->
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-primary">Report Filters</h6>
    </div>
    <div class="card-body">
        <form action="{{ route('AgeAnalysisReport.data') }}" method="post">
            @csrf

            <div class="form-group row">
                <div class="col-md-4 mb-3">
                    <label class="font-weight-bold text-secondary">Report Type</label>
                    <select class="form-control" name="report_type" id="reportType" required>
                        <option value="" disabled {{ request()->filled('report_type') ? '' : 'selected' }}>Select</option>
                        <option value="summary" {{ request()->input('report_type') == 'summary' ? 'selected' : '' }}>Summary</option>
                        <option value="detailed" {{ request()->input('report_type') == 'detailed' ? 'selected' : '' }}>Detailed</option>
                    </select>
                </div>

                <div class="col-md-4 mb-3">
                    <label class="font-weight-bold text-secondary">Date From</label>
                    <input type="date" class="form-control" name="from_date"
                           value="{{ request()->input('from_date', now()->format('Y-m-d')) }}" required>
                </div>

                <div class="col-md-4 mb-3">
                    <label class="font-weight-bold text-secondary">Date To</label>
                    <input type="date" class="form-control" name="to_date"
                           value="{{ request()->input('to_date', now()->format('Y-m-d')) }}" required>
                </div>
            </div>

            <div style="display: flex;">
                <button type="submit" id="viewButton" class="btn btn-primary btn-user btn-block" style="width: 100px; height: 40px; margin-right: 10px; margin-top: 6px;">View</button>
                <a href="{{ route('AgeAnalysisReport') }}" class="btn btn-secondary btn-user btn-block" style="width: 100px;">Refresh</a>
            </div>
        </form>
    </div>

    <!-- Only show report tables if a report type is set in the request -->
    @if(request()->filled('report_type'))

        <div class="card-body">

            {{-- Summary Report --}}
            @if(request()->input('report_type') == 'summary')
                <div id="summaryTable">


                    <table class="table table-bordered">
                        <thead>
                            <tr >
                                <th>Tenant</th>
                                <th>180+ Days</th>
                                <th>150 Days</th>
                                <th>120 Days</th>
                                <th>90 Days</th>
                                <th>60 Days</th>
                                <th>30 Days</th>
                                <th>Current</th>
                                <th>Balance</th>
                            </tr>
                        </thead>
                        <tbody>
    @php
        $totals = ['180_days' => 0, '150_days' => 0, '120_days' => 0, '90_days' => 0, '60_days' => 0, '30_days' => 0, 'current' => 0, 'balance' => 0];
    @endphp

    @foreach($reportData as $row)
        <tr>
            <td>{{ $row['tenant'] }}</td>
            <td>{{ !empty($row['180_days']) ? number_format($row['180_days'], 2) : '' }}</td>
            <td>{{ !empty($row['150_days']) ? number_format($row['150_days'], 2) : '' }}</td>
            <td>{{ !empty($row['120_days']) ? number_format($row['120_days'], 2) : '' }}</td>
            <td>{{ !empty($row['90_days']) ? number_format($row['90_days'], 2) : '' }}</td>
            <td>{{ !empty($row['60_days']) ? number_format($row['60_days'], 2) : '' }}</td>
            <td>{{ !empty($row['30_days']) ? number_format($row['30_days'], 2) : '' }}</td>
            <td>{{ !empty($row['current']) ? number_format($row['current'], 2) : '' }}</td>
            <td>{{ !empty($row['balance']) ? number_format($row['balance'], 2) : '' }}</td>
        </tr>

        @foreach($totals as $key => $value)
            @php $totals[$key] += $row[$key]; @endphp
        @endforeach
    @endforeach
</tbody>
<tfoot>
    <tr>
        <th>Totals:</th>
        <th>180+ Days<br><span style="color: blue;">{{ $totals['180_days'] != 0 ? number_format($totals['180_days'], 2) : '' }}</span></th>
        <th>150 Days<br><span style="color: blue;">{{ $totals['150_days'] != 0 ? number_format($totals['150_days'], 2) : '' }}</span></th>
        <th>120 Days<br><span style="color: blue;">{{ $totals['120_days'] != 0 ? number_format($totals['120_days'], 2) : '' }}</span></th>
        <th>90 Days<br><span style="color: blue;">{{ $totals['90_days'] != 0 ? number_format($totals['90_days'], 2) : '' }}</span></th>
        <th>60 Days<br><span style="color: blue;">{{ $totals['60_days'] != 0 ? number_format($totals['60_days'], 2) : '' }}</span></th>
        <th>30 Days<br><span style="color: blue;">{{ $totals['30_days'] != 0 ? number_format($totals['30_days'], 2) : '' }}</span></th>
        <th>Current<br><span style="color: blue;">{{ $totals['current'] != 0 ? number_format($totals['current'], 2) : '' }}</span></th>
        <th>Balance<br><span style="color: blue;">{{ $totals['balance'] != 0 ? number_format($totals['balance'], 2) : '' }}</span></th>
    </tr>
    <tr>
        <th>% of Balance:</th>
        @foreach (['180_days', '150_days', '120_days', '90_days', '60_days', '30_days', 'current'] as $key)
            <td>
                {{ $totals['balance'] > 0 && $totals[$key] > 0 ? round(($totals[$key] / $totals['balance']) * 100, 2) . '%' : '' }}
            </td>
        @endforeach
        <td></td>
    </tr>
</tfoot>


                    </table>
                </div>
            @endif
            {{-- Detailed Report --}}
@if(request()->input('report_type') == 'detailed')
    @if($detailedData->isNotEmpty())
        <div id="detailedTable">
            @foreach ($detailedData as $tenantName => $transactions)
                @php
                    $firstTxn = $transactions->first();
                    $tenantTotal = 0;
                @endphp
                <div class="tenant-section" style="margin-top: 30px; page-break-inside: avoid;">
                    <h4 style="margin-bottom: 15px; border-bottom: 1px solid #eee; padding-bottom: 8px;">
                        <strong>Tenant:</strong> {{ $tenantName }}
                    </h4>
                    <table class="table table-striped table-bordered" style="width: 100%; margin-bottom: 15px;">
                        <thead>
                            <tr>
                                <th style="width: 10%;">Date</th>
                                <th style="width: 10%;">Invoice</th>
                                <th style="width: 8%;">Discount</th>
                                <th style="width: 12%;">Rent (USD)</th>
                                <th style="width: 17%;">Amount Paid (USD)</th>
                                <th style="width: 14%;">Balance (USD)</th>
                                <th style="width: 8%;">Overdue(dys)</th>
                                <th style="width: 10%;">Age(Group)</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($transactions as $txn)
                                @php
                                    $entryDate = \Carbon\Carbon::parse($txn->entrydate);
                                    $now = \Carbon\Carbon::parse($to_date);
                                    $daysOverdue = $entryDate->diffInDays($now, false);
                                    $daysOverdue = max(0, $daysOverdue);

                                    $discountAmount = ($txn->discount / 100) * $txn->total;
                                    $paidAmount = $txn->dr ?? 0;
                                    $balance = ($txn->total ?? 0) - $discountAmount - $paidAmount;
                                    $bucket = match(true) {
                                        $daysOverdue >= 180 => '180 Days',
                                        $daysOverdue >= 150 => '150 Days',
                                        $daysOverdue >= 120 => '120 Days',
                                        $daysOverdue >= 90  => '90 Days',
                                        $daysOverdue >= 60  => '60 Days',
                                        $daysOverdue >= 30  => '30 Days',
                                        default            => 'Current',
                                    };

                                    $tenantTotal += $balance;
                                @endphp
                                <tr>
                                    <td>{{ $entryDate->format('d/m/Y') }}</td>
                                    <td>{{ $txn->batch }}</td>
                                    <td>{{ $txn->discount }}%</td>
                                    <td>{{ number_format(num: $txn->total, decimals: 2) }}</td>
                                    <td>{{ number_format(num: $paidAmount, decimals: 2) }}</td>
                                    <td>{{ number_format(num: $balance, decimals: 2) }}</td>
                                    <td>{{ $daysOverdue }} days</td>
                                    <td>{{ $bucket }}</td>
                                </tr>
                            @endforeach
                        </tbody>
                        <tfoot class="bg-primary-subtle">
                            <tr>
                                <td colspan="7" class="text-center font-weight-bold fs-2 text-primary">
                                    Closing balance for <span class="fs-10 text-dark text-uppercase">{{ $tenantName }}</span>
                                    : USD{{ number_format(num: $tenantTotal, decimals: 2) }}
                                </td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            @endforeach
        </div>
    @else
        <div class="text-center text-muted mt-5">
            <i class="fas fa-file-invoice-dollar" style="font-size: 3rem; color: #E6111FFF;"></i>
            <strong>
                <p class="mt-2">No detailed age analysis data found for the selected date range.</p>
            </strong>
        </div>
    @endif
@endif

        </div>
    @endif
</div>
@endsection
