<title>Butiran Tuntutan Bulanan</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.segment {
        background: white;
        border-radius: 10px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        margin-top: 2rem;
        padding: 1.5rem;
    }
    .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-Diluluskan { background-color: rgba(26,188,156,0.3); color: #0b5449; }
    .status-Ditolak { background-color: rgba(231,76,60,0.3); color: #7e2018; }

    table.ui.table { background: white; border-radius: 10px; }
    .totals-row td { font-weight: 700; background: #f7f7f8; }
    .small-muted { font-size: .9rem; color: #666; }

    @media (max-width: 768px) {
        .ui.container { padding: 0 2rem; }
    }
</style>

<div class="ui container">
    <h2 class="ui header">Butiran Tuntutan Bulanan</h2>
    <p>
        <strong>Projek:</strong> {{ $projectName }} <br>
        <strong>Bulan:</strong> {{ \Carbon\Carbon::parse($month)->translatedFormat('F Y') }}
    </p>

    {{-- Claims Table --}}
    <table class="ui celled table">
        <thead>
            <tr>
                <th>Tarikh</th>
                <th>Butiran</th>
                <th>Dari</th>
                <th>Ke</th>
                <th>Jumlah KM</th>
                <th>Tol (RM)</th>
                <th>Lain-lain (RM)</th>
                <th>Status</th>
                <th>Jumlah (RM)</th>
                <th>Tindakan</th>
            </tr>
        </thead>
        <tbody>
            @php
                $total = 0;
                $totalMileage = 0;
                $totalToll = 0;
                $totalOthers = 0;
            @endphp

            @foreach($claims as $c)
                @php
                    $total += $c->total_claim_amount;
                    $totalMileage += $c->total_mileage ?? 0;
                    $totalToll += $c->toll_amount ?? 0;
                    $totalOthers += $c->others_amount ?? 0;
                @endphp

                <tr>
                    <td>{{ \Carbon\Carbon::parse($c->claim_date)->format('d/m/Y') }}</td>
                    <td>{{ $c->description ?? '-' }}</td>
                    <td>{{ $c->distance_from ?? '-' }}</td>
                    <td>{{ $c->distance_to ?? '-' }}</td>
                    <td>{{ number_format($c->total_mileage, 1) }}</td>
                    <td>{{ number_format($c->toll_amount ?? 0, 2) }}</td>
                    <td>{{ number_format($c->others_amount ?? 0, 2) }}</td>
                    <td>
                        @if($c->status === 'Ditolak')
                            <span class="status-label status-Ditolak"
                                data-tooltip="{{ $c->reject_reason ?? 'Tiada sebab diberikan.' }}"
                                data-inverted
                                data-position="top center"
                                style="cursor: help;">
                                {{ $c->status }}
                            </span>
                        @else
                            <span class="status-label status-{{ $c->status }}">
                                {{ $c->status }}
                            </span>
                        @endif
                    </td>
                    <td>
                        RM {{ number_format($c->total_claim_amount, 2) }}
                    </td>
                    <td>
                        {{-- actions for Diproses --}}
                        @if($c->status === 'Diproses')
                            <div style="margin-top:8px;">
                                <button class="ui yellow tiny button edit-btn"
                                        data-id="{{ $c->id }}"
                                        data-date="{{ $c->claim_date }}"
                                        data-description="{{ $c->description }}"
                                        data-distance-from="{{ $c->distance_from }}"
                                        data-distance-to="{{ $c->distance_to }}"
                                        data-mileage="{{ $c->total_mileage }}"
                                        data-toll="{{ $c->toll_amount }}"
                                        data-others="{{ $c->others_amount }}">
                                    <i class="edit icon"></i> Kemaskini
                                </button>

                                <form action="{{ route('mileage::applications.destroy', $c->id) }}" 
                                    method="POST" style="display:inline;"
                                    onsubmit="return confirm('Padam tuntutan ini?');">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" class="ui red tiny button">
                                        <i class="trash icon"></i> Padam
                                    </button>
                                </form>
                            </div>
                        @endif
                    </td>
                </tr>
            @endforeach
        </tbody>
        <tfoot>
            <tr class="totals-row">
                <td colspan="4" class="right aligned"><strong>Jumlah Keseluruhan:</strong></td>
                <td>{{ number_format($totalMileage, 1) }} KM</td>
                <td>RM {{ number_format($totalToll, 2) }}</td>
                <td>RM {{ number_format($totalOthers, 2) }}</td>
                <td></td>
                <td><strong>RM {{ number_format($total, 2) }}</strong></td>
            </tr>
        </tfoot>
    </table>

    {{-- Info Section --}}
    <div class="ui segment">
        <h4><i class="info circle icon"></i> Nota Pengiraan</h4>
        <p>
            • Potongan 40KM dikenakan bagi setiap hari perjalanan.<br>
            • Kadar (Kereta): RM0.55/km bagi ≤500km, RM0.50/km bagi >500km.<br>
            • Kadar (Motosikal): RM0.30/km.<br>
            • Tuntutan termasuk Tol dan Lain-lain jika disertakan resit.
        </p>
    </div>

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

{{-- Edit Modal Script --}}
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
    // Initialize tooltips for Ditolak statuses
    $('[data-tooltip]').popup({
        variation: 'very wide',
        hoverable: true,
        position: 'top center',
        delay: {
            show: 100,
            hide: 200
        }
    });

    // 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 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;
        }

        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>
</div>
@endsection
