@extends('layouts.app')

@section('content')

<!-- Content wrapper scroll start -->
<div class="content-wrapper-scroll">

<!-- Content wrapper start -->
<div class="content-wrapper">
@if($discounting_amount == null)
@if($invoice->count())
<div class="alert alert-danger alert-dismissible fade show" role="alert">
Hello {{auth()->user()->name}}! you didn't complete your last transaction. COMPLETE INVOICE or <a href="{{route('deleteDump')}}">CREATE NEW INVOICE</a>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
@else
@endif
@endif
<div style="background-color:#ffffff; padding:15px">

<form id="newinvoice">
    @csrf
<!-- Row start -->
<div class="row gutters">
    
    <div class="col-xl-12 col-lg-12 col-md-12 col-sm-4 col-12">
        <div class="form-section-header">New Invoice</div>
    </div>
    <div class="col-xl-4 col-lg-4 col-md-4 col-sm-4 col-12">
        
     <!-- Field wrapper start -->
     <div class="field-wrapper">
            <select name="invoice_product_name" class="select-single js-states" title="Select Product Category"  onchange="getPrice()" id="ddlViewBy" data-live-search="true">
            <option selected disabled>Select Item</option>
                    @foreach($products as $product)
                            <option value="{{$product->FinalProductionID}}">{!!$product->Name!!}</option>
                    @endforeach
            </select>
            <div class="field-placeholder">Product Name</div>
        </div>
        <!-- Field wrapper end -->
        
    </div>
    <div class="col-xl-4 col-lg-4 col-md-4 col-sm-4 col-12">
        
        <!-- Field wrapper start -->
        <div class="field-wrapper">
            <div class="input-group">
                <input class="form-control" type="text" value="1" id="quantity" name="invoice_quantity" onKeyUp="calculateTotal()">
                <span class="input-group-text">
                <i class="fa fa-sort-numeric-asc" aria-hidden="true"></i>
                </span>
            </div>
            <div class="field-placeholder">Quantity</div>
        </div>
        <!-- Field wrapper end -->

    </div>
    <div class="col-xl-4 col-lg-4 col-md-4 col-sm-4 col-12">
        
        <!-- Field wrapper start -->
        <div class="field-wrapper">
            <div class="input-group">
                <input class="form-control" readonly step="0.01" type="number" id="price" name="invoice_unit_price">
                <span class="input-group-text">
                    GH₵
                </span>
            </div>
            <div class="field-placeholder">price</div>
        </div>
        <!-- Field wrapper end -->

    </div>

    <div class="col-xl-4 col-lg-4 col-md-4 col-sm-4 col-12">
        
        <!-- Field wrapper start -->
        <div class="field-wrapper">
            <div class="input-group">
                <input class="form-control" readonly id="total" type="text" name="invoice_total_price">
                <span class="input-group-text">
                GH₵
                </span>
            </div>
            <div class="field-placeholder">Total Price</div>
        </div>
        <!-- Field wrapper end -->

    </div>
    <div class="col-xl-4 col-lg-4 col-md-4 col-sm-4 col-12">
        
        <!-- Field wrapper start -->
        <div class="field-wrapper">
            <div class="input-group">
                <select name="status" onchange="getValue()" id="getStatus">
                    <option value="General">General</option>
                    <option value="On The House" id="On The House">On The House</option>
                </select>
            </div>
            <div class="field-placeholder">Status</div>
        </div>
        <!-- Field wrapper end -->

    </div>
    <div class="col-xl-4 col-lg-4 col-md-4 col-sm-4 col-12">
        
        <!-- Field wrapper start -->
        <div class="field-wrapper">
            <div class="input-group">
                @if($invoice_number == null)
                <input class="form-control" type="text" id="myInput" readonly name="invoice_number" value="<?=rand(5034580,10034580)+rand(5034580,10034580) . date("Yd") . date('Hi');?>">
                @else
                <input class="form-control" type="text" id="myInput" readonly name="invoice_number" value="<?= $invoice_number->invoice_number ?>">
                @endif
                <span class="input-group-text">
                    <i class="icon-edit-2"></i>
                </span>
            </div>
            <div class="field-placeholder">Invoice ID</div>
        </div>
        <!-- Field wrapper end -->

    </div>
    
    <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">

    <input type="text" value="" readonly name="category" id="category" hidden>

    </div>
    @if(auth()->user()->sales_person_category == "Delivery")
    <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
        <button class="btn btn-primary"><i class="icon-shopping-cart1" aria-hidden="true"></i> Add to Cart</button> 
    </div>
    <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12" style="float:right">
     <button class="btn btn-primary" type="button"><i class="fa fa-motorcycle" aria-hidden="true"></i> Add Delivery</button>
    </div>
    @else
    <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
    <button class="btn btn-primary" ><i class="icon-shopping-cart1" aria-hidden="true"></i> Add to Cart</button> 
    </div>
    @endif
    
