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

@push('style')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fomantic-ui/2.9.3/semantic.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;
    }
</style>
@endpush

@section('content')
<div class="ui container">
    <div class="ui segments">
        <div class="ui segment">
            <h2 class="ui header" style="margin: 10px">Permohonan Tuntutan Perjalanan</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>

                            {{-- optional project picker --}}
                            <div class="inline field">
                                <label class="three-wide field required">Nama Projek</label>
                                <select class="ui search dropdown eight wide field" name="project_id" id="project_id" required>
                                    <option value="">Pilih Projek</option>
                                    @foreach($projects as $project)
                                        <option value="{{ $project->id }}">{{ $project->p_project_description }}</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">
                                    <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">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://cdnjs.cloudflare.com/ajax/libs/fomantic-ui/2.9.3/semantic.min.js"></script>

<script>
$(document).ready(function() {
    // --- Modal on load ---
    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();
            $('#claim_date').calendar({
                type: 'date',
                maxDate: new Date(),
                formatter: {
                    date: function(date) {
                        if (!date) return '';
                        let d = date.getDate();
                        let m = date.getMonth() + 1;
                        let y = date.getFullYear();
                        return `${y}-${m<10?'0':''}${m}-${d<10?'0':''}${d}`;
                    }
                }
            });
        }
    }).modal('show');

    // --- Calculation ---
    function calculateTotals() {
        const mileage = parseFloat($('#total_mileage').val()) || 0;
        const claimable = Math.max(0, mileage - 40);
        const toll = parseFloat($('#toll_amount').val()) || 0;
        const others = parseFloat($('#others_amount').val()) || 0;
        const total = toll + others;

        $('#claimable_mileage_formula').text(`${mileage.toFixed(2)} - 40 = ${claimable.toFixed(2)} KM`);
        $('#toll_claim').text(`RM ${toll.toFixed(2)}`);
        $('#others_claim').text(`RM ${others.toFixed(2)}`);
        $('#total_claim').text(`RM ${total.toFixed(2)}`);

        $('#claimable_mileage_input').val(claimable.toFixed(2));
    }

    $('#total_mileage, #toll_amount, #others_amount').on('input', function() {
        calculateTotals();
        const othersVal = parseFloat($('#others_amount').val()) || 0;
        if (othersVal > 0) {
            $('#others_description_wrapper').slideDown();
            $('#others_description').prop('required', true);
        } else {
            $('#others_description_wrapper').slideUp();
            $('#others_description').prop('required', false).val('');
        }
    });

    // --- summary Modal ---
    $('#claimForm').on('submit', function(e) {
        e.preventDefault();

        // ✅ Project validation check
        const projectId = $('#project_id').val();
        if (!projectId || projectId === "") {
            $('body').toast({
                class: 'error',
                message: 'Sila pilih projek sebelum menghantar tuntutan.',
                showProgress: 'bottom'
            });
            $('#project_id').closest('.field').addClass('error');
            return false;
        } else {
            $('#project_id').closest('.field').removeClass('error');
        }

        const project = $('#project_id option:selected').text();
        const claimDate = $('#date').val();
        const vehicle = $('#jenis_kenderaan_id option:selected').text();
        const desc = $('input[name="description"]').val();
        const from = $('select[name="distance_from"] option:selected').text();
        const to = $('input[name="distance_to"]').val();
        const mileage = $('#total_mileage').val();
        const claimable = $('#claimable_mileage_input').val();
        const toll = $('#toll_amount').val() || 0;
        const others = $('#others_amount').val() || 0;
        const othersDesc = $('#others_description').val() || '-';

        // Remove previous modal if any
        $('#claimSummaryModal').remove();

        const summaryModal = `
            <div class="ui modal" id="claimSummaryModal">
                <div class="header">Ringkasan Tuntutan Anda</div>
                <div class="content">
                    <p><strong>Tarikh:</strong> ${claimDate}</p>
                    <p><strong>Jenis Kenderaan:</strong> ${vehicle}</p>
                    <p><strong>Nama Projek:</strong> ${project}</p>
                    <p><strong>Butiran:</strong> ${desc}</p>
                    <p><strong>Dari:</strong> ${from}</p>
                    <p><strong>Ke:</strong> ${to}</p>
                    <p><strong>Jumlah Perbatuan:</strong> ${mileage} KM</p>
                    <p><strong>Layak Dituntut:</strong> ${mileage} - 40 = ${claimable} KM</p>
                    <p><strong>Toll:</strong> RM ${parseFloat(toll).toFixed(2)}</p>
                    <p><strong>Lain-lain:</strong> RM ${parseFloat(others).toFixed(2)}</p>
                    <p><strong>Butiran Lain-lain:</strong> ${othersDesc}</p>
                </div>
                <div class="actions">
                    <div class="ui grey button" id="editClaim"><i class="arrow left icon"></i> Edit</div>
                    <div class="ui green approve button"><i class="check icon"></i> Hantar</div>
                </div>
            </div>`;

        $('body').append(summaryModal);

        $('#claimSummaryModal').modal({
            closable: false,
            onApprove: function() {
                $('#claimForm')[0].submit();
                return false;
            }
        }).modal('show');

        $(document).off('click', '#editClaim').on('click', '#editClaim', function() {
            $('#claimSummaryModal').modal('hide');
        });
    });
});
</script>
@endpush
