@section('meta')
<meta name="csrf-token" content="{{ csrf_token() }}">
@endsection

<div class="row">
    <div class="col-sm-12 col-md-8">
        <div class="card mt-3">
            <div class="card-header">
                <h5 class="mb-0">Wang Proses</h5>
            </div>

            <div class="card-body">
                <div class="form-group">
                    <label for="no_fail_lesen">No Fail Lesen</label>
                    <input type="text" class="form-control" id="no_fail_lesen" name="no_fail_lesen"
                    value="{{ old('no_fail_lesen', $permohonan->no_fail_lesen) }}" data-permohonan-id="{{ $permohonan->id }}" 
                    {{ !is_null($permohonan->no_fail_lesen) ? 'disabled' : '' }}   />
                    <small id="no_fail_status" class="text-muted"></small>
                </div> 
            @if(is_null($permohonan->no_resit_wang_proses()))
                <!-- PILIHAN JANA BIL -->
                <div class="mb-3">
                    <label class="form-label fw-bold">Cara Jana Bil</label>
                    <div class="d-flex gap-4">
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="cara_jana" id="cara_jana_mylesen">
                            <label class="form-check-label" for="cara_jana_mylesen">
                                Automatik (mylesen)
                            </label>
                        </div>

                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="cara_jana" id="cara_jana_epbt">
                            <label class="form-check-label" for="cara_jana_epbt">
                                Manual (epbt)
                            </label>
                        </div>
                    </div>
                </div>

                <!-- CARD GROUP -->
                <div class="card-group" id="janaBilGroup">

                    <!-- CARD 1: AUTOMATIK -->
                    <div class="card border-success me-2" id="cardAuto" style="display:none;">
                        <div class="card-header bg-success text-white py-2">Jana Bil Automatik</div>
                        <div class="card-body">

                            <form id="formMylesen">

                                <div class="mb-2">
                                    <label class="form-label">Keterangan</label>
                                    <input type="text" id="keterangan" class="form-control"
                                        value="PROSES PERMOHONAN LESEN PENJAJA SEMENTARA">
                                </div>

                                <div class="mb-2">
                                    <label class="form-label">Kod Hasil</label>
                                    <input type="text" id="kod_hasil" class="form-control"
                                        value="H72407">
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-2">
                                        <label class="form-label">Amaun (RM)</label>
                                        <input type="number" id="amaun" class="form-control"
                                            value="30">
                                    </div>

                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Kuantiti</label>
                                        <input type="number" id="qty" class="form-control"
                                            value="1" readonly>
                                    </div>
                                </div>

                                <button type="button" class="btn btn-success w-100"
                                        id="btnJanaBil">
                                    Jana Bil Automatik
                                </button>

                            </form>

                        </div>
                    </div>

                    <!-- CARD 2: MANUAL -->
                    <div class="card border-primary ms-2" id="cardManual" style="display:none;">
                        <div class="card-header bg-primary text-white py-2">Masukkan No Bil Manual</div>

                        <div class="card-body">
                            <form action="{{route('pt.simpan-wangproses')}}" method="post" id="formEPBT">
                                @csrf
                                <input type="hidden" name="permohonan_id" id="permohonan_id" value="{{$permohonan->id}}">

                                <label class="form-label">No Bil EPBT</label>

                                <div class="d-flex">
                                    <input type="text" id="no_bil_pelbagai" name="no_bil_pelbagai"
                                        class="form-control"
                                        placeholder="BPELxxx">

                                    <button type="submit"
                                            class="btn btn-primary ms-2"
                                            id="simpanbil"
                                            disabled>
                                        Simpan
                                    </button>
                                </div>

                            </form>
                        </div>
                    </div>

                </div>
            @endif
                <!-- SENARAI BIL -->
                <hr class="my-4">

                <h6 class="fw-bold">Senarai Bil</h6>

                <div class="row">
                    @foreach($permohonan->bilpelbagais as $bp)
                        <div class="col-md-4">
                            <div class="card border-info mb-3">
                                <div class="card-header fw-bold text-info">
                                <h6 class="card-title fw-bold text-info">Bil: {{ $bp->no_akaun_bilpelbagai }}</h6>
                                </div>
                                <div class="card-body">
                                    <p>{{ $bp->description }}</p>
                                    <div>Amaun: RM {{ number_format($bp->amaun_bil(), 2) }}</div>
                                </div>
                                <div class="card-footer">
                                    @if(is_null($bp->no_resit))
                                        
                                        <h6 class="card-title fw-bold text-danger">Belum Bayar</h6>
                                    @else
                                    <h6 class="card-title fw-bold text-success">RESIT : {{ $bp->no_resit }}</h6>
                                    @endif
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>

            </div>
        </div>
    </div>
    <div class="col-sm-12 col-md-4">
        <div class="card card-round">
            <div class="card-header">
                <div class="card-head-row card-tools-still-right">
                    <h4 class="card-title">Maklumat Fail</h4>
                </div>
            </div>        
            <div class="card-body"> 
