<title>Senarai Tuntutan</title>
@extends('ui::layouts.app')

@section('content')
<style>
    body {
        background-color: #f0f2f5;
    }

    .ui.container {
        max-width: 100% !important;
        overflow-x: hidden;
        padding: 0 5rem 0 2rem;
        box-sizing: border-box;
        margin-top: 3rem;
    }

    h2.ui.header {
        font-size: 1.8rem;
        font-weight: 700;
        color: #1b1c1d;
        margin-bottom: 0.5rem;
    }

    h3.ui.dividing.header {
        font-size: 1.3rem;
        font-weight: 600;
        color: #444;
        margin-top: 1.5rem;
        border-bottom: 2px solid #ddd;
        padding-bottom: 0.5rem;
    }

    .ui.table {
        margin-top: 1rem !important;
        background: white;
        border-radius: 10px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }

    .ui.table th {
        background: #f9fafb !important;
        color: #444;
        font-weight: 600;
    }

    .filter-bar {
        display: flex;
        align-items: center;
        gap: 1rem;
        background: white;
        border-radius: 8px;
        box-shadow: 0 3px 6px rgba(0, 0, 0, 0.08);
        padding: 0.8rem 1.5rem;
        width: fit-content;
        margin: 1.5rem 0;
    }

    .filter-bar label {
        font-weight: 600;
        color: #333;
        margin-right: 0.5rem;
    }

    .filter-bar input[type="month"] {
        border: 1px solid #dcdcdc;
        border-radius: 6px;
        padding: 0.4rem 0.6rem;
        font-size: 1rem;
        color: #333;
        transition: all 0.2s ease;
        height: 38px; /* ensures same height as button */
        line-height: 1.2rem;
    }

    .filter-bar input[type="month"]:focus {
        border-color: #21ba45;
        outline: none;
        box-shadow: 0 0 0 2px rgba(33, 186, 69, 0.15);
    }

    .filter-bar button {
        height: 38px;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    @media (max-width: 768px) {
        .filter-bar {
            flex-direction: column;
            align-items: flex-start;
            width: 100%;
        }

        .filter-bar button {
            width: 100%;
            margin-top: 0.5rem;
        }
    }

    .summary-toggle {
        cursor: pointer;
        background: white;
        border-radius: 10px;
        padding: 1rem 1.5rem;
        box-shadow: 0 3px 6px rgba(0, 0, 0, 0.08);
        display: flex;
        align-items: center;
        justify-content: space-between;
        transition: 0.2s ease;
        margin-bottom: 1rem;
    }

    .summary-toggle:hover {
        background: #f9fafb;
    }

    .summary-toggle i {
        transition: transform 0.3s ease;
    }

    .summary-toggle.active i {
        transform: rotate(180deg);
    }

    .summary-content {
        display: none;
        background: white;
        border-radius: 10px;
        box-shadow: 0 3px 6px rgba(0, 0, 0, 0.08);
        padding: 1.2rem 1.5rem;
        margin-bottom: 2rem;
    }

    .summary-content table {
        width: 100%;
        border-collapse: collapse;
        font-size: 0.95rem;
    }

    .summary-content td {
        padding: 6px 0;
    }

    .summary-content td:first-child {
        font-weight: 600;
        width: 50%;
        color: #333;
    }

    .status-label {
        display: inline-block;
        padding: 6px 12px;
        border-radius: 8px;
        font-size: 0.85rem;
        font-weight: 600;
        text-transform: capitalize;
        color: #fff;
    }

    .status-Diproses { background-color: rgba(33,133,208,0.3); color: #1b4f72; }
    .status-Disokong { background-color: rgba(46,204,113,0.3); color: #1d5d38; }
    .status-Disahkan { background-color: rgba(241,196,15,0.3); color: #7a6000; }
    .status-Disemak { background-color: rgba(155,89,182,0.3); color: #4a2c63; }
    .status-Dibayar { background-color: rgba(26,188,156,0.3); color: #0b5449; }
    .status-Ditolak { background-color: rgba(231,76,60,0.3); color: #7e2018; }

    @media (max-width: 768px) {
        .ui.container { padding: 0 2rem; }
        .filter-bar { flex-direction: column; align-items: flex-start; width: 100%; }
    }
</style>

<div class="ui container">
    <h2 class="ui header">Senarai Tuntutan Bulanan</h2>

    {{-- Month Filter --}}
    <form method="GET" class="filter-bar">
        <label for="month">Bulan:</label>
        <input type="month" id="month" name="month" value="{{ $month ?? now()->format('Y-m') }}" required>
        <button class="ui teal button">
            <i class="filter icon"></i> Tapis
        </button>
    </form>

    {{-- Calculation Summary Toggle --}}
    <div class="summary-toggle" id="summaryToggle">
        <span><i class="calculator icon"></i> Ringkasan Pengiraan Bulanan</span>
        <i class="angle down icon"></i>
    </div>

    <div class="summary-content" id="summaryContent">
        @php
            // === Step 1: Base totals ===
            $totalMileage = $claims->sum('total_mileage');
            $totalToll = $claims->sum('toll_amount');
            $totalOthers = $claims->sum('others_amount');

            // === Step 2: Deduct 400 km per month (not 40 per day) ===
            $claimableDistance = max(0, $totalMileage - 400);

            // === Step 3: Determine vehicle type & rate ===
            $vehicleType = strtolower($claims->first()->jenisKenderaan->name ?? 'kereta');
            $rate1 = 0.55;  // ≤500 km
            $rate2 = 0.50;  // >500 km
            $rateMoto = 0.30;

            // === Step 4: Mileage amount ===
            if ($vehicleType === 'motosikal' || $vehicleType === 'motorcycle') {
                $firstPart = $claimableDistance;
                $secondPart = 0;
                $mileageAmount = $claimableDistance * $rateMoto;
                $rateNote = "Motosikal – RM0.30/km";
            } else {
                $firstPart = min($claimableDistance, 500);
                $secondPart = max(0, $claimableDistance - 500);
                $mileageAmount = ($firstPart * $rate1) + ($secondPart * $rate2);
                $rateNote = "Kereta – RM0.55/km (≤500km), RM0.50/km (>500km)";
            }

            // === Step 5: Total before penalty ===
            $totalBeforePenalty = $mileageAmount + $totalToll + $totalOthers;

            // === Step 6: Calculate penalty by month ===
            $latestClaim = $claims->sortByDesc('created_at')->first();
            $submissionDate = \Carbon\Carbon::parse($latestClaim->created_at ?? now());
            $claimDate = \Carbon\Carbon::parse($claims->min('claim_date') ?? now());
            $monthsDiff = $claimDate->diffInMonths($submissionDate);

            if ($monthsDiff <= 1) {
                $penaltyRate = 0;
                $penaltyLabel = "Tiada penalti (≤ 1 bulan)";
            } elseif ($monthsDiff <= 3) {
                $penaltyRate = 0.10;
                $penaltyLabel = "Penalti 10% (lewat >1 bulan ≤3 bulan)";
            } elseif ($monthsDiff <= 6) {
                $penaltyRate = 0.30;
                $penaltyLabel = "Penalti 30% (lewat >3 bulan ≤6 bulan)";
            } else {
                $penaltyRate = 'BOD';
                $penaltyLabel = "Tertakluk kepada budi bicara Lembaga Pengarah (>6 bulan)";
            }

            if ($penaltyRate !== 'BOD') {
                $penaltyAmount = $totalBeforePenalty * $penaltyRate;
                $finalTotal = $totalBeforePenalty - $penaltyAmount;
            } else {
                $penaltyAmount = 0;
                $finalTotal = $totalBeforePenalty;
            }

            // === Step 7: System total from DB ===
            $totalAmount = $claims->sum('total_claim_amount');
        @endphp

        <table>
            <tr><td>Jumlah Perbatuan (Sebenar)</td><td>{{ number_format($totalMileage, 1) }} KM</td></tr>
            <tr><td>Potongan Bulanan</td><td>400 KM</td></tr>
            <tr><td>Jumlah Layak Tuntut</td><td>{{ number_format($claimableDistance, 1) }} KM</td></tr>
            <tr><td>Kadar Kiraan</td><td>{{ $rateNote }}</td></tr>

            {{-- Breakdown of mileage --}}
            <tr>
                <td>Kiraan Perbatuan</td>
                <td>
                    @if($vehicleType === 'motosikal' || $vehicleType === 'motorcycle')
                        {{ number_format($firstPart, 1) }} × RM{{ number_format($rateMoto, 2) }}
                        = <strong>RM {{ number_format($mileageAmount, 2) }}</strong>
                    @else
                        ({{ number_format($firstPart, 1) }} × RM{{ number_format($rate1, 2) }})
                        + ({{ number_format($secondPart, 1) }} × RM{{ number_format($rate2, 2) }})
                        <br><br><strong>RM {{ number_format($mileageAmount, 2) }}</strong>
                    @endif
                </td>
            </tr>

            {{-- Toll and others --}}
            <tr><td>Jumlah Tol</td><td>RM {{ number_format($totalToll, 2) }}</td></tr>
            <tr><td>Jumlah Lain-lain</td><td>RM {{ number_format($totalOthers, 2) }}</td></tr>

            {{-- Total before penalty --}}
            <tr>
                <td><strong>Jumlah Subtotal (Perbatuan + Tol + Lain-lain)</strong></td>
                <td><strong>RM {{ number_format($totalBeforePenalty, 2) }}</strong></td>
            </tr>

            {{-- Penalty --}}
            <tr>
                <td>Penalti</td>
                <td>
                    @if($penaltyRate === 'BOD')
                        <span style="color:#d35400;"><i class="exclamation triangle icon"></i> {{ $penaltyLabel }}</span>
                    @else
                        {{ $penaltyLabel }}<br>
                        Tolak: RM {{ number_format($penaltyAmount, 2) }}
                    @endif
                </td>
            </tr>

            {{-- Final total --}}
            <tr>
                <td><strong>Jumlah Akhir</strong></td>
                <td><strong>RM {{ number_format($finalTotal, 2) }}</strong></td>
            </tr>

            <tr>
                <td colspan="2" style="font-style:italic; color:#888;">
                    *Perbezaan kecil mungkin disebabkan pembulatan atau kemaskini oleh kewangan.*
                </td>
            </tr>
        </table>
    </div>

    {{-- Success message --}}
    @if(session('success'))
        <div class="ui positive message">{{ session('success') }}</div>
    @endif

    {{-- Error message --}}
    @if(session('error'))
        <div class="ui negative message">
            <i class="close icon"></i>
            <div class="header">Ralat!</div>
            <p>{{ session('error') }}</p>
        </div>
    @endif


    {{-- Group claims by project --}}
    @php
        $claimsByProject = $claims->groupBy(function ($claim) {
            return $claim->project->p_project_description ?? 'Tanpa Projek';
        });
    @endphp

    {{-- Existing claim tables remain unchanged --}}
    @forelse($claimsByProject as $projectName => $projectClaims)
        <h3 class="ui dividing header">
            <i class="folder icon"></i> {{ $projectName }}
        </h3>

        @if($projectName !== 'Tanpa Projek')
            <div style="margin-bottom: 0.5rem; font-size: 0.9rem; color: #555;">
                <i class="info circle icon"></i>
                Anda boleh mengemaskini tuntutan yang berstatus <strong>Diproses</strong> dengan menekan butang <strong>‘Lihat’</strong>.
            </div>
        @endif

        @if($projectName !== 'Tanpa Projek')
            @php
                $totalMileage = $projectClaims->sum('total_mileage');
                $totalAmount = $projectClaims->sum('total_claim_amount');
                $firstClaim = $projectClaims->first();
            @endphp

            <table class="ui celled table">
                <thead>
                    <tr>
                        <th>Jumlah Tuntutan</th>
                        <th>Jumlah Perbatuan (KM)</th>
                        <th>Jumlah Keseluruhan (RM)</th>
                        <th>Status</th>
                        <th>Tindakan</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>{{ $projectClaims->count() }}</td>
                        <td>{{ number_format($totalMileage, 1) }}</td>
                        <td>RM {{ number_format($totalAmount, 2) }}</td>
                        <td>
                            @foreach($projectClaims->pluck('status')->unique() as $status)
                                <span class="status-label status-{{ $status }}">{{ $status }}</span>
                            @endforeach
                        </td>
                        <td>
                            <a href="{{ route('mileage::applications.show', ['application' => $firstClaim->id, 'project_id' => $firstClaim->project_id]) }}" 
                                class="ui blue button tiny">
                                <i class="eye icon"></i> Lihat
                            </a>
                        </td>
                    </tr>
                </tbody>
            </table>
            <br>
        @else
            {{-- Tanpa Projek Table --}}
            <table class="ui celled table">
                <thead>
                    <tr>
                        <th>No.</th>
                        <th>Tarikh</th>
                        <th>Jenis Kenderaan</th>
                        <th>Butiran</th>
                        <th>Perbatuan (KM)</th>
                        <th>Jumlah (RM)</th>
                        <th>Status</th>
                        <th>Tindakan</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($projectClaims as $claim)
                        <tr>
                            <td>{{ $loop->iteration }}</td>
                            <td>{{ \Carbon\Carbon::parse($claim->claim_date)->format('d/m/Y') }}</td>
                            <td>{{ $claim->jenisKenderaan->name ?? '-' }}</td>
                            <td>{{ $claim->description }}</td>
                            <td>{{ number_format($claim->total_mileage, 1) }}</td>
                            <td>RM {{ number_format($claim->total_claim_amount, 2) }}</td>
                            <td>
                                <span class="status-label status-{{ $claim->status }}">{{ $claim->status }}</span>
                            </td>
                            <td>
                            {{-- Always show Lihat --}}
                            <a href="{{ route('mileage::applications.viewEach', ['id' => $claim->id]) }}" 
                                class="ui blue button tiny">
                                <i class="eye icon"></i> Lihat
                            </a>

                            @php
                                $isIncomplete = empty($claim->claim_date) || empty($claim->distance_from) || empty($claim->distance_to) || empty($claim->description) || empty($claim->total_mileage);
                            @endphp

                            @if($claim->status === 'Diproses')
                                @if($isIncomplete)
                                    <button class="ui grey button tiny disabled" title="Maklumat tidak lengkap — tidak boleh dikemaskini.">
                                        <i class="ban icon"></i> Tidak Lengkap
                                    </button>
                                @else
                                    <button class="ui yellow button tiny edit-btn"
                                            data-id="{{ $claim->id }}"
                                            data-date="{{ $claim->claim_date }}"
                                            data-description="{{ $claim->description }}"
                                            data-distance-from="{{ $claim->distance_from }}"
                                            data-distance-to="{{ $claim->distance_to }}"
                                            data-mileage="{{ $claim->total_mileage }}"
                                            data-toll="{{ $claim->toll_amount }}"
                                            data-others="{{ $claim->others_amount }}">
                                        <i class="edit icon"></i> Kemaskini
                                    </button>
                                @endif

                                <form action="{{ route('mileage::applications.destroy', $claim->id) }}" 
                                    method="POST" 
                                    style="display:inline;"
                                    onsubmit="return confirm('Padam tuntutan ini?');">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" class="ui red button tiny">
                                        <i class="trash icon"></i> Padam
                                    </button>
                                </form>
                            @endif
                        </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        @endif
    @empty
        <div class="ui message">Tiada tuntutan dijumpai untuk bulan ini.</div>
    @endforelse

    {{-- Edit Modal --}}
    <div class="ui modal" id="editModal">
        <i class="close icon"></i>
        <div class="header">Kemaskini Tuntutan</div>
        <div class="content">
            <form id="editForm" method="POST" action="">
                @csrf
                @method('PUT')
                <div class="ui form">
                    <div class="field required">
                        <label>Tarikh</label>
                        <input type="date" name="claim_date" id="editDate" required>
                    </div>

                    <div class="two fields">
                        <div class="field required">
                            <label>Dari</label>
                            <input type="text" name="distance_from" id="editFrom" required>
                        </div>
                        <div class="field required">
                            <label>Ke</label>
                            <input type="text" name="distance_to" id="editTo" required>
                        </div>
                    </div>

                    <div class="field required">
                        <label>Butiran</label>
                        <input type="text" name="description" id="editDescription" required>
                    </div>

                    <div class="three fields">
                        <div class="field required">
                            <label>Jumlah KM</label>
                            <input type="number" step="0.1" name="total_mileage" id="editMileage" required>
                        </div>
                        <div class="field">
                            <label>Tol (RM)</label>
                            <input type="number" step="0.01" name="toll_amount" id="editToll">
                        </div>
                        <div class="field">
                            <label>Lain-lain (RM)</label>
                            <input type="number" step="0.01" name="others_amount" id="editOthers">
                        </div>
                    </div>

                    <div class="field" id="othersDetailsField" style="display:none;">
                        <label>Butiran Lain-lain</label>
                        <input type="text" name="others_details" id="editOthersDetails" 
                            placeholder="Nyatakan butiran lain-lain (contoh: bayaran penghantaran, dokumen, dsb)">
                    </div>
                </div>
            </form>
        </div>
        <div class="actions">
            <div class="ui cancel button">Batal</div>
            <button type="submit" form="editForm" class="ui primary button">Simpan</button>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
    // Toggle Summary Section
    $('#summaryToggle').on('click', function() {
        $(this).toggleClass('active');
        $('#summaryContent').slideToggle(250);
    });

    // Handle Edit button click
    $('.edit-btn').on('click', function() {
        const id = $(this).data('id');
        const date = $(this).data('date');
        const desc = $(this).data('description');
        const from = $(this).data('distance-from');
        const to = $(this).data('distance-to');
        const mileage = $(this).data('mileage');
        const toll = $(this).data('toll');
        const others = $(this).data('others');

        const updateUrl = "{{ route('mileage::applications.update', ':id') }}".replace(':id', id);

        $('#editForm').attr('action', updateUrl);
        $('#editDate').val(date);
        $('#editDescription').val(desc);
        $('#editFrom').val(from);
        $('#editTo').val(to);
        $('#editMileage').val(mileage);
        $('#editToll').val(toll);
        $('#editOthers').val(others);

        // Trigger the others field logic
        $('#editOthers').trigger('input');

        $('#editModal').modal('show');
    });

    // Show/Hide "Butiran Lain-lain" based on input
    $('#editOthers').on('input', function() {
        const value = parseFloat($(this).val()) || 0;
        if (value > 0) {
            $('#othersDetailsField').slideDown();
            $('#editOthersDetails').attr('required', true);
        } else {
            $('#othersDetailsField').slideUp();
            $('#editOthersDetails').removeAttr('required');
            $('#editOthersDetails').val('');
        }
    });

    // Validate before form submission
    $('#editForm').on('submit', function(e) {
        const others = parseFloat($('#editOthers').val()) || 0;
        const othersDetails = $('#editOthersDetails').val().trim();

        if (others > 0 && othersDetails === '') {
            e.preventDefault();
            alert('Sila isi Butiran Lain-lain kerana jumlah Lain-lain (RM) lebih daripada 0.');
            $('#editOthersDetails').focus();
            return;
        }

        // General validation for required fields
        let valid = true;
        $('#editForm [required]').each(function() {
            if ($(this).val().trim() === '') {
                valid = false;
                $(this).focus();
                alert('Sila isi semua ruangan yang diperlukan.');
                e.preventDefault();
                return false;
            }
        });
    });
});
</script>
@endsection