</div>
<!-- Row end -->
</form>
</div>


                                        
<table class="table table-bordered" id="tabler">
    <thead>
        <tr>
            <th colspan="7" class="pt-3 pb-3">Invoice Details</th>
        </tr>
        <tr>
            <th width="50%">Product</th>
            <th>Quantity</th>
            <th width="20%">Price</th>
            <th width="30%">Amount (Net)</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        @foreach($invoice as $invoice)
        <tr>
            <td>
                <!-- Field wrapper start -->
                <div class="field-wrapper m-0">
                    <select class="select-single js-states w-100" data-live-search="true">
                        <option>{!!invoice->invoice_product_name!!}</option>
                    </select>
                </div>
                <!-- Field wrapper end -->
            </td>
            <td>
                <!-- Field wrapper start -->
                <div class="field-wrapper m-0">
                    <input type="number" readonly class="form-control" value="{{$invoice->invoice_quantity}}" placeholder="Qty">
                </div>
                <!-- Field wrapper end -->
            </td>
        
            <td>
                <!-- Field wrapper start -->
                <div class="field-wrapper m-0">
                    <div class="input-group">
                        <input type="number" readonly class="form-control" value="{{$invoice->invoice_unit_price}}">
                        <span class="input-group-text">
                        GH₵
                        </span>
                    </div>
                </div>
                <!-- Field wrapper end -->
            </td>
            <td>
                <!-- Field wrapper start -->
                <div class="field-wrapper m-0">
                    <div class="input-group">
                        <input type="text" readonly class="form-control" value="{{$invoice->invoice_total_price}}">
                        <span class="input-group-text">GH₵</span>
                    </div>
                </div>
                <!-- Field wrapper end -->
            </td>
            
            <td>
                <div class="table-actions">
                    <button class="btn btn-light" id="{{$invoice->id}}" onClick="DeleteItem(this.id)">
                        <i class="icon-trash-2"></i>
                    </button>
                </div>
            </td>
        </tr>
        @endforeach
        <tr>
            <td colspan="6">
                <div class="row gutters justify-content-end">
                    <div class="col-auto">
                        <label class="col-form-label">Discount % / GH₵ of Total Amount</label>
                    </div>
                    <div class="col-auto" style="max-width: 90px;">
                        <!-- Discount Button trigger modal -->
                        <button type="button" class="btn btn-primary mb-2" data-bs-toggle="modal" data-bs-target="#exampleModalSmall">
                            Add Discount
                        </button>
                    </div>
                </div>
            </td>
        </tr>
        <tr>
            <td colspan="4">&nbsp;</td>
            <td colspan="2">
                <p class="m-0">Subtotal</p>
                <p class="m-0">Discount</p>
                <p class="m-0">VAT</p>
                <h5 class="mt-2">Total Amount</h5>
            </td>
            <td>
                <p class="m-0">@convert($total_cost_invoice)</p>
                <p class="m-0" id="discounting">
                    <?php
                        if ($discounting_amount == null) {
                            echo "GHS 0,00";
                        }else {
                           if ($discounting_amount->type == "Cash") {
                            echo 'GH₵'. $discounting_amount->discount;
                           }elseif ($discounting_amount->type == "Percentage") {
                            echo  $discounting_amount->discount . "%";
                          }
                        }

                    ?>
                </p>
                <p class="m-0">GH₵0.00</p>
                @if($discounting_amount == null)
                <h5 class="mt-2" id="tcost">GH₵@convert($total_cost_invoice)</h5>
                @else
                <h5 class="mt-2" id="tcost">GH₵ @convert($discounting_amount->amount_paid)</h5>
                @endif
            </td>
        </tr>
    </tbody>
</table>

<!-- Row start -->
<div class="row gutters">

<div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
    <div class="form-actions-footer">
        <div class="text-end">
            <a href="#" onclick="confirmCreateNew()" class="btn btn-primary ms-1">New Invoice</a>
             <button class="btn btn-light" onclick="saveDraft()">Save Draft</button>
            <a href="#" onclick="confirmInvoice()" class="btn btn-info ms-1">Create Invoice</a>
        </div>
    </div>
</div>

</div>
<!-- Row end -->

</div>
<!-- Content wrapper end -->