@if(auth()->user()->hasRole(['pembantu tadbir', 'super'])&&($permohonan->status_progress == 'semakan bayaran proses'))            
                <form action="{{route('pt.simpan-nofail')}}" method="post">
                    @csrf
                    <input type="hidden" name="permohonan_id" id="permohonan_id" value="{{$permohonan->id}}">
                    @if(!is_null($permohonan->penempatan_id))
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="penempatan">Penempatan</label>
                                <input type="text" id="penempatan" class="form-control" readonly name="penempatan" value="{{$permohonan?->penempatan?->nama}}" >  
                            </div> 
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="no_petak">No Petak</label>
                                <input type="text" id="no_petak" class="form-control" name="no_petak" value="{{$permohonan?->no_petak}}" >  
                            </div> 
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="kawasan">Kawasan</label>
                                <input type="text" id="kawasan" class="form-control" readonly name="kawasan" value="{{$permohonan?->kawasan->nama}}" >    
                            </div> 
                        </div>
                        <div class="col-6">
                            <div class="form-group">
                                <label for="taman">Taman</label>
                                <input type="text" id="taman" class="form-control" readonly name="taman" value="{{$permohonan?->taman->nama}}" >   
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="form-group">
                                <label for="jalan">Jalan</label>
                                <input type="text" id="jalan" class="form-control" readonly name="jalan" value="{{$permohonan?->jalan?->nama}}" >    
                            </div>
                        </div>
                    </div>
                    @else
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="kawasan">Kawasan</label>
                                <select id="kawasan" name="kawasan" class="form-select" required>
                                    @foreach($kawasans as $kawasan)
                                        <option value="{{$kawasan->id}}" {{ $permohonan?->kawasan_id == $kawasan->id ? 'selected' : ''}}>{{$kawasan->nama}}</option>
                                    @endforeach
                                </select>
                            </div> 
                        </div>
                        <div class="col-6">
                            <div class="form-group">
                                <label for="taman">Taman</label>
                                <select id="taman" name="taman" class="form-select"  >
                                    <option value="">{{$permohonan?->taman_id}}</option>    
                                    @foreach($tamans as $taman)
                                        <option value="{{$taman->id}}" {{ $permohonan?->taman_id == $taman->id ? 'selected' : ''}}>{{$taman->nama}}</option>
                                    @endforeach
                                </select>   
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="form-group">
                                <label for="jalan">Jalan</label>
                                <select id="jalan" class="form-select" name="jalan"  >
                                    <option value=""></option>    
                                    @foreach($jalans as $jalan)
                                        <option value="{{$jalan->id}}" {{ $permohonan?->jalan_id == $jalan->id ? 'selected' : ''}}>{{$jalan->nama}}</option>
                                    @endforeach
                                </select>   
                            </div>
                        </div>
                    </div>
                    @endif
                    <div class="form-group">
                        <label for="no_akaun_lesen">No Akaun Lesen</label>
                        <input type="text" class="form-control" id="no_akaun_lesen" name="no_akaun_lesen"
                        value="{{ old('no_akaun_lesen', $permohonan->no_akaun_lesen) }}" />
                    </div> 
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="jenis_jualan">Jenis Jualan</label>
                                <select id="jenis_jualan" name="jenis_jualan" class="form-select" required>
                                    <option value="">{{$permohonan?->jenis_jualan_id}}</option>    
                                    @foreach($jenis_jualans as $jenis_jualan)
                                        <option value="{{$jenis_jualan->id}}" {{ $permohonan?->jenis_jualan_id == $jenis_jualan->id ? 'selected' : ''}}>{{$jenis_jualan->nama}}</option>
                                    @endforeach
                                </select>  
                            </div> 
                        </div>
                    </div>
                    <div class="form-group">
                        <input id="simpannofail" class="btn btn-sm btn-secondary" type="submit" name="simpannofail" value="Simpan" />
                    </div>
                </form>
                <hr>
                <form action="{{route('pt.hantar-ppk')}}" method="post">
                        @csrf
                        <input type="hidden" name="permohonan_id" id="permohonan_id" value="{{$permohonan->id}}">
                        <div class="form-group">
                            <label class="form-check-label" for="flexRadioDefault1">
                                Serah kepada Penolong Pegawai Kesihatan
                            </label>
                        </div>
                        <div class="form-group">
                            <input id="simpan" class="btn btn-sm btn-secondary" type="submit" name="janabil" value="Hantar" />
                        </div> 
                    </div>
                </form>
  @else
  
                <div class="form-group">
                    <label for="no_fail_lesen">No Fail Lesen</label>
                    <input type="text" class="form-control" id="no_fail_lesen" disabled
                    value="{{ old('no_fail_lesen', $permohonan->no_fail_lesen) }}" />
                </div> 
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="jenis_perniagaan">Jenis Perniagaan</label>
                            <input type="text" class="form-control" id="jenis_perniagaan" disabled
                            value="{{ old('jenis_perniagaan', $permohonan->jenis_perniagaan) }}" />
                        </div> 
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="kodkawasan">Kawasan</label>
                            <input type="text" class="form-control" id="kodkawasan" disabled
                            value="{{ old('kodkawasan', $permohonan->kodkawasan) }}" />
                        </div>                         
                    </div>
                </div>
  @endif
            </div>
        </div>
    </div> <!-- /.col -->         
