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

@section('content')
<style>
    body { background-color: #f0f2f5; }
    .ui.container { padding: 0 5rem 3rem 2rem; margin-top: 3rem; }
    h2.ui.header { font-size: 1.8rem; font-weight: 700; margin-bottom: .5rem; }
    .ui.table { background: white; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
    .ui.segment {
        background: white;
        border-radius: 10px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        margin-top: 2rem;
        padding: 1.5rem;
    }
    .ui.button {
        margin-top: 1rem;
    }

    /* --- Larger, more comfortable action buttons --- */
    .actions-group .ui.button.tiny {
        padding: 9px 14px !important;         /* more padding for height & width */
        font-size: 0.9rem !important;         /* slightly larger font */
        line-height: 1.2rem !important;
        min-width: 100px;                     /* more space for labels */
        text-align: center;
        border-radius: 8px !important;        /* smoother rounded edges */
        font-weight: 600 !important;
        transition: all 0.2s ease-in-out;
    }

    /* Hover effect for better feedback */
    .actions-group .ui.button.tiny:hover {
        transform: translateY(-2px);
        box-shadow: 0 3px 6px rgba(0, 0, 0, 0.15);
    }

    /* Keep consistent gap between buttons */
    .actions-group {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
        flex-wrap: wrap;
    }

    .inline-form {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        margin: 0;
    }

    .actions-group .ui.red.button.tiny,
    .actions-group .ui.green.button.tiny,
    .actions-group .ui.blue.button.tiny {
        border-radius: 6px !important;
        font-weight: 500 !important;
    }

    /* Responsive alignment */
    @media (max-width: 768px) {
        .actions-group {
            flex-direction: column;
            gap: 4px;
        }
    }

    .status-label {
        display: inline-block;
        padding: 6px 12px;
        border-radius: 8px;
        font-size: 0.85rem;
        font-weight: 600;
        text-transform: capitalize;
        opacity: 0.9;
    }
    .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; }
    }
    .totals-row td { font-weight: 700; background: #f7f7f8; }

    td form {
        display: inline-block;
        margin-left: 4px;
    }
</style>

<div class="ui container">
    {{-- Header --}}
    <h2 class="ui header">{{ $user->name }}</h2>
    <p><strong>Bulan:</strong> {{ \Carbon\Carbon::parse($month)->translatedFormat('F Y') }}</p>

    {{-- Back button --}}
    <a href="{{ route('mileage::finance.index', ['month' => $month]) }}" class="ui grey button">
        <i class="arrow left icon"></i> Kembali
    </a>

    {{-- Claims Table --}}
    <table class="ui celled table">
        <thead>
            <tr>
                <th>#</th> {{-- new column for numbering --}}
                <th>Tarikh</th>
                <th>Butiran</th>
                <th>Jenis Kenderaan</th>
                <th>Dari</th>
                <th>Ke</th>
                <th>KM</th>
                <th>Tol (RM)</th>
                <th>Lain-lain (RM)</th>
                <th>Jumlah (RM)</th>
                <th>Status</th>
                <th>Tindakan</th>
            </tr>
        </thead>
        <tbody>
            @php
                use Carbon\Carbon;

                // Sort claims by ascending date
                $claims = $claims->sortBy(fn($c) => Carbon::parse($c->claim_date));

                // Step 1: Non-rejected claims
                $validClaims = $claims->where('status', '!=', 'Ditolak');

                // Step 2: Restrict to claims within the displayed month
                $monthStart = Carbon::parse($month)->startOfMonth();
                $monthEnd   = Carbon::parse($month)->endOfMonth();

                $validInMonth = $validClaims->filter(function($c) use ($monthStart, $monthEnd) {
                    if (empty($c->claim_date)) return false;
                    try {
                        $d = Carbon::parse($c->claim_date);
                    } catch (\Exception $e) {
                        return false;
                    }
                    return $d->between($monthStart, $monthEnd);
                });

                // Step 3: Count unique calendar days (YYYY-MM-DD)
                $uniqueDays = $validInMonth
                    ->pluck('claim_date')
                    ->map(fn($d) => Carbon::parse($d)->toDateString())
                    ->unique()
                    ->count();

                // Step 4: Compute base totals
                $total = 0;
                $totalMileage = $validInMonth->sum('total_mileage');
                $totalToll = $validInMonth->sum('toll_amount');
                $totalOthers = $validInMonth->sum('others_amount');

                // Step 5: Deduction
                $deduction = 40 * $uniqueDays;

                // === Calculate mileageAmount BEFORE the table ===
                $rateCar1 = 0.55; $rateCar2 = 0.50; $rateMoto = 0.30;
                $mileageAmount = 0;
                $vehicleGroups = [];

                $vehicleGroupCount = max(1, $validInMonth->groupBy(fn($c) => strtolower($c->jenisKenderaan->name ?? 'kereta'))->count());

                foreach ($validInMonth->groupBy(fn($c) => strtolower($c->jenisKenderaan->name ?? 'kereta')) as $type => $group) {
                    $typeMileage = $group->sum('total_mileage');
                    $typeClaimable = max(0, $typeMileage - ($deduction / $vehicleGroupCount));

                    if (in_array($type, ['motosikal', 'motorcycle'])) {
                        $typeAmount = $typeClaimable * $rateMoto;
                    } else {
                        $firstPart  = min($typeClaimable, 500);
                        $secondPart = max(0, $typeClaimable - 500);
                        $typeAmount = ($firstPart * $rateCar1) + ($secondPart * $rateCar2);
                    }

                    $mileageAmount += $typeAmount;
                }

                $subtotal = $mileageAmount + $totalToll + $totalOthers;
            @endphp

            @php
            // Group all claims by project (null = Tiada Projek)
            $groupedClaims = $claims->groupBy(function ($c) {
                return $c->project->p_project_description ?? 'Tiada Projek';
            });

            // Move "Tiada Projek" to the bottom
            $groupedClaims = $groupedClaims->sortBy(function ($claims, $projectName) {
                return $projectName === 'Tiada Projek' ? 1 : 0;
            });
        @endphp

        @forelse($groupedClaims as $projectName => $projectClaims)
            {{-- Project header --}}
            <tr style="background:#f8f9fa;">
                <td colspan="11" style="font-weight:bold;">
                    <i class="file alternate outline icon"></i> {{ $projectName }}
                </td>
            </tr>

            @foreach($projectClaims as $index => $claim)
                @php
                    $rowTotal = 0;
                    $claimableKM = 0;
                    $vehicle = strtolower($claim->jenisKenderaan->name ?? 'kereta');

                    if ($claim->status !== 'Ditolak') {
                        $claimableKM = $claim->total_mileage ?? 0;
                        if (in_array($vehicle, ['motosikal', 'motorcycle'])) {
                            $rowTotal = $claimableKM * 0.30;
                        } else {
                            $firstPart = min($claimableKM, 500);
                            $secondPart = max(0, $claimableKM - 500);
                            $rowTotal = ($firstPart * 0.55) + ($secondPart * 0.50);
                        }
                    }
                @endphp

                <tr>
                    <td>{{ $loop->iteration }}</td>
                    <td>{{ \Carbon\Carbon::parse($claim->claim_date)->format('d/m/Y') }}</td>
                    <td>{{ $claim->description ?? '-' }}</td>
                    <td>{{ ucfirst($vehicle) }}</td>
                    <td>{{ $claim->distance_from ?? '-' }}</td>
                    <td>{{ $claim->distance_to ?? '-' }}</td>
                    <td>{{ number_format($claim->total_mileage, 1) }}</td>
                    <td>{{ number_format($claim->toll_amount ?? 0, 2) }}</td>
                    <td>{{ number_format($claim->others_amount ?? 0, 2) }}</td>
                    <td>
                        {{ $claim->status !== 'Ditolak'
                            ? 'RM ' . number_format($rowTotal, 2)
                            : '- (Tuntutan Ditolak)' }}
                    </td>
                    <td><span class="status-label status-{{ $claim->status }}">{{ $claim->status }}</span></td>
                    <td>
                        <div class="actions-group">
                            {{-- Lihat (View) button - always visible --}}
                            <a href="{{ route('mileage::finance.viewEach', $claim->id) }}"
                            class="ui blue button tiny"
                            title="Lihat Butiran">
                                <i class="eye icon"></i> Lihat
                            </a>

                            {{-- Kemaskini button - show only for claims that can be edited --}}
                            @if(in_array($claim->status, ['Diproses', 'Disokong', 'Disahkan']))
                                <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 }}"
                                        data-others-details="{{ $claim->others_details }}">
                                    <i class="edit icon"></i> Kemaskini
                                </button>
                            @endif

                            {{-- Show Semak/Tolak buttons only if claim is not final --}}
                            @if(!in_array($claim->status, ['Disemak', 'Ditolak', 'Dibayar']))
                                <form action="{{ route('mileage::finance.updateStatus', $claim->id) }}" method="POST" class="inline-form">
                                    @csrf
                                    @method('PUT')

                                    @if(in_array($claim->status, ['Disahkan', 'Disokong', 'Diproses']))
                                        <button type="submit" name="action" value="Disemak" class="ui green button tiny">
                                            <i class="check icon"></i> Semak
                                        </button>
                                    @endif

                                    <button type="submit" name="action" value="Ditolak" class="ui red button tiny">
                                        <i class="times icon"></i> Tolak
                                    </button>
                                </form>
                            @endif
                            {{-- Show Bayar button only if claim is Disemak --}}
                            @if($claim->status === 'Disemak')
                                <form action="{{ route('mileage::finance.updateStatus', $claim->id) }}" method="POST" class="inline-form">
                                    @csrf
                                    @method('PUT')
                                    <button type="submit" name="action" value="Dibayar" class="ui teal button tiny">
                                        <i class="money bill alternate icon"></i> Bayar
                                    </button>
                                </form>
                            @endif
                        </div>
                    </td>
                </tr>
            @endforeach
            @php
                $projMileage = $projectClaims->sum('total_mileage');
                $projToll    = $projectClaims->sum('toll_amount');
                $projOthers  = $projectClaims->sum('others_amount');
            @endphp
            <tr class="totals-row">
                <td colspan="6" style="text-align:right;"><strong>Jumlah Projek Ini</strong></td>
                <td><strong>{{ number_format($projMileage, 1) }} KM</strong></td>
                <td><strong>RM {{ number_format($projToll, 2) }}</strong></td>
                <td><strong>RM {{ number_format($projOthers, 2) }}</strong></td>
                <td colspan="2"></td>
            </tr>

        @empty
            <tr>
                <td colspan="11" class="center aligned">Tiada tuntutan untuk bulan ini.</td>
            </tr>
        @endforelse

            @if($validInMonth->count() > 0)
                <tr class="totals-row">
                    <td colspan="6" style="text-align:right;"><strong>Jumlah Keseluruhan</strong></td>
                    <td><strong>{{ number_format($totalMileage, 1) }} KM</strong></td>
                    <td><strong>RM {{ number_format($totalToll, 2) }}</strong></td>
                    <td><strong>RM {{ number_format($totalOthers, 2) }}</strong></td>
                    <td colspan="2"><strong>RM {{ number_format($mileageAmount, 2) }}</strong></td>
                </tr>
            @endif

        </tbody>
    </table>

    {{-- Detailed Calculation Summary --}}
    @if($claims->count() > 0)
    @php
        // Use already filtered valid claims & computed uniqueDays
        $claimableDistance = max(0, $totalMileage - $deduction);

        // === Mileage by vehicle type ===
        $rateCar1 = 0.55; $rateCar2 = 0.50; $rateMoto = 0.30;
        $mileageAmount = 0;
        $vehicleGroups = [];

        foreach ($validInMonth->groupBy(fn($c) => strtolower($c->jenisKenderaan->name ?? 'kereta')) as $type => $group) {
            $typeMileage = $group->sum('total_mileage');
            $typeClaimable = max(0, $typeMileage - ($deduction / max($validInMonth->groupBy('jenisKenderaan.name')->count(), 1)));

            if (in_array($type, ['motosikal', 'motorcycle'])) {
                $typeAmount = $typeClaimable * $rateMoto;
                $vehicleGroups[] = [
                    'type' => ucfirst($type),
                    'details' => "{$typeClaimable} km × RM{$rateMoto}",
                    'amount' => $typeAmount
                ];
            } else {
                $firstPart  = min($typeClaimable, 500);
                $secondPart = max(0, $typeClaimable - 500);
                $typeAmount = ($firstPart * $rateCar1) + ($secondPart * $rateCar2);
                $vehicleGroups[] = [
                    'type' => ucfirst($type),
                    'details' => "{$firstPart} km × RM{$rateCar1}" .
                                ($secondPart > 0 ? " + {$secondPart} km × RM{$rateCar2}" : ""),
                    'amount' => $typeAmount
                ];
            }

            $mileageAmount += $typeAmount;
        }

        // === Subtotal ===
        $subtotal = $mileageAmount + $totalToll + $totalOthers;

        // === Penalty ===
                $finalTotal = $subtotal - $totalPenalty;
    @endphp


    <div class="ui segment">
        <h4><i class="calculator icon"></i> Ringkasan Pengiraan Bulanan</h4>
        <table class="ui definition table">
            <tr><td>Jumlah Perbatuan (Sebenar)</td><td>{{ number_format($totalMileage,1) }} KM</td></tr>
            <tr><td>Hari Tuntutan</td><td>{{ $uniqueDays }} hari</td></tr>
            <tr><td>Potongan 40 KM/Hari</td><td>{{ $uniqueDays }} × 40 = {{ $deduction }} KM</td></tr>
            <tr>
                <td>Jumlah Layak Tuntut</td>
                <td>
                    {{ number_format($totalMileage,1) }} KM − {{ number_format($deduction,1) }} KM
                    = <strong>{{ number_format($claimableDistance,1) }} KM</strong>
                </td>
            </tr>
            <tr>
                <td>Kadar Kiraan</td>
                <td>
                    @foreach($vehicleGroups as $v)
                        • {{ ucfirst($v['type']) }}: {!! $v['details'] !!} = <strong>RM {{ number_format($v['amount'],2) }}</strong><br>
                    @endforeach
                </td>
            </tr>
            <tr><td>Jumlah Perbatuan (RM)</td><td>RM {{ number_format($mileageAmount,2) }}</td></tr>
            <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>
            <tr><td><strong>Subtotal (Sebelum Penalti)</strong></td><td><strong>RM {{ number_format($subtotal,2) }}</strong></td></tr>
            <tr>
                <td>Penalti</td>
                <td>
                    @if($isBOD)
                        <span style="color:#d35400;"><i class="exclamation triangle icon"></i> Tertakluk kepada BOD</span>
                    @elseif($totalPenalty > 0)
                        Tolak: RM {{ number_format($totalPenalty, 2) }}<br>
                        @foreach($penaltyBreakdown as $p)
                            @if($p['penalty'] > 0)
                                • {{ \Carbon\Carbon::parse($p['claim_date'])->format('d/m/Y') }}: {{ $p['label'] }} (RM {{ number_format($p['penalty'], 2) }})<br>
                            @endif
                        @endforeach
                    @else
                        Tiada penalti
                    @endif
                </td>
            </tr>

            <tr class="totals-row">
                <td><strong>Jumlah Akhir (Selepas Penalti)</strong></td>
                <td><strong>RM {{ number_format($finalTotal,2) }}</strong></td>
            </tr>
        </table>
    </div>
    @endif

    {{-- 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>
@endsection

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {

    // === 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 othersDetails = $(this).data('others-details');

        const updateUrl = "{{ route('mileage::finance.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);
        $('#editOthersDetails').val(othersDetails || '');

        // 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').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;
        }

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