@extends('admin-layouts.master')

@section('title', 'Laporan Pendapatan')

@section('content')
<style>
    @media print {
        .no-print {
            display: none !important;
        }
        
        .card {
            border: none !important;
            box-shadow: none !important;
        }
        
        .table {
            font-size: 11px;
        }
        
        .table th,
        .table td {
            padding: 4px !important;
            border: 1px solid #000 !important;
        }
        
        .table-active {
            background-color: #f8f9fa !important;
            -webkit-print-color-adjust: exact;
        }
        
        .page-title-box,
        .breadcrumb,
        .card-header,
        .btn,
        .pagination {
            display: none !important;
        }
    }
</style>
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="page-title-box">
                <div class="page-title-right">
                    <ol class="breadcrumb m-0">
                        <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
                        <li class="breadcrumb-item"><a href="#">Laporan</a></li>
                        <li class="breadcrumb-item active">Pendapatan</li>
                    </ol>
                </div>
                <h4 class="page-title">Laporan Pendapatan</h4>
            </div>
        </div>
    </div>

    <!-- Filter Card -->
    <div class="row mb-3">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <form method="GET" action="{{ route('reports.revenue.index') }}" class="row g-3">
                        <div class="col-md-3">
                            <label class="form-label">Tanggal Mulai</label>
                            <input type="date" class="form-control" name="start_date" value="{{ $startDate }}">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Tanggal Akhir</label>
                            <input type="date" class="form-control" name="end_date" value="{{ $endDate }}">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Status Invoice</label>
                            <select class="form-select form-control" name="status">
                                <option value="all" {{ $status == 'all' ? 'selected' : '' }}>Semua Status</option>
                                <option value="pending" {{ $status == 'pending' ? 'selected' : '' }}>Pending</option>
                                <option value="paid" {{ $status == 'paid' ? 'selected' : '' }}>Lunas</option>
                                <option value="cancelled" {{ $status == 'cancelled' ? 'selected' : '' }}>Dibatalkan</option>
                                <option value="overdue" {{ $status == 'overdue' ? 'selected' : '' }}>Jatuh Tempo</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">&nbsp;</label>
                            <div class="d-grid gap-2 d-md-block">
                                <button type="submit" class="btn btn-primary">
                                    <i class="mdi mdi-filter"></i> Filter
                                </button>
                                <a href="{{ route('reports.revenue.show', request()->query()) }}" class="btn btn-info">
                                    <i class="mdi mdi-eye"></i> Detail
                                </a>
                                <a href="{{ route('reports.revenue.print', request()->query()) }}" class="btn btn-success" target="_blank">
                                    <i class="mdi mdi-printer"></i> Print
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="row mb-3">
        <div class="col-xl-3 col-md-6">
            <div class="card widget-flat">
                <div class="card-body">
                    <div class="float-end">
                        <i class="mdi mdi-currency-usd widget-icon bg-success-lighten text-success"></i>
                    </div>
                    <h5 class="text-muted font-weight-normal mt-0" title="Total Pendapatan">Total Pendapatan</h5>
                    <h3 class="mt-3 mb-3">Rp {{ number_format($summary['total_revenue'], 0, ',', '.') }}</h3>
                    <p class="mb-0 text-muted">
                        <span class="text-success me-2"><i class="mdi mdi-arrow-up-bold"></i></span>
                        <span class="text-nowrap">Periode ini</span>
                    </p>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6">
            <div class="card widget-flat">
                <div class="card-body">
                    <div class="float-end">
                        <i class="mdi mdi-bed widget-icon bg-info-lighten text-info"></i>
                    </div>
                    <h5 class="text-muted font-weight-normal mt-0" title="Pendapatan Kamar">Pendapatan Kamar</h5>
                    <h3 class="mt-3 mb-3">Rp {{ number_format($summary['total_room_revenue'], 0, ',', '.') }}</h3>
                    <p class="mb-0 text-muted">
                        <span class="text-info me-2"><i class="mdi mdi-arrow-up-bold"></i></span>
                        <span class="text-nowrap">{{ number_format(($summary['total_revenue'] > 0 ? ($summary['total_room_revenue']/$summary['total_revenue']) * 100 : 0), 1) }}% dari total</span>
                    </p>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6">
            <div class="card widget-flat">
                <div class="card-body">
                    <div class="float-end">
                        <i class="mdi mdi-room-service widget-icon bg-warning-lighten text-warning"></i>
                    </div>
                    <h5 class="text-muted font-weight-normal mt-0" title="Pendapatan Layanan">Pendapatan Layanan</h5>
                    <h3 class="mt-3 mb-3">Rp {{ number_format($summary['total_service_revenue'], 0, ',', '.') }}</h3>
                    <p class="mb-0 text-muted">
                        <span class="text-warning me-2"><i class="mdi mdi-arrow-up-bold"></i></span>
                        <span class="text-nowrap">{{ number_format(($summary['total_revenue'] > 0 ? ($summary['total_service_revenue']/$summary['total_revenue']) * 100 : 0), 1) }}% dari total</span>
                    </p>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6">
            <div class="card widget-flat">
                <div class="card-body">
                    <div class="float-end">
                        <i class="mdi mdi-receipt widget-icon bg-primary-lighten text-primary"></i>
                    </div>
                    <h5 class="text-muted font-weight-normal mt-0" title="Total Invoice">Total Invoice</h5>
                    <h3 class="mt-3 mb-3">{{ $summary['paid_invoices'] + $summary['pending_invoices'] + $summary['overdue_invoices'] }}</h3>
                    <p class="mb-0 text-muted">
                        <span class="text-success me-2">{{ $summary['paid_invoices'] }} Lunas</span>
                        <span class="text-warning me-2">{{ $summary['pending_invoices'] }} Pending</span>
                        <span class="text-dark">{{ $summary['overdue_invoices'] }} Jatuh Tempo</span>
                    </p>
                </div>
            </div>
        </div>
    </div>

    <!-- Invoice List -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <h4 class="header-title">Daftar Invoice</h4>
                        <div>
                            <button onclick="printInvoiceList()" class="btn btn-success btn-sm">
                                <i class="fa fa-print"></i> Print List
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-centered table-striped dt-responsive nowrap w-100" id="invoice-list-table">
                            <thead>
                                <tr>
                                    <th>No</th>
                                    <th>Nama</th>
                                    <th>Tipe dan Nomor Kamar</th>
                                    <th>Tgl Check In</th>
                                    <th>Tgl Check Out</th>
                                    <th>Lama Inap</th>
                                    <th>Harga</th>
                                    <th>Layanan</th>
                                    
                                    <th>Subtotal</th>
                                    <th>Diskon</th>

                                    <th>Pajak</th>
                                    <th>Total</th>
                                    <th class="no-print">Status</th>
                                    <th class="no-print">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($invoices as $index => $invoice)
                                @php
                                    $booking = $invoice->booking;
                                    $guest = $booking->guest ?? null;
                                    $bookingDetail = $booking->bookingDetails->first();
                                    $room = $bookingDetail->room ?? null;
                                    $roomType = $room->typeRoom ?? null;
                                    
                                    $checkIn = $booking->check_in_date ? \Carbon\Carbon::parse($booking->check_in_date) : null;
                                    $checkOut = $booking->check_out_date ? \Carbon\Carbon::parse($booking->check_out_date) : null;
                                    $lamaInap = ($checkIn && $checkOut) ? $checkIn->diffInDays($checkOut) : 0;
                                    
                                    $hargaPerMalam = $bookingDetail->room_price ?? 0;
                                    $totalBiaya = $invoice->room_total + $invoice->services_total;
                                @endphp
                                <tr>
                                    <td>{{ $index + 1 }}</td>
                                    <td>{{ $guest->name ?? '-' }}</td>
                                    <td>
                                        @if($room && $roomType)
                                            {{ $room->room_number }}- {{ $roomType->name }}
                                        @else
                                            -
                                        @endif
                                    </td>
                                    <td>{{ $checkIn ? $checkIn->format('d M Y') : '-' }}</td>
                                    <td>{{ $checkOut ? $checkOut->format('d M Y') : '-' }}</td>
                                    <td class="text-center">{{ $lamaInap }}</td>
                                    <td class="text-end">{{ number_format($hargaPerMalam, 0, ',', '.') }}</td>
                                    <td class="text-end">{{ number_format($invoice->services_total, 0, ',', '.') }}</td>
                                    <td class="text-end">{{ number_format($totalBiaya, 0, ',', '.') }}</td>
                                    <td class="text-end">{{ number_format($invoice->discount_amount, 0, ',', '.') }}</td>

                                    <td class="text-end">{{ number_format($invoice->tax_amount, 0, ',', '.') }}</td>
                                    <td class="text-end"><strong>{{ number_format($invoice->grand_total, 0, ',', '.') }}</strong></td>
                                    <td class="no-print">
                                        @switch($invoice->status)
                                            @case('paid')
                                                <span class="badge bg-success text-white">Lunas</span>
                                                @break
                                            @case('pending')
                                                <span class="badge bg-warning text-white">Pending</span>
                                                @break
                                            @case('cancelled')
                                                <span class="badge bg-danger text-white">Dibatalkan</span>
                                                @break
                                            @case('overdue')
                                                <span class="badge bg-dark text-white">Jatuh Tempo</span>
                                                @break
                                            @default
                                                <span class="badge bg-secondary">{{ ucfirst($invoice->status) }}</span>
                                        @endswitch
                                    </td>
                                    <td class="no-print">
                                        <div class="btn-group" role="group">
                                            <a href="{{ route('invoices.show', $invoice->id) }}" class="btn btn-sm btn-outline-info">
                                                <i class="fa fa-eye"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                                @empty
                                <tr>
                                    <td colspan="12" class="text-center">Tidak ada data invoice untuk periode ini</td>
                                </tr>
                                @endforelse
                            </tbody>
                            @if($invoices->count() > 0)
                            <tfoot>
                                <tr class="table-active">
                                    <th colspan="6" class="text-end">TOTAL:</th>
                                    <th class="text-end">{{ number_format($invoices->sum(function($invoice) { return $invoice->booking->bookingDetails->sum('room_price'); }), 0, ',', '.') }}</th>
                                    <th class="text-end">{{ number_format($invoices->sum('services_total'), 0, ',', '.') }}</th>
                                    

                                    <th class="text-end">{{ number_format($invoices->sum('room_total') + $invoices->sum('services_total'), 0, ',', '.') }}</th>
                                    <th class="text-end">{{ number_format($invoices->sum('discount_amount'), 0, ',', '.') }}</th>
                                    <th class="text-end">{{ number_format($invoices->sum('tax_amount'), 0, ',', '.') }}</th>
                                    <th class="text-end"><strong>{{ number_format($invoices->sum('grand_total'), 0, ',', '.') }}</strong></th>
                                    <th class="no-print"></th>
                                    <th class="no-print"></th>
                                </tr>
                            </tfoot>
                            @endif
                        </table>
                    </div>

                    @if($invoices->hasPages())
                    <div class="d-flex justify-content-center mt-3 no-print">
                        {{ $invoices->appends(request()->query())->links() }}
                    </div>
                    @endif
                </div>
            </div>
        </div>
    </div>

    <!-- Monthly Revenue Chart -->
    @if($monthlyRevenue->count() > 0)
    <div class="row mt-3">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="header-title">Trend Pendapatan Bulanan</h4>
                </div>
                <div class="card-body">
                    <div id="monthly-revenue-chart"></div>
                </div>
            </div>
        </div>
    </div>
    @endif
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>

