@extends('layouts.app_operasi')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="card">

                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb pb-3">
                      <li class="breadcrumb-item"><a href="{{ url('/') }}">Home</a></li>
                      <li class="breadcrumb-item active" aria-current="page">Komoditi</li>
                    </ol>
                </nav>

                <div class="card-body">
                    <div class="row">
                        <div class="col-2 justify-content-start">
                        </div>
                    </div>
                    <div class="row form-group" id="maklumat_komuditi">
                        <div class="col-md-5">
                            <div class="row form-group">
                                <div class="col-md-4 text-right">No Sijil : </div>
                                <div class="col-md-8"><span id="nosijil_span"></span></div>
                            </div>
                            <div class="row form-group">
                                <div class="col-md-4 text-right">Harga : </div>
                                <div class="col-md-8"><span id="harga_span"></span></div>
                            </div>
                            <div class="row form-group">
                                <div class="col-md-4 text-right">Limit Komoditi : </div>
                                <div class="col-md-8">{{ 'RM ' . number_format($min_komoditi) }}</div>
                            </div>
                        </div>
                        <div class="col-md-7">
                            <div class="row form-group">
                                <div class="col-md-4 text-right">Kod Produk / Diskripsi : </div>
                                <div class="col-md-8"><span id="produk_span"></span></div>
                            </div>
                            <div class="row form-group">
                                <div class="col-md-4 text-right">Unit : </div>
                                <div class="col-md-8"><span id="unit_span"></span></div>
                            </div>
                            <div class="row form-group">
                                <div class="col-md-4 text-right">Baki Nilai Komoditi : </div>
                                <div class="col-md-8"><span id="nilai_span"></span></div>
                            </div>
                        </div>
                    </div>
                    <div class="row justify-content-center" id="tiada_komuditi">
                        <div class="col-12 text-center">
                            <p>Tiada Komoditi</p>
                        </div>
                        <div class="col-md-5">
                            <div class="row form-group">
                                <div class="col-md-4 text-right">Limit Komoditi : </div>
                                <div class="col-md-8">{{ 'RM ' . number_format($min_komoditi) }}</div>
                            </div>
                        </div>
                    </div>
                    <div class="row form-group justify-content-center">
                        <input type="hidden" value="{{ $user_name }}" id="user_name" name="user_name">
                        <button class="btn btn-primary mr-2" id="pembelian">Pembelian Komoditi</button>
                        <button class="btn btn-danger mr-2" id="penjualan">Penjualan Komoditi</button>
                        <a class="btn btn-primary mr-2" href="{{ route('rekod.komoditi') }}">Rekod Transaksi Komoditi</a>
                        <button class="btn btn-danger mr-2" id="limit_komoditi">Ubah Limit Komoditi</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">{{ __('Rekod Pembelian/Penjualan Komoditi') }}</div>
                <div class="card-body text-center">
                    <div class="row justify-content-between mb-4">
                        <div class="col text-left">
                            <div class="form-group d-flex align-items-center">
                                <label for="limit-komoditi" style="width: 600px" class="mb-0">Had Paparan Rekod Komoditi</label>
                                <select onchange="loadKomoditiRecord()" name="limit_view" id="limit_view" class="form-control">
                                  <option selected value="20">20</option>
                                  <option value="100">100</option>
                                  <option value="500">500</option>
                                  <option value="1000">1000</option>
                                  <option disabled>Untuk rekod keseluruhan, sila print</option>
                                </select>
                              </div>
                        </div>
                        <div class="col text-right">
                            <a href="{{ route('laporan.komoditi') }}" target="_blank" class="btn btn-primary" title="Cetak Rekod Jual/Beli Komoditi"><i class="fa fa-print" aria-hidden="true"></i></a>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <div class="spinner-border" role="status" id="loading-spinner">
                                <span class="sr-only">Loading...</span>
                              </div>
                            <table id="rekod_komuditi" class="table table-striped table-hover">
                                <thead class="thead-dark">
                                    <tr>
                                        <th>Bil</th>
                                        <th>No Sijil</th>
                                        <th>Tarikh</th>
                                        <th>Masa</th>
                                        <th>Nilai Komoditi</th>
                                        <th>Transaksi Oleh</th>
                                        <th>Transaksi</th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="pembelian_modal" tabindex="-1" data-backdrop="static"  aria-labelledby="ModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="ModalLabel">Pembelian Komoditi</h5>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-12">
                        <div class="row form-group">
                            <div class="col-md-4">No Sijil</div>
                            <div class="col-md-8">
                                <input type="text" class="form-control" id="nosijil" name="nosijil">
                            </div>
                        </div>
                        <div class="row form-group">
                            <div class="col-md-4">Produk</div>
                            @php
                                $produk = Http::withOptions(['verify' => config('app.api_verify')])->get($api_url . '/api/komuditi/produk')->json();
                            @endphp
                            <div class="col-md-8">
                                <select name="produk" id="produk" class="form-control">
                                    <option disabled selected> -- Pilih Produk -- </option>
                                    @foreach($produk as $index=>$product)
                                        <option value="{{ $product['kodproduk'] }}">{{ $product['description'] }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="row form-group">
                            <div class="col-md-4">Unit</div>
                            <div class="col-md-8">
                                <input type="text" readonly class="form-control" id="unit" name="unit">
                            </div>
                        </div>
                        <div class="row form-group">
                            <div class="col-md-4">Harga</div>
                            <div class="col-md-8">
                                <input type="text" class="form-control" id="harga" name="harga">
                            </div>
                        </div>
                        <div class="row form-group">
                            <div class="col-md-4">Nilai</div>
                            <div class="col-md-8">
                                <input type="text" class="form-control" id="nilai" name="nilai">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <div class="form-group row">
                    <button type="button" class="btn btn-primary mr-md-2" name="terima_komuditi" id="terima_komuditi">Sahkan</button>
                    <button type="button" class="btn btn-danger" name="batal_komuditi" id="batal_komuditi" data-dismiss="modal">Batal</button>
                </div>
            </div>
            </form>
        </div>
    </div>
</div>
<div class="modal fade" id="limit_komoditi_modal" tabindex="-1" data-backdrop="static"  aria-labelledby="ModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form action="{{ route('komoditi.limit') }}" method="post">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title" id="ModalLabel">Ubah Limit Komoditi</h5>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="row form-group">
                                <div class="col-md-4">Limit Komoditi</div>
                                <div class="col-md-8">
                                    <input type="text" class="form-control" id="komoditi_limit" name="komoditi_limit">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <div class="form-group row">
                        <button type="submit" class="btn btn-primary mr-md-2" name="terima_komuditi_limit" id="terima_komuditi_limit">Sahkan</button>
                        <button type="button" class="btn btn-danger" name="batal_komuditi_limit" id="batal_komuditi_limit" data-dismiss="modal">Batal</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<div class="modal fade" id="detail_komuditi" tabindex="-1" data-backdrop="static"  aria-labelledby="ModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="ModalLabel">Detail Komoditi</h5>
            </div>
            <div class="modal-body">
                <div class="row form-group">
                    <div class="col-md-4">Kod Produk / Diskripsi : </div>
                    <div class="col-md-8"><span id="produk_span_modal"></span></div>
                </div>
                <div class="row form-group">
                    <div class="col-md-4">Unit : </div>
                    <div class="col-md-8"><span id="unit_span_modal"></span></div>
                </div>
                <div class="row form-group">
                    <div class="col-md-4">Harga : </div>
                    <div class="col-md-8"><span id="harga_span_modal"></span></div>
                </div>
            </div>
            <div class="modal-footer">
                <div class="form-group row">
                    <button type="button" class="btn btn-danger" name="tutup_komuditi" id="tutup_komuditi" data-dismiss="modal">Tutup</button>
                </div>
            </div>
            </form>
        </div>
    </div>
</div>
<script>
    let api_url = "{{ $api_url }}";

    var tablerekod = $('#rekod_komuditi').DataTable( {
        "pageLength": 1000,
        "bLengthChange": false,
    });

    $(document).ready( function () {
        checkKomuditi();
    });

    const formatter = new Intl.NumberFormat('en-US', {
        minimumFractionDigits: 2
    });

    $('#pembelian').on('click',function(){
        $('#pembelian_modal').modal('show');
    });

    $('#limit_komoditi').on('click',function(){
        $('#limit_komoditi_modal').modal('show');
    });

    $('#penjualan').on('click',function(){
        var nosijil = $('#nosijil_span').text();
        var baki_komoditi = $('#nilai_span').text();
        Swal.fire({
            title: 'Adakah anda setuju penjualan baki komoditi?',
            showCancelButton: true,
            confirmButtonText: `Setuju`,
            cancelButtonText: `Batal`,
        }).then((result) => {
            /* Read more about isConfirmed, isDenied below */
            console.log(result);
            if (result.isConfirmed) {
                $.ajax({
                    method:'post',
                    url: api_url + '/api/komuditi/jual',
                    datatype:'json',
                    data:{
                        'purchased_by': "{{ $user_name }}",
                        'nosijil': nosijil
                    },
                    success:function(data){
                        console.log(data);
                        if(data == 'berjaya'){
                            checkKomuditi();
                            Swal.fire({
                                icon: 'success',
                                title: 'Berjaya!',
                                text: 'Penjualan Unit Komuditi Berjaya'
                            });
                        }else{
                            checkKomuditi();
                            Swal.fire({
                                icon: 'error',
                                title: 'Amaran!',
                                text: 'Penjualan Unit Komuditi Tidak Berjaya'
                            });
                        }
                    }
                })
            } else if (result.isDismissed) {
                Swal.fire('Baki Komoditi Tidak Dijual', '', 'info')
            }
        })
    });

    $('#produk').change(function(){
        var produk = $('#produk').val();
        $.ajax({
            method:'get',
            url : api_url + '/api/komuditi/unit',
            dataType: 'json',
            data: {
                'kodproduk':produk
            },
            success:function(data){
                $('#unit').val(data)
            }
        });
    })

    function checkKomuditi(){
        $.ajax({
            method:'get',
            url: api_url + '/api/komuditi/check',
            success:function(data){
                var kodproduk = data['kodproduct'];
                $.ajax({
                    method:'get',
                    url : api_url + '/api/komuditi/description',
                    dataType : 'json',
                    data:{
                        'kodproduk': kodproduk
                    },
                    success:function(description){
                        var komuditi_semasa = Object.keys(description).length

                        if(komuditi_semasa == 0){
                            $('#maklumat_komuditi').hide();
                            $('#tiada_komuditi').show();
                            $('#penjualan').prop('disabled', true);
                            $('#pembelian').prop('disabled', false);
                        }else{
                            $('#maklumat_komuditi').show();
                            $('#tiada_komuditi').hide();
                            if(data['unit_komuditi'] == 0){
                                $('#penjualan').prop('disabled', true);
                                $('#pembelian').prop('disabled', false);
                            }else{
                                $('#penjualan').prop('disabled', false);
                                $('#pembelian').prop('disabled', true);
                            }
                        }
                        $('#nosijil_span').text(data['no_sijil'])
                        $('#harga_span').text('RM ' + formatter.format(data['nilai']))
                        $('#produk_span').text(description['kodproduk'] + ' / ' + description['description'])
                        $('#unit_span').text(description['unit'])
                        $('#nilai_span').text('RM ' + formatter.format(data['unit_komuditi']))
                    }
                })
            }
        });
        loadKomoditiRecord();
    }

    function loadKomoditiRecord()
    {
        var selectedLimitView = $('#limit_view').find(":selected").val();

        $('#loading-spinner').show();
        tablerekod.clear().draw();
        $.ajax({
            method:'get',
            url: api_url + '/api/komuditi/rekodkomuditi',
            data: {
                'limit_view': selectedLimitView,
            },
            success:function(rekod){
                var bilcount = 0;
                $.each(rekod,function(index,rekod_transaksi){
                    bilcount ++
                    tablerekod.row.add([
                        bilcount,
                        "<a data-toggle='modal' data-kodproduk='"+ rekod_transaksi['kodproduk'] +"' data-harga='" + rekod_transaksi['harga'] +"' data-target='#detail_komuditi' >"+rekod_transaksi['nosijil'] + '</a>',
                        rekod_transaksi['date_purchase'],
                        rekod_transaksi['time_purchase'],
                        formatter.format(rekod_transaksi['unit_komuditi']),
                        rekod_transaksi['transaction_by'],
                        rekod_transaksi['transaction_type']
                    ]).draw();
                });
                $('#loading-spinner').hide();
            }
        })
    }

    $('#detail_komuditi').on('show.bs.modal', function(event) {
        var button = $(event.relatedTarget);
        var kodproduk = button.data('kodproduk');
        var harga = button.data('harga');

        $.ajax({
            method:'get',
            url : api_url + '/api/komuditi/description',
            dataType : 'json',
            data:{
                'kodproduk': kodproduk
            },
            success:function(description){
                $('#harga_span_modal').text('RM ' + formatter.format(harga));
                $('#produk_span_modal').text(description['kodproduk'] + ' / ' + description['description']);
                $('#unit_span_modal').text(description['unit']);
            }
        })
    })

    $('#terima_komuditi').on('click',function(){
        var nosijil = $('#nosijil').val();
        var produk = $('#produk').val();
        var unit = $('#unit').val();
        var harga = $('#harga').val();
        var nilai = $('#nilai').val();

        $.ajax({
            method:'post',
            url: api_url + '/api/komuditi/pembelian',
            dataType : 'json',
            data:{
                'unit_komuditi' : nilai,
                'nilai' : harga,
                'nosijil' : nosijil,
                'kodproduct' : produk,
                'purchased_by' : "{{ $user_name }}"
            },
            success:function(data){
                checkKomuditi();
                $('#nosijil').val('');
                $("#produk").prop("selected", false);
                $('#unit').val('');
                $('#harga').val('');
                $('#nilai').val('');
                Swal.fire({
                    icon: 'success',
                    title: 'Berjaya!',
                    text: 'Pendahuluan Unit Komuditi Berjaya'
                });
                $('#pembelian_modal').modal('hide');
                komoditiNotify();
            }
        });
    });
    function komoditiNotify(){
        $.ajax({
            method:'get',
            url: "{{ route('beli.notifyKomoditi') }}",
            success:function(data){
                console.log('berjaya');
            }
        });
    }

</script>
@endsection