</div> <!--end::Row-->


@section('js')

@if(auth()->user()->hasRole(['pembantu tadbir', 'super'])&&($permohonan->status_progress == 'baru'))
<script>
    $(function () {

        function hideAll() {
            $("#cardAuto").hide();
            $("#cardManual").hide();
        }

        hideAll();

        // Auto
        $("#cara_jana_mylesen").on("click", function(){
            hideAll();
            $("#cardAuto").show();
        });

        // Manual
        $("#cara_jana_epbt").on("click", function(){
            hideAll();
            $("#cardManual").show();
        });

        // Enable simpan bila ada input
        $("#no_bil_pelbagai").on("keyup", function(){
            $("#simpanbil").prop("disabled", $(this).val().trim() === "");
        });

        // AJAX jana bil automatik
        $("#btnJanaBil").on("click", function(){

            let data = {
                _token: "{{ csrf_token() }}",
                permohonan_id: "{{ $permohonan->id }}",
                keterangan: $("#keterangan").val(),
                kod_hasil: $("#kod_hasil").val(),
                amaun: $("#amaun").val(),
                qty: $("#qty").val(),
            };

            $.post("{{ route('pt.jana-bil-automatik') }}", data, function(res){
                if(res.success){
                    alert("Bil dijana: " + res.message);
                    location.reload();
                } else {
                    alert("Gagal jana bil");
                }
            });
        });

    });

    $(function () {
        $.ajaxSetup({
            headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
        });

        let t = null;

        $('#no_fail_lesen').on('input', function () {
            const $el = $(this);
            const permohonanId = $el.data('permohonan-id');
            const noFailLesen = $el.val().trim();

            clearTimeout(t);
            t = setTimeout(function () {
                $('#no_fail_status').text('Menyimpan...');

                $.ajax({
                    url: `/lesen-penjaja/${permohonanId}/no-fail-lesen`,
                    method: 'POST',
                    dataType: 'json',
                    data: { no_fail_lesen: noFailLesen },
                    success: function (res) {
                        if (res.ok) {
                            $('#no_fail_status').text('Disimpan ✓');
                        } else {
                            $('#no_fail_status').text(res.message || 'Gagal simpan.');
                        }
                    },
                    error: function (xhr) {
                        let msg = 'Gagal simpan.';
                        if (xhr.status === 422 && xhr.responseJSON?.errors?.no_fail_lesen) {
                            msg = xhr.responseJSON.errors.no_fail_lesen[0];
                        } else if (xhr.responseJSON?.message) {
                            msg = xhr.responseJSON.message;
                        }
                        $('#no_fail_status').text(msg);
                    }
                });
            }, 400); // 0.4s debounce
        });
    });

   