<script>
    // Print Invoice List Function
    function printInvoiceList() {
        // Hide elements not needed for print
        var printContents = document.getElementById('invoice-list-table').outerHTML;
        var originalContents = document.body.innerHTML;
        
        // Create print header
        var printHeader = `
            <div style="text-align: center; margin-bottom: 30px;">
                <h2>LAPORAN PENDAPATAN HOTEL</h2>
                <h3>Daftar Invoice</h3>
                <p>Periode: {{ $startDate }} s/d {{ $endDate }}</p>
                <p>Dicetak pada: ` + new Date().toLocaleDateString('id-ID', {
                    weekday: 'long',
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                }) + `</p>
            </div>
        `;
        
        // Print styles
        var printStyles = `
            <style>
                @media print {
                    body { font-family: Arial, sans-serif; font-size: 12px; }
                    table { width: 100%; border-collapse: collapse; margin-top: 20px; }
                    th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                    th { background-color: #f5f5f5; font-weight: bold; }
                    .text-center { text-align: center; }
                    .text-end { text-align: right; }
                    .no-print { display: none !important; }
                    .table-active { background-color: #f8f9fa; font-weight: bold; }
                }
            </style>
        `;
        
        document.body.innerHTML = printStyles + printHeader + printContents;
        window.print();
        document.body.innerHTML = originalContents;
        window.location.reload(); // Reload to restore functionality
    }
