<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;   /* never exceed viewport */
            overflow-x: hidden;           /* cut accidental overflow */
            padding: 0 5rem 0 2rem;          /* breathing space from right */
            box-sizing: border-box;       /* include padding in width calc */
        }
        
        .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;              /* allow wrapping instead of pushing right */
            gap: 0.5rem;                  /* spacing between label & field */
            width: 100%;                  /* force row within parent */
            box-sizing: border-box;
        }

        .ui.form .inline.field > label.three-wide {
            flex: 0 0 2rem;              /* reserve space for label */
            margin-right: 50px;
            max-width: 30%;               /* but never hog the full row */
            min-width: 8rem;
            white-space: normal;
            word-break: break-word; 
        }

        .ui.form .inline.field .eight.wide.field {
            flex: 1 1 auto;               /* take remaining space */
            min-width: 0;                 /* shrink properly */
            max-width: 100%;              /* don’t spill outside */
            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;
            }
        }

    </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>Maklumat Tuntutan</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">Nama Projek<font color="red">*</font></label>
                                    <select class="ui search dropdown eight wide field form-control" name="project_id" id="project_select" required>
                                        <option value="">Sila 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 Tuntutan<font color="red">*</font></label>
                                    <input class="eight wide field" name="description" type="text" placeholder="Cth: Mesyuarat Projek B" 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 PPJ" 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.50" 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: 15.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: 0.00">
                                </div>
                                <div class="inline field required" 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>

                    {{-- Rumusan Tuntutan --}}
                    <div class="ui segment">
                        <p>Rumusan Pengiraan Tuntutan</p>
                        <div class="ui segment">
                            <table class="ui celled table">
                                <tbody>
                                    <tr>
                                        <td>Jumlah Perbatuan Layak Tuntut</td>
                                        <td id="claimable_mileage">0 KM</td>
                                    </tr>
                                    <tr>
                                        <td>Jumlah Tuntutan Perjalanan <span id="mileage_rate_label"></span></td>
                                        <td id="mileage_claim_amount">RM 0.00</td>
                                    </tr>
                                    <tr>
                                        <td>Toll (RM)</td>
                                        <td id="toll_claim_amount">RM 0.00</td>
                                    </tr>
                                    <tr>
                                        <td>Lain-lain (RM)</td>
                                        <td id="others_claim_amount">RM 0.00</td>
                                    </tr>
                                    <tr>
                                        <td>Penalti (RM) (Jika Ada)</td>
                                        <td id="penalty_claim_amount">RM 0.00</td>
                                    </tr>
                                    <tr>
                                        <td>Sebab Penalti (Jika Ada)</td>
                                        <td id="penalty_reason">-</td>
                                    </tr>
                                    <tr>
                                        <td><strong>Jumlah Keseluruhan Tuntutan (RM)</strong></td>
                                        <td><strong id="total_claim_amount">RM 0.00</strong></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Hidden inputs to send calculated values to server -->
                    <input type="hidden" name="user_id" id="user_id_input" value="{{ auth()->user()->id }}">
                    <!-- <input type="hidden" name="staff_id" id="staff_id_input" value="{{ auth()->user()->employeeCode }}"> -->
                    <input type="hidden" name="claimable_mileage" id="claimable_mileage_input" value="0">
                    <input type="hidden" name="mileage_claim_amount" id="mileage_claim_amount_input" value="0.00">
                    <input type="hidden" name="total_claim_amount" id="total_claim_amount_input" value="0.00">
                    <input type="hidden" name="toll_amount" id="toll_amount_input" value="0.00">
                    <input type="hidden" name="others_amount" id="others_amount_input" value="0.00">
                    <input type="hidden" name="penalty_amount" id="penalty_amount_input" value="0.00">
                    <input type="hidden" name="penalty_reason" id="penalty_reason_input" value="-">

                    <button class="ui primary button blue" type="submit" id="btn_hantar">Seterusnya</button>
                </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 src="https://cdnjs.cloudflare.com/ajax/libs/jquery.blockUI/2.70/jquery.blockUI.js"></script>

    <script>
        $(document).ready(function() {
            // Initialize dropdowns & calendar
            $('.ui.dropdown').dropdown();
            $('#claim_date').calendar({
                type: 'date',
                maxDate: new Date(), // Prevent selecting future dates
                formatter: {
                    date: function (date) {
                        if (!date) return '';
                        let day = date.getDate();
                        let month = date.getMonth() + 1;
                        let year = date.getFullYear();
                        return year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
                    }
                },
                onChange: function(date, text) {
                    $('#date').val(text);
                }
            });

            // Calculate total claim
            $('#total_mileage, #toll_amount, #others_amount, #jenis_kenderaan_id').on('input change', function() {
                calculateTotalClaim();
            });

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

            function calculateTotalClaim() {
                const vehicleType = $('#jenis_kenderaan_id').val();
                let mileage = parseFloat($('#total_mileage').val()) || 0;
                const toll = parseFloat($('#toll_amount').val()) || 0;
                const others = parseFloat($('#others_amount').val()) || 0;

                const vehicleRates = {
                    '1': { type: 'Kereta', baseRate: 0.55, higherMileageRate: 0.50 },
                    '2': { type: 'Motosikal', baseRate: 0.30 }
                };

                let rate = 0, claimableMileage = 0, mileageClaimAmount = 0;

                if (vehicleRates[vehicleType]) {
                    claimableMileage = Math.max(0, mileage - 40);

                    if (vehicleRates[vehicleType].type === 'Kereta') {
                        if (claimableMileage <= 500) {
                            mileageClaimAmount = claimableMileage * vehicleRates[vehicleType].baseRate;
                        } else {
                            mileageClaimAmount = (500 * vehicleRates[vehicleType].baseRate) +
                                                ((claimableMileage - 500) * vehicleRates[vehicleType].higherMileageRate);
                        }
                    } else {
                        // Motosikal - flat rate
                        mileageClaimAmount = claimableMileage * vehicleRates[vehicleType].baseRate;
                    }
                }

                let rateLabel = "";

                if (vehicleRates[vehicleType]) {
                    claimableMileage = Math.max(0, mileage - 40);

                    if (vehicleRates[vehicleType].type === 'Kereta') {
                        if (claimableMileage <= 500) {
                            mileageClaimAmount = claimableMileage * vehicleRates[vehicleType].baseRate;
                            rateLabel = `(RM ${vehicleRates[vehicleType].baseRate.toFixed(2)}/km)`;
                        } else {
                            mileageClaimAmount = (500 * vehicleRates[vehicleType].baseRate) +
                                                ((claimableMileage - 500) * vehicleRates[vehicleType].higherMileageRate);
                            rateLabel = `(RM ${vehicleRates[vehicleType].baseRate.toFixed(2)}/km first 500km, RM ${vehicleRates[vehicleType].higherMileageRate.toFixed(2)}/km after)`;
                        }
                    } else {
                        mileageClaimAmount = claimableMileage * vehicleRates[vehicleType].baseRate;
                        rateLabel = `(RM ${vehicleRates[vehicleType].baseRate.toFixed(2)}/km)`;
                    }
                }

                // --- Penalty calculation ---
                let penalty = 0, penaltyReason = "-";
                const claimDate = $('#date').val();
                if (claimDate) {
                    const claimMoment = new Date(claimDate);
                    const now = new Date();

                    // calculate month difference
                    const monthsDiff = (now.getFullYear() - claimMoment.getFullYear()) * 12 +
                                    (now.getMonth() - claimMoment.getMonth());

                    if (monthsDiff <= 1) {
                        penalty = 0;
                        penaltyReason = "-";
                        $('#btn_hantar').prop('disabled', false);
                    } else if (monthsDiff > 1 && monthsDiff <= 3) {
                        penalty = mileageClaimAmount * 0.10;
                        penaltyReason = "Lewat hantar lebih 1 bulan tetapi ≤ 3 bulan (10%)";
                        $('#btn_hantar').prop('disabled', false);
                    } else if (monthsDiff > 3 && monthsDiff <= 6) {
                        penalty = mileageClaimAmount * 0.30;
                        penaltyReason = "Lewat hantar lebih 3 bulan tetapi ≤ 6 bulan (30%)";
                        $('#btn_hantar').prop('disabled', false);
                    } else if (monthsDiff > 6) {
                        penaltyReason = "Lewat lebih 6 bulan - Tertakluk kepada budi bicara Lembaga Pengarah";
                        $('#btn_hantar').prop('disabled', true);
                        showCustomAlert("Tuntutan lebih daripada 6 bulan tidak boleh dihantar. Sila rujuk Lembaga Pengarah.");
                    }


                }

                const totalClaim = mileageClaimAmount + toll + others - penalty;

                // Update visible summary
                $('#claimable_mileage').text(claimableMileage.toFixed(2) + ' KM');
                $('#mileage_claim_amount').text('RM ' + mileageClaimAmount.toFixed(2));
                $('#mileage_rate_label').text(rateLabel);
                $('#toll_claim_amount').text('RM ' + toll.toFixed(2));
                $('#others_claim_amount').text('RM ' + others.toFixed(2));
                $('#penalty_claim_amount').text('RM ' + penalty.toFixed(2));
                $('#penalty_reason').text(penaltyReason);
                $('#total_claim_amount').text('RM ' + totalClaim.toFixed(2));

                // Update hidden inputs
                $('#claimable_mileage_input').val(claimableMileage.toFixed(2));
                $('#mileage_claim_amount_input').val(mileageClaimAmount.toFixed(2));
                $('#toll_amount_input').val(toll.toFixed(2));
                $('#others_amount_input').val(others.toFixed(2));
                $('#total_claim_amount_input').val(totalClaim.toFixed(2));
                $('#penalty_amount_input').val(penalty.toFixed(2));
                $('#penalty_reason_input').val(penaltyReason);
            }


            // show modal on form submit, but prevent regular submit
            $('#claimForm').on('submit', function(e) {
                e.preventDefault();

                // client-side required checks (keep yours or extend)
                const requiredFields = [
                    '#date',
                    '#jenis_kenderaan_id',
                    'input[name="description"]',
                    'select[name="distance_from"]',
                    'input[name="distance_to"]',
                    '#total_mileage',
                    '#project_select'
                ];
                let allFieldsFilled = requiredFields.every(field => {
                    const val = $(field).val();
                    return val !== null && val.toString().trim() !== '';
                });
                if (!allFieldsFilled) {
                    showCustomAlert("Sila isi semua maklumat yang bertanda *");
                    return;
                }


                // build modal HTML (remove previous first)
                $('#claimSummaryModal').remove();
                const claimDate = $('#date').val();
                const vehicleTypeText = $('#jenis_kenderaan_id option:selected').text();
                const projectText = $('#project_select option:selected').text();
                const description = $('input[name="description"]').val();
                const distanceFrom = $('select[name="distance_from"] option:selected').text();
                const distanceTo = $('input[name="distance_to"]').val();
                const claimableMileage = $('#claimable_mileage_input').val() || '0';
                const mileageClaimAmount = $('#mileage_claim_amount_input').val() || '0.00';
                const toll = $('#toll_amount_input').val() || '0.00';
                const others = $('#others_amount_input').val() || '0.00';
                const penalty = parseFloat($('#penalty_claim_amount').text().replace('RM ', '')) || 0;
                const penaltyReason = $('#penalty_reason').text() || "-";
                const totalClaim = $('#total_claim_amount_input').val() || '0.00';

                const summaryHtml = `
                    <div class="ui large modal" id="claimSummaryModal">
                        <div class="header">Ringkasan Tuntutan Anda</div>
                        <div class="content">
                            <p><strong>Tarikh:</strong> ${claimDate}</p>
                            <p><strong>Jenis Kenderaan:</strong> ${vehicleTypeText}</p>
                            <p><strong>Projek:</strong> ${projectText}</p>
                            <p><strong>Butiran Tuntutan:</strong> ${description}</p>
                            <p><strong>Dari:</strong> ${distanceFrom}</p>
                            <p><strong>Ke:</strong> ${distanceTo}</p>
                            <p><strong>Jumlah Perbatuan Layak Tuntut:</strong> ${claimableMileage} KM</p>
                            <p><strong>Jumlah Tuntutan Perjalanan:</strong> RM ${parseFloat(mileageClaimAmount).toFixed(2)}</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>${$('#others_description').val() ? `(${ $('#others_description').val() })` : '' }</p>
                            <p><strong>Penalti (Jika Ada):</strong> ${$('#penalty_claim_amount').text()}</p>
                            <p><strong>Sebab Penalti:</strong> ${$('#penalty_reason').text()}</p>
                            <p><strong>Jumlah Keseluruhan Tuntutan:</strong> RM ${parseFloat(totalClaim).toFixed(2)}</p>
                        </div>
                        <div class="actions">
                            <div class="ui button" id="editClaim">Edit</div>
                            <div class="ui green approve button" id="confirmClaim">Confirm</div>
                        </div>
                    </div>`;

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

                // show modal; onApprove -> do AJAX POST to store route, then redirect to show page
                $('#claimSummaryModal').modal({
                    onApprove: function() {
                        $('#claimForm')[0].submit(); // normal form submit
                        return false; // stop modal from auto-closing twice
                    }
                }).modal('show');

                // Edit: hide modal to edit fields
                $('#editClaim').on('click', function() {
                    $('#claimSummaryModal').modal('hide');
                });
            });
            calculateTotalClaim();
        });
    </script>
@endpush