</script>


@endif 

    @if(auth()->user()->hasRole(['pembantu tadbir', 'super'])&&($permohonan->status_progress == 'semakan bayaran proses'))
<script>
    function loadKawasan() {
        $.getJSON('/get_kawasan', function(data) {
            $('#kawasan').append('<option value="">-- Sila Pilih Kawasan --</option>');
            data.forEach(k => {
                $('#kawasan').append(
                    $('<option>', {
                        value: k.id,
                        text: k.nama,
                        selected: k.id == defaultKawasanId
                    })
                );
            });

            if (defaultKawasanId && defaultTamanId) {
                loadTaman(defaultKawasanId, defaultTamanId);
            }
        });
    }

    function loadTaman(kawasanId, selectedId = null, done = null) {
        $.getJSON('/get_taman', { kawasan_id: kawasanId }, function(data) {
            $('#taman').empty().append('<option value="">-- Sila Pilih Taman --</option>');
            data.forEach(t => {
                $('#taman').append(
                    $('<option>', {
                        value: t.id,
                        text: t.nama,
                        selected: selectedId && (String(t.id) === String(selectedId))
                    })
                );
            });

            $('#taman').prop('disabled', false);

            // Kekalkan logic asal (default jalan) kalau kau still guna untuk edit page
            if (selectedId && typeof defaultJalanId !== 'undefined' && defaultJalanId) {
                loadJalan(selectedId, defaultJalanId);
            }

            if (typeof done === 'function') done();
        });
    }

    function loadJalan(tamanId, selectedId = null, done = null) {
        $.getJSON('/get_jalan', { taman_id: tamanId }, function(data) {
            $('#jalan').empty().append('<option value="">-- Sila Pilih Jalan --</option>');
            data.forEach(j => {
                $('#jalan').append(
                    $('<option>', {
                        value: j.id,
                        text: j.nama,
                        selected: selectedId && (String(j.id) === String(selectedId))
                    })
                );
            });
            $('#jalan').prop('disabled', false);

            if (typeof done === 'function') done();
        });
    }

    /* === EVENT LISTENER KAWASAN/TAMAN/JALAN === */

    $("#kawasan").change(function() {
        let kawasanId = $(this).val();

        $('#taman').empty().append('<option value="">-- Sila Pilih Taman --</option>').prop('disabled', !kawasanId);
        $('#jalan').empty().append('<option value="">-- Sila Pilih Jalan --</option>').prop('disabled', true);

        if (kawasanId) loadTaman(kawasanId);
    });

    $("#taman").change(function() {
        let tamanId = $(this).val();
        let namaTaman = $(this).find("option:selected").text() || '';
        let namaKawasan = $("#kawasan option:selected").text() || '';

        $('#jalan').empty().append('<option value="">-- Sila Pilih Jalan --</option>').prop('disabled', !tamanId);

        if (tamanId) {
            loadJalan(tamanId);

            // kalau ada penempatan, gabung bagi geocode lagi tepat
            const q = namaTaman ? (namaTaman + "," + namaKawasan) : false;
            if (q) {
                $("#searchBox").val(q);
                cariKoordinat();
            }
        }
    });

    $("#jalan").change(function() {
        let textJalan = $(this).find("option:selected").text() || '';
        let textTaman = $("#taman option:selected").text() || '';

        if (textJalan) {
            // susunan boleh ikut taste; ni aku letak jalan+taman+penempatan
            const parts = [textJalan, textTaman].filter(Boolean);
            $("#searchBox").val(parts.join(", "));
            cariKoordinat();
        }
    });

</script>


  @endif
@endsection