@extends('layouts.nav')
@section('title')
{{$JournalType}} Receipt
@endsection
@section('content')

                    <!-- Page Heading -->
                    <div class="d-sm-flex align-items-center justify-content-between mb-4">
                        <h1 class="h3 mb-0 text-gray-800">{{$JournalType}}  Receipt</h1>
                      </div>


                      <div class="row">

                      <!-- Donut Chart -->
                      <div class="col-xl-4 col-lg-5">
                            <div class="card shadow mb-4">
                                <!-- Card Header - Dropdown -->
                                <div class="card-header py-3" style="height: 70px;">
                                    <h6 class="m-0 font-weight-bold text-primary"  id="formHeader">Process Receipt</h6>


                                </div>
                                <!-- Card Body -->
                                <div class="card-body">
                                @if (session('success'))
                            <div class="alert alert-success" id="successMessage"  style="margin: 20px;">
                                {{ session('success') }}
                            </div>
                        @endif

                        @if ($errors->any())

                                    <div class="form-group"  id="successMessage"  style="margin: 20px;">
                                        <div class="card bg-warning text-white shadow">
                                            <div class="card-body">

                                                @foreach ($errors->all() as $error)
                                                <div style="color: red; ">{{ $error }}</div>
                                                @endforeach

                                            </div>
                                        </div>
                                    </div>
                                    @endif
                            <form class="card-body" action="{{route('savereceipt')}}" method="post" id="accountTypeForm">
                            @csrf
                            <input type="hidden" id="accountId" name="id" value="">
                            <input type="hidden" id="source" name="source" value="{{$JournalType}}">
                            <div class="form-group">
                            <input type="hidden" class="form-control form-control-user" id="AccCode" placeholder="Control Account" name="AccCode"  value="{{ $journal }}" required readonly>
                             </div>
                             <div class="form-group">
                            <input type="text" class="form-control form-control-user" id="batch" placeholder="Receipt Number" name="batch"  value="{{ $batch }}" required {{ $batch == 'REC' ? '' : 'readonly' }}  onkeydown="preventRemoval(event)" oninput="enforcePrefixAndUpdateURL(this)">
                             </div>

                                <div class="form-group">
                                        <input type="date" class="form-control form-control-user" id="date" placeholder="Entry Date" name="date"  value="{{ old('date', \Carbon\Carbon::now()->format('Y-m-d')) }}" required>

                                </div>
                                <div class="form-group">
                                <input type="text" class="form-control form-control-user" id="mdes" placeholder="Main Description" name="mdes"  value="{{ $mdes }}" required>

                                </div>
                                <div class="form-group">
                                <select class="form-control form-control-user" id="account" name="account"  value="{{ old('account') }}"  required>
                                        <option value="" disabled selected>Select {{$JournalType}} Account</option>

                                        @foreach ($Accounts as $Account)

                                        <option value="{{ $Account->Code }}">{{ $Account->Code.'/'.$Account->Name }}</option>

                                        @endforeach
                                    </select>
                                </div>

                                <div class="form-group">
                                        <select class="form-control form-control-user"  id="reff" name="reff"  value="{{ old('reff') }}"  required>
                                        <option value="" disabled selected>Reference: {{$JournalType}} Invoice </option>

                                        @foreach ($Refs as $Ref)

                                        <option value="{{ $Ref->Batch }}">{{ $Ref->Batch}}</option>

                                        @endforeach
                                    </select>
                                </div>
                                <div class="form-group">
                                        <input type="text" class="form-control form-control-user" id="narr" placeholder="Description" name="narr"  value="{{ old('narr') }}" required>

                                </div>


                                <div class="form-group">
                                <select class="form-control form-control-user" id="gl" name="gl"  value="{{ old('gl') }}"  required>
                                        <option value="" disabled selected>Select Account</option>

                                        @foreach ($gls as $gl)

                                        <option value="{{ $gl->AccCode }}">{{ $gl->AccCode.'/'.$gl->AccName }}</option>

                                        @endforeach
                                    </select>
                                </div>

                                <div class="form-group">
                                <input type="text" class="form-control form-control-user" id="amount" placeholder="Amount" name="amount"  value="{{ old('amount') }}" required>

                                </div>

                                <div class="form-group">
                                <select class="form-control form-control-user" id="curr" name="curr"  value="{{ old('curr') }}"  required>
                                        <option value="" disabled selected>Select Currency</option>

                                        @foreach ($currencys as $currency)

                                        <option value="{{ $currency->ID}}">{{ $currency->Name }}</option>

                                        @endforeach
                                    </select>
                                </div>


                               <div style="display: flex;">
                               <input type="submit" style="width: 100px;height: 40px; margin-right: 10px; margin-top: 6px" value="Save" class="btn btn-primary btn-user btn-block"  id="submitButton"/>

                                <input style="width: 100px;" onclick="refreshAccountType('', '', '', '', '', '', '', '', '')"  type="reset" value="Refresh" class="btn btn-secondary btn-user btn-block"  onclick="hideMessages()"/>

                               </div>

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

                        <div class="col-xl-8 col-lg-7">

                            <div class="card shadow mb-4">
                                <div class="card-header py-3">
                                    <h6 style="float: left;" class="m-0 font-weight-bold text-primary">{{$JournalType}} Transactions </h6>

                                        @if(!empty($PermissionsAddReceipt))
                                        <a id="process" href="{{route('printreceipt',['type'=>$JournalType,'invoice'=>$batch])}}" style="float: right; margin-top: -5px;" class="btn btn-success btn-icon-split">
                                            <span class="icon text-white-50">
                                                <i class="fas fa-check"></i>
                                            </span>
                                            <span class="text">Process</span>
                                        </a>
                                        @endif

                                </div>
                                <div class="card-body">
                                <div class="table-responsive">
                                <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0" style="font-size: 13px;">
                                    <thead>
                                        <tr>

                                        <th style="padding: 4px;">Entry Date</th>
                                        <th style="padding: 4px;">Description</th>
                                        <th style="padding: 4px;">Account</th>
                                        <th style="padding: 4px;">Reference</th>
                                        <th style="padding: 4px;">Total</th>
                                        <th style="padding: 4px;">Action</th>
                                        </tr>
                                    </thead>
                                    <tfoot>
                                        <tr>

                                        <th style="padding: 4px;">Entry Date</th>
                                        <th style="padding: 4px;">Description</th>
                                        <th style="padding: 4px;">Account</th>
                                        <th style="padding: 4px;">Reference</th>
                                        <th style="padding: 4px;">Total</th>
                                        <th style="padding: 4px;">Action</th>

                                        </tr>
                                    </tfoot>
                                    <tbody>

                                    @foreach ($Jts as $Jt)
                                            <tr>

                                                <td>{{ $Jt->EntryDate }}</td>
                                                <td>{{ $Jt->Narration }}</td>
                                                @php
                                                 $contractCode = $Jt->ContraCode;
                                                 if (!empty($Jt->ContraSubCode)) {
                                                 $contractCode .= '/' . $Jt->ContraSubCode;
                                                 }
                                                 @endphp
                                                <td>{{ $contractCode }}</td>
                                                <td>{{ $Jt->Refference }}</td>

                                                <td>{{ number_format($Jt->DR * $Jt->Rate, 2) }}</td>

                                                <td style="justify-content: center; align-items: center; ">
                                                @if(!empty($PermissionsEditReceipt))

                                                    <a href=""  class="btn btn-primary btn-circle" style="height: 25px; width: 15px;"  onclick="editAccountType(event,'{{ $Jt->ID }}', '{{ $Jt->AccSubCode }}', '{{ $Jt->Narration }}', '{{ $Jt->Refference }}',   '{{ $contractCode }}', '{{ $Jt->DR*$Jt->Rate }}', '{{ $Jt->Currency }}')">
                                                    <i class="fas fa-edit" style="font-size: 0.75em;"></i>
                                                    </a>
                                                @endif
                                                @if(!empty($PermissionsDeleteReceipt))

                                                    <a href="{{ route('deletereceipt', ['ID' => $Jt->ID,'type'=>$JournalType]) }}" style="height: 25px; width: 15px;"  class="btn btn-danger btn-circle" onclick="return confirmDelete('{{ $Jt->Refference .' => '.$Jt->Narration }}');">
                                                        <i class="fas fa-trash" style="font-size: 0.75em;"></i>
                                                    </a>
                                                @endif
                                                </td>

                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>

                                <div style="margin-top: 20px; font-weight: bold; text-align: right;">
                                    <div style="display: flex; justify-content: flex-end;">
                                        <div style="text-align: right; margin-right: 10px;">
                                            <p>Total Amount:</p>

                                        </div>
                                        <div style="text-align: left;">
                                            <p>{{ $symbol.' '.number_format($total, 2) }}</p>
                                      </div>
                                    </div>
                                </div>
                            </div>

                        </div>

                    </div>





                </div>



            </div>
            <script>
                                document.addEventListener('DOMContentLoaded', function () {
                document.getElementById('account').addEventListener('change', function () {
                    const accountCode = this.value;
                    const reffSelect = document.getElementById('reff');

                    reffSelect.innerHTML = '<option value="" disabled selected>Reference</option>';

                    if (accountCode) {
                        fetch(`{{ route('get-references', ':code') }}`.replace(':code', accountCode))
                            .then(response => {
                                if (!response.ok) throw new Error('Network response was not ok');
                                return response.json();
                            })
                            .then(data => {
                                if (data.length === 0) {
                                    const option = document.createElement('option');
                                    option.value = '';
                                    option.disabled = true;
                                    option.textContent = 'No references available';
                                    reffSelect.appendChild(option);
                                } else {
                                    data.forEach(ref => {
                                        const option = document.createElement('option');
                                        option.value = ref.Batch;
                                        option.textContent = `${ref.Batch} ->(Owing Balance: ${ref.balance ?? 'N/A'})`;
                                        reffSelect.appendChild(option);
                                    });
                                }
                            })
                            .catch(error => console.error('Error fetching references:', error));
                    }
                });
            });

                        </script>


                        <script>
                             function editAccountType(event,id, account, narr, reff, gl, amount, curr)
                             {
                                event.preventDefault();
                                document.getElementById('accountId').value = id;
                                document.getElementById('account').value = account;
                                document.getElementById('narr').value = narr;
                                document.getElementById('reff').value = reff;
                                document.getElementById('gl').value = gl;
                                document.getElementById('amount').value = amount;
                                document.getElementById('curr').value = curr;
                                document.getElementById('formHeader').innerText = 'Edit Receipt';
                                document.getElementById('submitButton').value = 'Edit';
                                document.getElementById('accountTypeForm').action = '{{route("editreceipt")}}';
                            }

                            function refreshAccountType(id, account, narr, reff, gl, amount, curr)
                            {
                                document.getElementById('accountId').value = id;
                                document.getElementById('account').value = account;
                                document.getElementById('narr').value = narr;
                                document.getElementById('reff').value = reff;
                                document.getElementById('gl').value = gl;
                                document.getElementById('amount').value = amount;
                                document.getElementById('curr').value = curr;
                                document.getElementById('formHeader').innerText = 'Process Receipt';
                                document.getElementById('submitButton').value = 'Save';
                                document.getElementById('accountTypeForm').action = '{{route("savereceipt")}}';
                                hideMessages();

                            }

                            function confirmDelete(Name) {
                                return confirm("Are you sure you want to delete: " + Name + "?");
                            }



                            function preventRemoval(event) {
                                const input = event.target;
                                if (input.selectionStart <= 3 && (event.key === 'Backspace' || event.key === 'Delete')) {
                                    event.preventDefault();
                                }
                            }

                            // Ensure the input starts with SUP when the page loads
                            document.addEventListener('DOMContentLoaded', (event) => {
                                const batchInput = document.getElementById('batch');
                                enforcePrefix(batchInput);
                            });

                            function enforcePrefixAndUpdateURL(input) {

                            updateURL(input.value);
                        }

                        function updateURL(batchValue) {
                            const type = "{{ $JournalType }}"; // Ensure $JournalType is available in the Blade template
                            const url = `{{ route('printreceipt', ['type' => ':type', 'invoice' => ':batch']) }}`.replace(':type', type).replace(':batch', batchValue);
                            document.getElementById('process').href = url;
                        }

                        // Ensure the input starts with SUP when the page loads
                        document.addEventListener('DOMContentLoaded', (event) => {
                            const batchInput = document.getElementById('batch');

                            updateURL(batchInput.value);
                        });



                </script>


@endsection
