@extends('layouts.app')

@section('header')
    <div class="flex items-center">
        <h1 class="text-2xl font-semibold text-gray-900">Rent Roll Report</h1>
    </div>
@endsection

@section('content')
<div class="py-6">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <!-- Report Filters -->
        <div class="bg-white shadow sm:rounded-lg mb-6">
            <div class="px-4 py-5 sm:p-6">
                <h3 class="text-lg leading-6 font-medium text-gray-900">Report Filters</h3>
                <form action="{{ route('reports.rent-roll') }}" method="GET" class="mt-5 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
                    <div class="sm:col-span-2">
                        <label for="date" class="block text-sm font-medium text-gray-700">For Month</label>
                        <div class="mt-1">
                            <input type="month" name="date" id="date" value="{{ date('Y-m', strtotime($reportDate)) }}" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md">
                        </div>
                    </div>

                    <div class="sm:col-span-2">
                        <label for="property_id" class="block text-sm font-medium text-gray-700">Property</label>
                        <div class="mt-1">
                            <select id="property_id" name="property_id" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md">
                                <option value="">All Properties</option>
                                @foreach($properties as $property)
                                    <option value="{{ $property->PropID }}" {{ $selectedProperty == $property->PropID ? 'selected' : '' }}>
                                        {{ $property->PropName }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    <div class="sm:col-span-2 flex items-end">
                        <div class="w-full flex space-x-3">
                            <a href="{{ route('reports.index') }}" class="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                                Back to Reports
                            </a>
                            <button type="submit" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                                Generate Report
                            </button>
                            <a href="{{ route('reports.export.rent-roll') }}?{{ http_build_query(request()->all()) }}" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500">
                                Export to Excel
                            </a>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- Summary Cards -->
        <div class="grid grid-cols-1 gap-5 sm:grid-cols-4 mb-6">
            <div class="bg-white overflow-hidden shadow rounded-lg">
                <div class="px-4 py-5 sm:p-6">
                    <div class="flex items-center">
                        <div class="flex-shrink-0 bg-indigo-500 rounded-md p-3">
                            <svg class="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
                            </svg>
                        </div>
                        <div class="ml-5 w-0 flex-1">
                            <dl>
                                <dt class="text-sm font-medium text-gray-500 truncate">Total Tenants</dt>
                                <dd class="flex items-baseline">
                                    <div class="text-2xl font-semibold text-gray-900">
                                        {{ $assignments->count() }}
                                    </div>
                                </dd>
                            </dl>
                        </div>
                    </div>
                </div>
            </div>

            <div class="bg-white overflow-hidden shadow rounded-lg">
                <div class="px-4 py-5 sm:p-6">
                    <div class="flex items-center">
                        <div class="flex-shrink-0 bg-green-500 rounded-md p-3">
                            <svg class="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                        </div>
                        <div class="ml-5 w-0 flex-1">
                            <dl>
                                <dt class="text-sm font-medium text-gray-500 truncate">Total Billed Amount</dt>
                                <dd class="flex items-baseline">
                                    <div class="text-2xl font-semibold text-gray-900">
                                        Ksh {{ number_format($totalBilled, 2) }}
                                    </div>
                                </dd>
                                <dt class="text-sm font-medium text-gray-500 truncate mt-1">
                                    <span class="text-xs">(Rent: Ksh {{ number_format($totalRentDue, 2) }})</span>
                                </dt>
                            </dl>
                        </div>
                    </div>
                </div>
            </div>

            @php
                $totalRent = $assignments->sum('MonthlyRent');
                $totalPaid = $assignments->sum('paid_amount');
                $collectionRate = $totalRent > 0 ? round(($totalPaid / $totalRent) * 100, 1) : 0;
            @endphp

            <div class="bg-white overflow-hidden shadow rounded-lg">
                <div class="px-4 py-5 sm:p-6">
                    <div class="flex items-center">
                        <div class="flex-shrink-0 bg-blue-500 rounded-md p-3">
                            <svg class="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                            </svg>
                        </div>
                        <div class="ml-5 w-0 flex-1">
                            <dl>
                                <dt class="text-sm font-medium text-gray-500 truncate">Amount Collected</dt>
                                <dd class="flex items-baseline">
                                    <div class="text-2xl font-semibold text-gray-900">
                                        Ksh {{ number_format($totalPaid, 2) }}
                                    </div>
                                    <div class="ml-2 flex items-baseline text-sm font-semibold {{ $collectionRate >= 90 ? 'text-green-600' : ($collectionRate >= 70 ? 'text-yellow-600' : 'text-red-600') }}">
                                        {{ $collectionRate }}%
                                    </div>
                                </dd>
                                <dt class="text-xs text-gray-500 mt-1">Collection Rate</dt>
                            </dl>
                        </div>
                    </div>
                </div>
            </div>

            <div class="bg-white overflow-hidden shadow rounded-lg">
                <div class="px-4 py-5 sm:p-6">
                    <div class="flex items-center">
                        <div class="flex-shrink-0 bg-yellow-500 rounded-md p-3">
                            <svg class="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                            </svg>
                        </div>
                        <div class="ml-5 w-0 flex-1">
                            <dl>
                                <dt class="text-sm font-medium text-gray-500 truncate">Paid This Month</dt>
                                <dd class="flex items-baseline">
                                    <div class="text-2xl font-semibold text-gray-900">
                                        Ksh {{ number_format($assignments->sum('paid_amount'), 2) }}
                                    </div>
                                </dd>
                            </dl>
                        </div>
                    </div>
                </div>
            </div>

            <div class="bg-white overflow-hidden shadow rounded-lg">
                <div class="px-4 py-5 sm:p-6">
                    <div class="flex items-center">
                        <div class="flex-shrink-0 bg-red-500 rounded-md p-3">
                            <svg class="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                        </div>
                        <div class="ml-5 w-0 flex-1">
                            <dl>
                                <dt class="text-sm font-medium text-gray-500 truncate">Outstanding</dt>
                                <dd class="flex items-baseline">
                                    <div class="text-2xl font-semibold text-gray-900">
                                        Ksh {{ number_format($assignments->sum('outstanding_balance'), 2) }}
                                    </div>
                                </dd>
                            </dl>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Rent Roll Table -->
        <!-- <div class="bg-white shadow overflow-hidden sm:rounded-lg mb-6">
            <div class="px-4 py-5 border-b border-gray-200 sm:px-6">
                <h3 class="text-lg leading-6 font-medium text-gray-900">Rent Roll for {{ \Carbon\Carbon::parse($reportDate)->format('F Y') }}</h3>
                <p class="mt-1 max-w-2xl text-sm text-gray-500">Detailed rent collection status by tenant</p>
            </div>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Unit
                            </th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Tenant
                            </th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Phone
                            </th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Property / Unit
                            </th>
                            <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Monthly Rent
                            </th>
                            <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Service Charges
                            </th>
                            <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Total Billed
                            </th>
                            <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Paid
                            </th>
                            <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Balance
                            </th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Status
                            </th>
                            <th scope="col" class="relative px-6 py-3">
                                <span class="sr-only">Actions</span>
                            </th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        @forelse($assignments as $assignment)
                            @php
                                $status = $assignment->outstanding_balance <= 0 ? 'Paid' : 
                                         ($assignment->paid_amount > 0 ? 'Partial' : 'Unpaid');
                                $statusColor = [
                                    'Paid' => 'green',
                                    'Partial' => 'yellow',
                                    'Unpaid' => 'red'
                                ][$status];
                            @endphp
                            <tr class="hover:bg-gray-50">
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                    {{ $assignment->unit->UnitID ?? 'N/A' }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-gray-900">{{ $assignment->tenant_name ?? 'N/A' }}</div>
                                    <div class="text-sm text-gray-500">{{ $assignment->unit->Property->PropertyName ?? 'N/A' }}</div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    {{ $assignment->tenant_phone ?? 'N/A' }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm text-gray-900">{{ $assignment->unit->property->PropertyName }}</div>
                                    <div class="text-sm text-gray-500">{{ $assignment->unit->UnitName }}</div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-right text-sm text-gray-500">
                                    Ksh {{ number_format($assignment->unit->MonthlyRent ?? 0, 2) }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-right text-sm text-gray-500">
                                    @php
                                        $serviceCharges = ($assignment->total_billed ?? 0) - ($assignment->unit->MonthlyRent ?? 0);
                                    @endphp
                                    @if($serviceCharges > 0)
                                        <span class="text-green-600">+{{ number_format($serviceCharges, 2) }}</span>
                                    @else
                                        {{ number_format(0, 2) }}
                                    @endif
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium text-gray-900">
                                    Ksh {{ number_format($assignment->total_billed ?? $assignment->unit->MonthlyRent ?? 0, 2) }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    <div class="font-medium {{ $assignment->paid_amount > 0 ? 'text-green-600' : 'text-gray-500' }}">
                                        Ksh {{ number_format($assignment->paid_amount, 2) }}
                                    </div>
                                    @if($assignment->paid_amount > 0)
                                        <div class="text-xs text-gray-500">
                                            {{ $assignment->last_payment ? 'Last: ' . \Carbon\Carbon::parse($assignment->last_payment)->format('M d, Y') : '' }}
                                        </div>
                                    @endif
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                    <span class="{{ $assignment->outstanding_balance > 0 ? 'text-red-600' : 'text-green-600' }}">
                                        Ksh {{ number_format($assignment->outstanding_balance, 2) }}
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-{{ $statusColor }}-100 text-{{ $statusColor }}-800">
                                        {{ $status }}
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                    <a href="#" class="text-indigo-600 hover:text-indigo-900">View</a>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="7" class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-center">
                                    No rental records found for the selected period.
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                    @if($assignments->count() > 0)
                        <tfoot class="bg-gray-50">
                            <tr>
                                <th colspan="2" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Totals
                                </th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Ksh {{ number_format($assignments->sum(function($a) { return $a->unit->MonthlyRent ?? 0; }), 2) }}
                                </th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    @php
                                        $totalServiceCharges = $assignments->sum(function($a) { 
                                            return ($a->total_billed ?? 0) - ($a->unit->MonthlyRent ?? 0); 
                                        });
                                    @endphp
                                    @if($totalServiceCharges > 0)
                                        <span class="text-green-600">+{{ number_format($totalServiceCharges, 2) }}</span>
                                    @else
                                        {{ number_format(0, 2) }}
                                    @endif
                                </th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Ksh {{ number_format($totalBilled, 2) }}
                                </th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Ksh {{ number_format($assignments->sum('paid_amount'), 2) }}
                                </th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Ksh {{ number_format($assignments->sum('outstanding_balance'), 2) }}
                                </th>
                                <th colspan="2" class="px-6 py-3">
                                </th>
                            </tr>
                        </tfoot>
                    @endif
                </table>
            </div>
        </div> -->

        <!-- Payment Status Chart -->
        <div class="bg-white p-6 rounded-lg shadow mb-6">
            <h3 class="text-lg font-medium text-gray-900 mb-4">Payment Status Overview</h3>
            <div class="h-96">
                <canvas id="paymentStatusChart"></canvas>
            </div>
        </div>

        @push('scripts')
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                const ctx = document.getElementById('paymentStatusChart').getContext('2d');
                
                // Prepare data for the chart
                const paid = {{ $assignments->sum('paid_amount') }};
                const outstanding = {{ $assignments->sum('outstanding_balance') }};
                const total = {{ $assignments->sum('MonthlyRent') }};
                
                // Create the chart
                new Chart(ctx, {
                    type: 'doughnut',
                    data: {
                        labels: ['Paid', 'Outstanding'],
                        datasets: [{
                            data: [paid, outstanding],
                            backgroundColor: [
                                'rgba(16, 185, 129, 0.7)',
                                'rgba(239, 68, 68, 0.7)'
                            ],
                            borderColor: [
                                'rgba(16, 185, 129, 1)',
                                'rgba(239, 68, 68, 1)'
                            ],
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'bottom',
                            },
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        const label = context.label || '';
                                        const value = context.raw || 0;
                                        const percentage = Math.round((value / total) * 100) || 0;
                                        return `${label}: Ksh ${value.toLocaleString()} (${percentage}%)`;
                                    }
                                }
                            },
                            title: {
                                display: true,
                                text: `Total: Ksh ${total.toLocaleString()}`,
                                font: {
                                    size: 16
                                }
                            }
                        },
                        cutout: '65%'
                    }
                });

                // Add payment status badges to table rows
                document.querySelectorAll('.payment-status').forEach(cell => {
                    const status = cell.getAttribute('data-status');
                    let className = 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full ';
                    
                    if (status === 'fully_paid') {
                        className += 'bg-green-100 text-green-800';
                        cell.textContent = 'Paid';
                    } else if (status === 'partially_paid') {
                        className += 'bg-yellow-100 text-yellow-800';
                        cell.textContent = 'Partial';
                    } else {
                        className += 'bg-red-100 text-red-800';
                        cell.textContent = 'Unpaid';
                    }
                    
                    cell.className = className;
                });
            });
        </script>
        @endpush
    </div>
</div>

<!-- Include Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    // Payment Status Doughnut Chart
    document.addEventListener('DOMContentLoaded', function() {
        const ctx = document.createElement('canvas');
        document.querySelector('.bg-gray-50').appendChild(ctx);
        
        const paid = {{ $assignments->where('outstanding_balance', '<=', 0)->count() }};
        const partial = {{ $assignments->where('outstanding_balance', '>', 0)->where('paid_amount', '>', 0)->count() }};
        const unpaid = {{ $assignments->where('paid_amount', '<=', 0)->count() }};
        
        new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: ['Paid', 'Partial', 'Unpaid'],
                datasets: [{
                    data: [paid, partial, unpaid],
                    backgroundColor: [
                        '#10B981', // green-500
                        '#F59E0B', // yellow-500
                        '#EF4444'  // red-500
                    ],
                    hoverOffset: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'right',
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const label = context.label || '';
                                const value = context.raw || 0;
                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                const percentage = Math.round((value / total) * 100);
                                return `${label}: ${value} (${percentage}%)`;
                            }
                        }
                    }
                }
            }
        });
    });
</script>
@endsection