<!-- Modal start -->
<div class="modal fade" id="exampleModalSmall" tabindex="-1" aria-labelledby="exampleModalSmallTitle" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalSmallTitle">Apply Discount Or Coupons</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="dis">
            @if($invoice_number == null)
            @else
            <form action="{{route('OrderDiscount')}}" method="POST">
                @csrf
                <input type="text" hidden readonly name="order_number" value="{{$invoice_number->invoice_number}}">
                <div class="mb-3">
                    <label class="form-label">Type:</label>
                    <select name="type" class="form-control">
                        <option value="Percentage">PERCENTAGE(%)</option>
                        <option value="Cash">CASH</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Set Discount</label>
                    <input type="number" name="discount" step="0.01" class="form-control">
                </div>
                <button type="submit" class="btn btn-primary">Apply</button>
            </form>
            @endif
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            </div>
        </div>
    </div>
</div>
<!-- Modal end -->




    <!-- Modal on the house start -->
    <div class="modal fade" id="onthehouse" tabindex="-1" aria-labelledby="exampleModalSmallTitle" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalSmallTitle">On the House Form</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                @include('inc.onhouse')
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>
    <!-- Modal end -->



</div>
<!-- Content wrapper scroll end -->


<script type="text/javascript">
    
    $("#newinvoice").on('submit', function(event) {
            event.preventDefault();
            $.ajax({
                type: "post",
                url: "{{route('InvoiceDump')}}",
                dataType: "json",
                data: $('#newinvoice').serialize(),
                success: function(data){
                    document.getElementById('price').value = "";
                    document.getElementById('total').value = "";
                    document.getElementById('quantity').value = "1";
                    document.getElementById('ddlViewBy').value = "";
                    $("#tabler").load(" #tabler");
                    $("#dis").load(" #dis");
                },
                error: function(data){
                    Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                     text: 'Something went wrong!',
                    footer: '<a href="">Why do I have this issue?</a>'
                    })
                }
            });
        });


        $("#discount").on('submit', function(event) {
            event.preventDefault();
            $.ajax({
                type: "post",
                url: "{{route('OrderDiscount')}}",
                dataType: "json",
                data: $('#discount').serialize(),
                success: function(data){
                    $("#tabler").load(" #tabler");
                    $("#dis").load(" #dis");
                },
                error: function(data){
                    Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                     text: 'Something went wrong!',
                    footer: '<a href="">Why do I have this issue?</a>'
                    })
                }
            });
        });



        



        function calculateTotal() {
            quantity = document.getElementById("quantity").value;
            price = document.getElementById("price").value;
            // document.getElementById("result").innerHTML = num1 * num2;
            document.getElementById("total").value = quantity*price;
        }


        function saveDraft() {

            Swal.fire({
            title: 'Are you sure?',
            text: "This Invoice will be saved as Draft Invoice!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, Save as Draft!'
            }).then((result) => {
            if (result.isConfirmed) {
                const xhttp = new XMLHttpRequest();
                xhttp.onload = function() {
                    $("#tabler").load(" #tabler");
                    Swal.fire(
                        'Saved to Draft!',
                        'This Invoice is Saved as Draft',
                        'success'
                        )
                }
                xhttp.open("GET", "/ceqa-dashboard/generate-draft-invoice");
                xhttp.send();
            }
            })
            
        }


        function DeleteItem(id) {
            const xhttp = new XMLHttpRequest();
            xhttp.onload = function() {
                $("#tabler").load(" #tabler");
            }
            xhttp.open("GET", "/ceqafoods/delete-item/"+id);
            xhttp.send();
            
        }

        function confirmInvoice() {
            Swal.fire({
                title: 'Create Invoice, Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, Save And Print!'
                }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = "{{route('generateInvoice')}}"
                }
                })
        }

        function getPrice() {
            var e = document.getElementById("ddlViewBy");

            const xhttp = new XMLHttpRequest();
            xhttp.onload = function() {
                $da = JSON.parse(this.responseText);
                document.getElementById("price").value = $da.price;
                document.getElementById("category").value = $da.category;
                quantity = document.getElementById("quantity").value;
                price = document.getElementById("price").value;
                document.getElementById("total").value = quantity*price;


            }
            xhttp.open("GET", "/get-product-price/"+e.value);
            xhttp.send();
            
        }

        function confirmCreateNew() {
            Swal.fire({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, create New Invoice!'
                }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = "{{route('deleteDump')}}";
                }
                })
        }


        function getValue() {
            var invoiceinput = document.getElementById("myInput").value;
            var e = document.getElementById("getStatus");
            if (e.value === "On The House") {
                $('#onthehouse').modal('show')
                document.getElementById("inv").value = invoiceinput
            }else{
                console.log("error")
            }
        }
</script>



@endsection