@extends('layouts.nav')
@section('title')
{{$JournalType}} Invoice
@endsection
@section('content')
@php
$PermissionsAddBanks = App\Models\PermissionsUserModel::getPermission('Add Banks', Auth::user()->id);
$PermissionsEditBanks = App\Models\PermissionsUserModel::getPermission('Edit Banks', Auth::user()->id);
$PermissionsDeletBanks = App\Models\PermissionsUserModel::getPermission('Delete Banks', Auth::user()->id);
@endphp

                    <!-- Page Heading -->
                    <div class="d-sm-flex align-items-center justify-content-between mb-4">
                        <h1 class="h3 mb-0 text-gray-800">{{$JournalType}}  Invoice</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 Invoice</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('savetransaction')}}" 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="Invoice"
                                        name="batch"
                                        value="{{ $JournalType == 'Supplier' ? 'SUP' : $batch }}"
                                        {{ $JournalType == 'Supplier' ? '' : 'readonly' }}
                                        onkeydown="preventRemoval(event)"
                                        >
                                </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">
                                        <input type="text" class="form-control form-control-user" id="narr" placeholder="Narration" name="narr"  value="{{ old('narr') }}" required>

                                </div>

                                <div class="form-group">
                                        <input type="text" class="form-control form-control-user" id="reff" placeholder="Refference" name="reff"  value="{{ old('reff') }}" 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">
                                <select class="form-control form-control-user" id="tax" name="tax"  value="{{ old('tax') }}"  required>
                                        <option value="" disabled selected>Select Tax</option>

                                        @foreach ($taxs as $tax)

                                        <option value="{{ $tax->ID.':'.$tax->Rate }}">{{ $tax->Rate.'% '.$tax->Name }}</option>

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

                                </div>

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

                                </div>

                                <div class="form-group">
                                <input type="text" class="form-control form-control-user" id="qty" placeholder="Quantity" name="qty"  value="{{ old('qty') }}" 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 class="form-group">
                                            <div class="custom-control custom-checkbox small">
                                                <input type="checkbox" class="custom-control-input" id="customCheck" name="customCheck">
                                                <label class="custom-control-label" for="customCheck">Operation Cost</label>
                                            </div>
                                        </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" onclick="updateURLAndSubmit(event)"/>

                                <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($PermissionsAddInvoice))
                                    <a id="process" href="{{route('printinvoice',['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;">Qty</th>
                                            <th style="padding: 4px;">Price</th>
                                            <th style="padding: 4px;">Disc %</th>
                                            <th style="padding: 4px;">Tax %</th>
                                            <th style="padding: 4px;">Tax Amt</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;">Qty</th>
                                        <th style="padding: 4px;">Price</th>
                                        <th style="padding: 4px;">Disc %</th>
                                        <th style="padding: 4px;">Tax %</th>
                                        <th style="padding: 4px;">Tax Amt</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->Qnty, 2) }}</td>
                                                <td>{{ number_format($Jt->Price * $Jt->Rate, 2) }}</td>
                                                <td>{{ number_format((($Jt->Price * ($Jt->Discount / 100)) * $Jt->Qnty) * $Jt->Rate, 2) }}</td>
                                                <td>{{ number_format($Jt->Tax, 2) }}</td>
                                                <td>{{ number_format(($Jt->Qnty * ($Jt->Price - ($Jt->Price * ($Jt->Discount / 100)))) * ($Jt->Tax / 100) * $Jt->Rate, 2) }}</td>
                                                <td>{{ number_format(($Jt->Qnty * $Jt->Price) * $Jt->Rate, 2) }}</td>

                                                <td style="justify-content: center; align-items: center; ">

                                                    <a href=""  class="btn btn-primary btn-circle" style="height: 25px; width: 15px;"  onclick="editAccountType(event,'{{ $Jt->ID }}', '{{ $Jt->AccSubCode }}', '{{ $Jt->Narration }}', '{{ $Jt->Refference }}','{{ $Jt->Price }}',   '{{ $contractCode }}', '{{ $Jt->Qnty }}', '{{ $Jt->Discount }}',  '{{ $Jt->TaxID.':'.$Jt->Tax  }}','{{ $Jt->Currency }}')">
                                                    <i class="fas fa-edit" style="font-size: 0.75em;"></i>
                                                    </a>
                                                  <a href="#"
                                                    style="height: 25px; width: 15px;"
                                                    class="btn btn-danger btn-circle"
                                                    onclick="confirmDelete('{{ $Jt->Narration }}', '{{ $Jt->Refference }}', '{{ route('deleteinvoice', ['ID' => $Jt->ID, 'type' => $JournalType]) }}'); return false;">
                                                        <i class="fas fa-trash" style="font-size: 0.75em;"></i>
                                                    </a>
                                                </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 (Exc):</p>
                                            <p>Total (Tax):</p>
                                            <p>Total (Dis):</p>
                                            <p>Total (Inc):</p>
                                        </div>
                                        <div style="text-align: left;">
                                            <p>{{ $symbol.' '.number_format($totalExcludingTax, 2) }}</p>
                                            <p>{{ $symbol.' '.number_format($totalTaxAmount, 2) }}</p>
                                            <p>{{ $symbol.' '.number_format($totalDiscounts, 2) }}</p>
                                            <p>{{ $symbol.' '.number_format($totalIncludingTax, 2) }}</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- Confirmation Modal -->
                        <div class="modal fade" id="confirmDeleteModal" tabindex="-1" role="dialog" aria-labelledby="confirmDeleteModalLabel" aria-hidden="true">
                            <div class="modal-dialog" role="document">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="confirmDeleteModalLabel">Confirm Deletion</h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <div class="modal-body">
                                        Are you sure you want to delete: <span id="deleteItemName"></span>?
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                        <button type="button" class="btn btn-danger" id="confirmDeleteButton">Delete</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

             <script>
                    function editAccountType(event, id, account, narr, reff, price, gl, qty, disc, tax, Currency) {
                        event.preventDefault();
                        setFormValues(id, account, narr, reff, price, gl, qty, disc, tax, Currency, 'Edit Invoice', 'Edit', '{{route("edittransaction")}}');
                    }

                    function refreshAccountType(id, account, narr, reff, price, gl, qty, disc, tax, Currency) {
                        setFormValues(id, account, narr, reff, price, gl, qty, disc, tax, Currency, 'Process Invoice', 'Save', '{{route("savetransaction")}}');
                        hideMessages();
                    }

                    function setFormValues(id, account, narr, reff, price, gl, qty, disc, tax, Currency, headerText, buttonText, action) {
                        document.getElementById('accountId').value = id;
                        document.getElementById('account').value = account;
                        document.getElementById('narr').value = narr;
                        document.getElementById('reff').value = reff;
                        document.getElementById('price').value = price;
                        document.getElementById('gl').value = gl;
                        document.getElementById('qty').value = qty;
                        document.getElementById('disc').value = disc;
                        document.getElementById('tax').value = tax;
                        document.getElementById('curr').value = Currency;
                        document.getElementById('formHeader').innerText = headerText;
                        document.getElementById('submitButton').value = buttonText;
                        document.getElementById('accountTypeForm').action = action;
                    }
                    function confirmDelete(name, reference, deleteUrl) {
                        // Set the item name in the modal
                        document.getElementById('deleteItemName').innerText = `${name} => ${reference}`;

                        // Show the modal
                        $('#confirmDeleteModal').modal('show'); // Requires jQuery and Bootstrap's JS

                        // Handle the delete confirmation
                        document.getElementById('confirmDeleteButton').onclick = function() {
                            // Proceed with the deletion
                            window.location.href = deleteUrl; // Redirect to the delete URL

                            // Hide the modal after confirming
                            $('#confirmDeleteModal').modal('hide');
                        };
                    }

                    function updateURLAndSubmit(event) {
                        event.preventDefault(); // Prevent the default form submission

                        const batchInput = document.getElementById('batch');
                        let batchValue = batchInput.value.trim();

                        // Ensure the batch value starts with "SUP" for suppliers
                        if ("{{ $JournalType }}" === 'Supplier' && !batchValue.startsWith('SUP')) {
                            batchValue = 'SUP' + batchValue; // Ensure it starts with "SUP"
                        }

                        // Update the URL for the process button
                        const processButton = document.getElementById('process');
                        const type = "{{ $JournalType }}"; // Assuming this is set in your Blade template
                        const url = `{{ route('printinvoice', ['type' => ':type', 'invoice' => ':batch']) }}`
                            .replace(':type', type)
                            .replace(':batch', batchValue); // Use the updated batch value

                        if (processButton) {
                            processButton.href = url; // Update the button URL
                        }

                        // Submit the form after updating the URL
                        document.getElementById('accountTypeForm').submit(); // Ensure your form has this ID
                    }
                </script>
@endsection
