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

@section('content')
<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);
    }
    @keyframes spin { 
        to { transform: rotate(360deg); } 
    }
    #loader {
        position: fixed;
        top: 0; left: 0;
        width: 100%; height: 100%;
        display: none;
        align-items: center; justify-content: center;
        background: rgba(0, 0, 0, 0.5);
        z-index: 9999;
    }
    #loader div {
        margin-top: 20%;
        margin-left:45%;
        width: 60px; height: 60px;
        border: 6px solid #fff;
        border-top: 6px solid transparent;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }
</style>

<div id="loader"><div></div></div>
<div class="ui container">
    <h2 class="ui header">Senarai Tuntutan</h2>

    @if(session('success'))
        <div class="ui positive message">
            {{ session('success') }}
        </div>
    @endif

    @foreach($claimsByMonth as $month => $claims)
    <h3 class="ui dividing header">{{ $month }}</h3>
    <table class="ui celled table">
        <thead>
            <tr>
                <th>No.</th>
                <th>Tarikh Tuntutan</th>
                <th>Nama Projek</th>
                <th>Jenis Kenderaan</th>
                <th>Jumlah Perbatuan</th>
                <th>Jumlah Tuntutan</th>
                <th>Status</th>
                <th>Tindakan</th>
            </tr>
        </thead>
        <tbody>
            @foreach($claims as $claim)
                <tr>
                    <td>{{ $loop->iteration }}</td>
                    <td>{{ $claim->claim_date }}</td>
                    <td>{{ $claim->project->p_project_description ?? '-' }}</td>
                    <td>{{ $claim->jenisKenderaan->name ?? '-' }}</td>
                    <td>{{ $claim->total_mileage ?? 0 }} km</td>
                    <td>RM {{ number_format($claim->total_claim_amount, 2) }}</td>
                    <td>{{ $claim->status }}</td>
                    <td>
                        <a href="{{ route('mileage::applications.show', $claim->id) }}" class="ui blue button tiny">
                            Lihat
                        </a>
                        @if($claim->status === 'Diproses')
                            <!-- Edit button (opens modal) -->
                            <button class="ui yellow button tiny editBtn" style="margin-bottom: 10px"
                                    data-id="{{ $claim->id }}"
                                    data-date="{{ $claim->claim_date }}"
                                    data-project="{{ $claim->project_id }}"
                                    data-vehicle="{{ $claim->jenis_kenderaan_id }}"
                                    data-description="{{ $claim->description }}"
                                    data-distanceto="{{ $claim->distance_to }}"
                                    data-mileage="{{ $claim->total_mileage }}"
                                    data-toll="{{ $claim->toll_amount }}"
                                    data-others="{{ $claim->others_amount }}"
                                    data-othersdesc="{{ $claim->others_description }}">
                                Kemaskini
                            </button>

                            <!-- Delete button -->
                            <form action="{{ route('mileage::applications.destroy', $claim->id) }}" method="POST" style="display:inline;">
                                @csrf
                                @method('DELETE')
                                <button type="submit" class="ui red button tiny" onclick="return confirm('Are you sure you want to delete this claim?')">Padam</button>
                            </form>
                        @endif
                    </td>
                </tr>
            @endforeach
        </tbody>
    </table>
@endforeach
</div>

<div id="loader"><div></div></div>
<!-- Edit Modal -->
<div id="editModal" class="ui modal">
  <i class="close icon"></i>
  <div class="header">Kemaskini Tuntutan</div>
  <div class="content">
    <form class="ui form" id="editForm" method="POST">
        @csrf
        @method('PUT')

        <input type="hidden" id="editId" name="id">

        <div class="field">
            <label>Tarikh Tuntutan</label>
            <input type="date" name="claim_date" id="editDate">
        </div>

        <div class="field">
          <label>Nama Projek</label>
          <select class="ui dropdown" name="project_id" id="editProject">
            @foreach($projects as $project)
              <option value="{{ $project->id }}">{{ $project->p_project_description }}</option>
            @endforeach
          </select>
        </div>

        <div class="field">
            <label>Jenis Kenderaan</label>
            <select class="ui dropdown" name="jenis_kenderaan_id" id="editVehicle">
                @foreach($jenisKenderaan as $vehicle)
                <option value="{{ $vehicle->id }}">{{ $vehicle->name }}</option>
                @endforeach
            </select>
        </div>

        <div class="field">
          <label>Butiran Tuntutan</label>
          <input type="text" name="description" id="editDescription">
        </div>

        <div class="field">
            <label>Jarak Ke</label>
            <input type="text" name="distance_to" id="editDistanceTo">
        </div>

        <div class="field">
          <label>Jumlah Perbatuan (KM)</label>
          <input type="number" name="total_mileage" id="editDistance">
        </div>

        <div class="field">
          <label>Toll (RM)</label>
          <input type="number" name="toll_amount" id="editToll">
        </div>

        <div class="field">
          <label>Lain-lain (RM)</label>
          <input type="number" name="others_amount" id="editOthers">
        </div>
     
        <div class="field">
            <label>Butiran Lain-lain</label>
            <input type="text" name="others_description" id="editOthersDescription">
        </div>

        <button type="submit" class="ui green button">Kemaskini</button>
    </form>
  </div>
