<title>Form Tuntutan (Tanpa Projek)</title>
@extends('ui::layouts.app')

@push('style')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fomantic-ui@2.9.3/dist/semantic.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fomantic-ui@2.9.3/dist/components/calendar.min.css">
<style type="text/css">
    body { background-color: #f0f2f5; }

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

    .ui.segments { margin-top: 2rem; }
    .ui.segment { box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); }

    .ui.form .inline.field {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
        width: 100%;
        box-sizing: border-box;
    }

    .ui.form .inline.field > label.three-wide {
        flex: 0 0 2rem;
        margin-right: 50px;
        max-width: 30%;
        min-width: 8rem;
        white-space: normal;
        word-break: break-word;
    }

    .ui.form .inline.field .eight.wide.field {
        flex: 1 1 auto;
        min-width: 0;
        max-width: 100%;
        box-sizing: border-box;
    }

    @media (max-width: 768px) {
        .ui.form .inline.field { flex-direction: column !important; align-items: flex-start !important; }
        .ui.form .inline.field > label.three-wide,
        .ui.form .inline.field .eight.wide.field { width: 100% !important; max-width: 100% !important; }
    }

    /* Modal styling */
    #claimSummaryModal.ui.modal {
        width: 500px !important;
        max-width: 100vw !important;
        font-size: 0.9rem;
    }

    #claimSummaryModal .content { max-height: 500px; overflow-y: auto; }
    #claimSummaryModal .header { font-size: 1.1rem; }

    #supportingDocsModal.ui.basic.modal {
        left: calc(50% + 100px) !important;
        transform: translate(-50%, -50%) !important;
        width: 500px !important;
        margin-top: 25%;
    }

    #supportingDocsModal .content p { font-size: 16px; line-height: 1.6; color: white; }
    #supportingDocsModal .ui.icon.header { color: #b33a3a; font-size: 2rem; }
    #supportingDocsModal .ui.icon.header i.icon { font-size: 5rem; }
    #supportingDocsModal .actions .button {
        background: linear-gradient(135deg, #21ba45 0%, #16ab39 100%);
        color: white; border-radius: 10px;
        padding: 10px 20px; font-weight: 600;
    }

    .ui.calendar .disabled.day {
        color: #ccc !important;
        text-decoration: line-through;
    }
</style>
@endpush

@section('content')
@if (session('error'))
    <div class="ui negative message">
        <i class="close icon"></i>
        <div class="header">{{ session('error') }}</div>
    </div>
@endif
@if (session('success'))
    <div class="ui positive message">
        <i class="close icon"></i>
        <div class="header">{{ session('success') }}</div>
    </div>
@endif

<div class="ui container">
    <div class="ui segments">
        <div class="ui segment">
            <h2 class="ui header" style="margin: 10px">Permohonan Tuntutan Perjalanan (Tanpa Projek)</h2>
        </div>

        <div class="ui secondary segment">
            <form class="ui form" id="claimForm" action="{{ route('mileage::applications.store') }}" method="POST">
                @csrf

                {{-- Maklumat Tuntutan --}}
                <div class="ui segment">
                    <p><strong>Maklumat Tuntutan</strong></p>
                    <div class="ui segment">
                        <div class="ui form">

                            <div class="inline field required">
                                <label class="three-wide field">Tarikh</label>
                                <div class="eight wide field ui calendar" id="claim_date">
                                    <div class="ui input left icon">
                                        <i class="calendar icon"></i>
                                        <input type="text" name="claim_date" id="date" placeholder="Tarikh Tuntutan" required readonly>
                                    </div>
                                </div>
                            </div>

                            <div class="inline field required">
                                <label class="three-wide field">Jenis Kenderaan</label>
                                <select class="ui dropdown eight wide field" name="jenis_kenderaan_id" id="jenis_kenderaan_id" required>
                                    <option value="">Sila Pilih</option>
                                    @foreach($jenisKenderaan as $jk)
                                        <option value="{{ $jk->id }}">{{ $jk->name }}</option>
                                    @endforeach
                                </select>
                            </div>

                            <div class="inline field required">
                                <label class="three-wide field">Butiran</label>
                                <input class="eight wide field" name="description" type="text" placeholder="Cth: Mesyuarat Dalaman" required>
                            </div>

                            <div class="inline field required">
                                <label class="three-wide field">Jarak Dari</label>
                                <select class="ui search dropdown eight wide field" name="distance_from" required>
                                    <option value="">Sila Pilih Lokasi</option>
                                    <option value="Pejabat">Pejabat</option>
                                </select>
                            </div>

                            <div class="inline field required">
                                <label class="three-wide field">Jarak Ke</label>
                                <input class="eight wide field" name="distance_to" type="text" placeholder="Cth: Pejabat JKR" required>
                            </div>

                            <div class="inline field required">
                                <label class="three-wide field">Jumlah Perbatuan (KM)</label>
                                <input class="eight wide field" name="total_mileage" id="total_mileage" type="number" step="0.01" placeholder="Cth: 120" required>
                            </div>

                            <div class="inline field">
                                <label class="three-wide field">Toll (RM)</label>
                                <input class="eight wide field" name="toll_amount" id="toll_amount" type="number" step="0.01" placeholder="Cth: 10.00">
                            </div>

                            <div class="inline field">
                                <label class="three-wide field">Lain-lain (RM)</label>
                                <input class="eight wide field" name="others_amount" id="others_amount" type="number" step="0.01" placeholder="Cth: 5.00">
                            </div>

                            <div class="inline field" id="others_description_wrapper" style="display:none;">
                                <label class="three-wide field">Butiran Lain-lain</label>
                                <input class="eight wide field" name="others_description" id="others_description" type="text" placeholder="Nyatakan butiran lain-lain">
                            </div>
                        </div>
                    </div>
                </div>

                {{-- Ringkasan --}}
                <div class="ui segment">
                    <p><strong>Ringkasan Pengiraan</strong></p>
                    <div class="ui segment">
                        <table class="ui celled table">
                            <tbody>
                                <tr><td>Jumlah Perbatuan Layak Tuntut</td><td id="claimable_mileage_formula">0 - 40 = 0 KM</td></tr>
                                <tr><td>Toll (RM)</td><td id="toll_claim">RM 0.00</td></tr>
                                <tr><td>Lain-lain (RM)</td><td id="others_claim">RM 0.00</td></tr>
                                <tr>
                                    <td>
                                        <strong>Jumlah Tol dan Lain-lain</strong><br>
                                        <small>(Jumlah keseluruhan sebenar akan dikira di Senarai Tuntutan)</small>
                                    </td>
                                    <td>
                                        <strong id="total_claim_amount">RM 0.00</strong>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <button class="ui primary button blue" type="submit">
                    <i class="paper plane icon"></i> Hantar
                </button>

                <input type="hidden" name="claimable_mileage" id="claimable_mileage_input" value="0">
            </form>
        </div>
    </div>