</script>

@if($monthlyRevenue->count() > 0)
<script>
    document.addEventListener("DOMContentLoaded", function () {
        var monthlyRevenueOptions = {
            chart: {
                type: 'area',
                height: 350,
                toolbar: { show: false },
                animations: {
                    enabled: true,
                    easing: 'easeinout',
                    speed: 800,
                }
            },
            series: [{
                name: 'Pendapatan',
                data: @json($monthlyRevenue->pluck('total')->map(fn($v) => (float) $v)->toArray())
            }],
            xaxis: {
                categories: @json($monthlyRevenue->map(function($item) {
                    return \Carbon\Carbon::create($item->year, $item->month)->translatedFormat('M Y');
                })->toArray()),
                labels: {
                    style: { colors: '#6c757d', fontSize: '12px' }
                }
            },
            yaxis: {
                labels: {
                    formatter: function(val) {
                        return 'Rp ' + val.toLocaleString('id-ID');
                    },
                    style: { colors: '#6c757d', fontSize: '12px' }
                }
            },
            colors: ['#0acf97'],
            dataLabels: { enabled: false },
            stroke: {
                curve: 'smooth',
                width: 3
            },
            fill: {
                type: 'gradient',
                gradient: {
                    shadeIntensity: 1,
                    opacityFrom: 0.4,
                    opacityTo: 0,
                    stops: [0, 100]
                }
            },
            tooltip: {
                theme: 'dark',
                y: {
                    formatter: function(val) {
                        return 'Rp ' + val.toLocaleString('id-ID');
                    }
                }
            },
            grid: {
                borderColor: '#f1f3fa',
                strokeDashArray: 4
            }
        };

        var monthlyRevenueChart = new ApexCharts(document.querySelector("#monthly-revenue-chart"), monthlyRevenueOptions);
        monthlyRevenueChart.render();
    });
</script>

@endif
@endpush

@endsection