</div>

<!-- Script to handle modal -->
<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() {
    // Ensure ajax sends X-CSRF-TOKEN
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    // initialize Semantic UI dropdowns and modal
    $('.ui.dropdown').dropdown();
    $('#editModal').modal({ autofocus: false });

    // delegate click (works if rows are dynamic)
    $(document).on('click', '.editBtn', function() {
        // quick debug: uncomment if modal doesn't open
        // console.log('Edit clicked', $(this).data());

        let $btn = $(this);
        let id = $btn.data('id');
        let date = $btn.data('date');
        let project = $btn.data('project');
        let vehicle = $btn.data('vehicle');
        let description = $btn.data('description');
        let distanceTo = $btn.data('distanceto');
        let mileage = $btn.data('mileage');
        let toll = $btn.data('toll');
        let others = $btn.data('others');
        let othersdesc = $btn.data('othersdesc');

        // set simple inputs
        $('#editId').val(id);
        $('#editDate').val(date || '');
        $('#editDescription').val(description || '');
        $('#editDistanceTo').val(distanceTo || '');
        $('#editDistance').val(mileage ?? '');
        $('#editToll').val(toll ?? '');
        $('#editOthers').val(others ?? '');
        $('#editOthersDescription').val(othersdesc ?? '');

        // set semantic ui dropdown selected values
        $('#editProject').dropdown('set selected', project || '');
        $('#editVehicle').dropdown('set selected', vehicle || '');

        if (others && others > 0) {
            $('#editOthersDescription').prop('readonly', false);
        } else {
            $('#editOthersDescription').val('').prop('readonly', true);
        }

        // show modal
        $('#editModal').modal('show');
    });

    // AJAX submit update (uses route() helper safely by replacing :id)
    $('#editForm').submit(function(e) {
        e.preventDefault();

        let id = $('#editId').val();
        let date = $('#editDate').val();
        let project = $('#editProject').val();
        let vehicle = $('#editVehicle').val();
        let description = $('#editDescription').val();
        let distanceTo = $('#editDistanceTo').val();
        let mileage = $('#editDistance').val();
        let toll = $('#editToll').val();
        let others = $('#editOthers').val();
        let othersDesc = $('#editOthersDescription').val();

        // check required fields
        if (!date || !project || !vehicle || !description || !mileage) {
            alert('Sila isi semua ruangan wajib.');
            return;
        }

        // check Butiran Lain-lain rule
        if (others && others > 0 && (!othersDesc || othersDesc === '-')) {
            alert('Sila isi Butiran Lain-lain kerana anda mempunyai jumlah Lain-lain.');
            return;
        }

        let formData = $(this).serialize(); // contains _token

        $.ajax({
            url: "{{ route('mileage::applications.update', ':id') }}".replace(':id', id),
            type: 'POST',
            data: formData + '&_method=PUT',
            beforeSend: function() {
                $('#editModal').modal('hide');
                $("#loader").show();
            },
            complete: function() {
                $("#loader").hide();
            },
            success: function(response) {
                if (response && response.success) {
                    alert(response.message || 'Claim updated successfully');
                    setTimeout(function() {
                        location.reload();
                    }, 300);
                } else {
                    alert('Unexpected response from server.');
                }
            },
            error: function(xhr) {
                let msg = "Update failed.";
                if (xhr.responseJSON) {
                    if (xhr.responseJSON.message) msg = xhr.responseJSON.message;
                    else if (xhr.responseJSON.errors) {
                        let errors = xhr.responseJSON.errors;
                        msg = Object.keys(errors).map(k => errors[k][0]).join("\n");
                    }
                } else {
                    msg = xhr.status + ' ' + xhr.statusText;
                }
                alert(msg);
            }
        });
    });
});
</script>

@endsection