</div>
@endsection

@push('script')
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/fomantic-ui@2.9.3/dist/semantic.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/fomantic-ui@2.9.3/dist/components/calendar.min.js"></script>

<script>
$(document).ready(function() {
    // Show / hide "Butiran Lain-lain" based on input
    function toggleOthersDescription() {
        const val = parseFloat($('#others_amount').val()) || 0;

        if (val > 0) {
            $('#others_description_wrapper').slideDown();
            $('#others_description').attr('required', true);
        } else {
            $('#others_description_wrapper').slideUp();
            $('#others_description').removeAttr('required').val('');
        }
    }

    // Run when user types
    $('#others_amount').on('input', toggleOthersDescription);

    // Run on page load in case editing
    toggleOthersDescription();

    // === Auto Calculation for Ringkasan Pengiraan ===
    function updateSummary() {
        const totalMileage = parseFloat($('#total_mileage').val()) || 0;
        const toll = parseFloat($('#toll_amount').val()) || 0;
        const others = parseFloat($('#others_amount').val()) || 0;

        let claimableMileage = 0;
        if (totalMileage > 40) claimableMileage = totalMileage - 40;

        let rate = 0.55;
        if (claimableMileage > 500) rate = 0.50;

        const mileageAmount = claimableMileage * rate;
        const totalClaim = mileageAmount + toll + others;

        $('#claimable_mileage_formula').text(`${totalMileage} - 40 = ${claimableMileage} KM`);
        $('#toll_claim').text(`RM ${toll.toFixed(2)}`);
        $('#others_claim').text(`RM ${others.toFixed(2)}`);
        $('#total_claim_amount').text(`RM ${totalClaim.toFixed(2)}`);
        $('#claimable_mileage_input').val(claimableMileage);
    }

    $('#total_mileage, #toll_amount, #others_amount').on('input', updateSummary);
    updateSummary();

    // === Modal Setup ===
    const modalHtml = `
        <div class="ui basic modal" id="supportingDocsModal">
            <div class="ui icon header">
                <i class="exclamation triangle icon"></i>
                Peringatan Penting
            </div>
            <div class="content" style="text-align:center;">
                <p>Dokumen sokongan seperti resit mesti dihantar kepada pihak Finance.<br>
                Jika <b>tidak</b>, tuntutan akan <b>DITOLAK</b>.</p>
            </div>
            <div class="actions" style="text-align:center;">
                <div class="ui green ok inverted button">
                    <i class="checkmark icon"></i> Saya Faham
                </div>
            </div>
        </div>`;
    $('body').append(modalHtml);

    $('#claimForm :input').prop('disabled', true);

    $('#supportingDocsModal').modal({
        closable: false,
        onApprove: function() {
            $('#claimForm :input').prop('disabled', false);
            $('.ui.dropdown').dropdown();

            setTimeout(() => {
                $('#claim_date').calendar({
                    type: 'date',
                    startMode: 'day',
                    touchReadonly: true,
                    monthFirst: false,
                    maxDate: new Date(),
                    disabledDates: [],
                    formatter: {
                        date: function(date) {
                            if (!date) return '';
                            const y = date.getFullYear();
                            const m = ('0' + (date.getMonth() + 1)).slice(-2);
                            const d = ('0' + date.getDate()).slice(-2);
                            return `${y}-${m}-${d}`;
                        }
                    }
                });
            }, 400);
        }
    }).modal('show');

});
</script>
@endpush
