@extends('welcome')
@section('title')
    @if ($type == 1)
        Factures
    @endif
    @if ($type == 2)
        Devis
    @endif
@endsection
@section('styles')
    <link href="{{ asset('dist/css/hotspot/hotspot.css') }}" rel="stylesheet" />
    <link href="{{ asset('dist/css/hotspot/style.css') }}" rel="stylesheet" />
@endsection

@section('content')
    <div class="content-wrapper">
        <div class="container-fluid">
            <div class="row mt-3">
                <div class="col-lg-12">
                    <div class="card m-3">
                        <div class="card-body">
                            <div class="d-flex justify-content-between m-3">
                                <h5 class="card-title">
                                    @if ($statement)
                                        Modifier
                                    @else
                                        Ajouter
                                    @endif
                                    @if ($type == 1)
                                        Facture
                                    @endif
                                    @if ($type == 2)
                                        Devis
                                    @endif
                                </h5>

                                <div>
                                    <h5 class="card-title">
                                        @if ($statement)
                                            Élaborée par: {{ $statement->user->name }} {{ $statement->user->lastName }}
                                        @else
                                            Élaborée par: {{ auth()->user()->name }} {{ auth()->user()->lastName }}
                                        @endif
                                    </h5>
                                    <h5 class="card-title">
                                        @if ($statement)
                                            @if ($statement->edit_id != null)
                                                Modifiée par: {{ $statement->edit->name }} {{ $statement->edit->lastName }}
                                            @else
                                                Modifiée par: {{ auth()->user()->name }} {{ auth()->user()->lastName }}
                                            @endif
                                        @endif
                                    </h5>
                                    @if ($statement)
                                        <a target="_blank" href="{{ route('statements.getPDF', $statement->id) }}"
                                            class="btn btn-success">Imprimer</a>
                                    @endif
                                </div>

                            </div>
                            <form method="POST" id="form" enctype="multipart/form-data"
                                action="{{ route('statements.store') }}">
                                @csrf
                                <div class="form-body">
                                    <div class="row">
                                        <div class="form-group col-12">
                                            <div class="row mb-5">
                                                <div class="form-group col-md-3">
                                                    <label>Référence: </label>
                                                    <input type="text" name="reference" disabled id="reference"
                                                        style="font-weight: bold;"
                                                        @if ($statement) value="{{ $statement->reference }}" @else value="{{ $ref }}" @endif
                                                        class="form-control">
                                                </div>
                                                <div class="form-group col-md-3" id="clientDiv">
                                                    <label>Client: </label>
                                                    <select name="client_id" class="form-control" id="selectClients">
                                                        <option value="0"
                                                            @if ($statement == null) selected @endif disabled>--
                                                        </option>
                                                        @foreach ($clients as $client)
                                                            <option @if ($statement && $statement->client_id == $client->id) selected @endif
                                                                value="{{ $client->id }}">{{ $client->name }}</option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                                <div class="form-group col-md-3">
                                                    <label>Date: </label>
                                                    <input type="date" name="date" class="form-control"
                                                        @if ($statement) value="{{ $statement->date }}" @else value="{{ $date }}" @endif>
                                                </div>
                                                <input type="hidden" name="type" value="{{ $type }}">
                                                @if ($type == 1)
                                                    <div class="form-group col-md-3">
                                                        <label>Timbre Fiscal: </label>
                                                        <input type="number" step="0.001" name="timbreFiscal"
                                                            value="{{ $statement ? $statement->timbreFiscal : $timbre }}"
                                                            class="form-control">
                                                    </div>
                                                @endif
                                            </div>
                                        </div>
                                        <input type="hidden" id="productsInput" name="items">
                                        <div class="form-group col-12">
                                            <div class="row">
                                                <div class="col-md-2">
                                                    <label>Code Article</label>
                                                    <div class="form-group" id="codeForm">
                                                        <select id="codeProduct" class="codeProduct form-control">
                                                            @foreach ($products as $product)
                                                                <option value="{{ $product->id }}">{{ $product->code }}
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="col-md-3">
                                                    <label>Articles</label>
                                                    <div class="form-group" id="searchForm">
                                                        <select id="selectProducts" class="selectProducts form-control">
                                                            @foreach ($products as $product)
                                                                <option value="{{ $product->id }}">{{ $product->name }}
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                        <input type="text" class="form-control" id="articleNom">
                                                    </div>
                                                </div>

                                                <div class="col-md-2">
                                                    <label>Quantité Disponible</label>
                                                    <div class="form-group">
                                                        <input type="number" class="form-control" disabled id="qteDispo"
                                                            value="0">
                                                    </div>
                                                </div>
                                                <div class="col-md-1">
                                                    <label>Quantité</label>
                                                    <div class="form-group">
                                                        <input type="number" step="1" min="0"
                                                            id="quantitéProducts" class="form-control" value="0">
                                                    </div>
                                                </div>
                                                @if ($type != 3)
                                                    <div class="col-md-1">
                                                        <label>Prix</label>
                                                        <div class="form-group">
                                                            <input type="number" step="0.001" min="0"
                                                                id="priceProducts" class="form-control">
                                                        </div>
                                                    </div>
                                                    <div class="col-md-1">
                                                        <label>Remise</label>
                                                        <div class="form-group">
                                                            <input type="number" step="0.01" min="0"
                                                                id="discountProducts" class="form-control">
                                                        </div>
                                                    </div>
                                                    <div class="col-md-1">
                                                        <label>TVA</label>
                                                        <div class="form-group">
                                                            <input type="number" step="0.01" min="0"
                                                                id="tvaProducts" class="form-control">
                                                        </div>
                                                    </div>
                                                @endif

                                                <div class="col-md-2 mb-5"
                                                    @if (Auth::user()->role_id != 1) style="display: none;" @endif>
                                                    <label>&nbsp;</label>
                                                    <div class="form-group">
                                                        <button type="button" class="btn btn-primary w-100"
                                                            id="addProduct">Ajouter</button>
                                                    </div>
                                                    <div id="annuler">
                                                    </div>
                                                </div>

                                            </div>
                                        </div>

                                        <div class="table-responsive">
                                            <table class="table table-striped">
                                                <thead>
                                                    <tr>
                                                        <th scope="col">Code</th>
                                                        <th scope="col">Article</th>
                                                        <th scope="col">Quantité</th>
                                                        @if ($type != 3)
                                                            <th scope="col">Prix Unit.</th>
                                                            <th scope="col">Montant HT</th>
                                                            <th scope="col">Remise %</th>
                                                            <th scope="col">Montant Remise</th>
                                                            <th scope="col">Montant HT Net</th>
                                                            <th scope="col">TVA %</th>
                                                            <th scope="col">Montant TVA</th>
                                                            <th scope="col">Total</th>
                                                        @endif
                                                        @if (Auth::user()->role_id == 1)
                                                            <th scope="col">Actions</th>
                                                        @endif
                                                    </tr>
                                                </thead>
                                                <tbody id="tbody">

                                                </tbody>
                                                <tfoot id="tfoot"></tfoot>
                                            </table>
                                        </div>

                                        <div class="form-group col-12">
                                            <label>Commentaire: </label>
                                            <textarea name="comment" class="form-control" id="" cols="30" rows="3">{{ $statement ? $statement->comment : '' }}</textarea>
                                        </div>



                                        <div class="modal-footer"
                                            @if (Auth::user()->role_id != 1) style="display: none;" @endif>

                                            <button type="button" id="formSubmit" class="btn btn-primary">
                                                <i class="bx bx-check d-block d-sm-none"></i>
                                                <span class="text-white">
                                                    @if ($statement)
                                                        Modifier
                                                    @else
                                                        Ajouter
                                                    @endif
                                                </span>
                                            </button>
                                        </div>


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



            </div>
            <!--End Row-->



            <!--start overlay-->
            <div class="overlay toggle-menu"></div>
            <!--end overlay-->
        </div>
        <!-- End container-fluid-->
    </div>
    @if ($type == 1 && $statement)
        <div class="content-wrapper">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card m-3">
                            <div class="card-body">
                                <div class="d-flex justify-content-between m-3">
                                    <h5 class="card-title">
                                        Règlements
                                    </h5>
                                    @if (Auth::user()->role_id == 1)
                                        <div class="float-end">
                                            <button type="button" class="btn btn-primary block" data-bs-toggle="modal"
                                                data-bs-target="#exampleModalCenter">
                                                Ajouter
                                            </button>
                                        </div>
                                    @endif


                                </div>
                                <div class="table-responsive">
                                    <table class="table table-striped">

                                        <thead>
                                            <tr>
                                                <th id="date">Date</th>
                                                <th>Montant</th>
                                                <th>Mode de Paiment</th>
                                                <th>Statut</th>
                                                @if (Auth::user()->role_id == 1)
                                                    <th>Actions</th>
                                                @endif
                                            </tr>
                                        </thead>

                                        <tbody id="tbody">
                                            @foreach ($statement->reglements as $reg)
                                                <tr>

                                                    <td style="width: 20%">{{ $reg->date }}</td>
                                                    <td style="width: 20%">{{ $reg->montant }}</td>
                                                    <td style="width: 20%">{{ $reg->modePaiment->libelle }} </td>
                                                    <td style="width: 20%">

                                                        @if ($reg->statut)
                                                            <span class="badge bg-success">⦿ Payé</span>
                                                        @else
                                                            <span class="badge bg-danger">⦾ Non Payé</span>
                                                        @endif

                                                    </td>
                                                    @if (Auth::user()->role_id == 1)
                                                        <td>
                                                            <div class="float-end">
                                                                <button class="btn btn-warning m-1"
                                                                    onclick="updateItem('{{ $reg->id }}', {{ $reg }})">
                                                                    <i class="bi bi-pencil-fill mx-1"></i> Modifier
                                                                </button>

                                                                <button class="btn btn-danger m-1"
                                                                    onclick="deleteItem('{{ $reg->id }}')">
                                                                    <i class="bi bi-trash3-fill mx-1"></i> Supprimer
                                                                </button>
                                                            </div>
                                                        </td>
                                                    @endif

                                                </tr>
                                            @endforeach

                                        </tbody>
                                    </table>
                                    <form id="deleteForm" method="POST">
                                        @csrf
                                        @method('DELETE')

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

                    <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog"
                        aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered modal-dialog-centered modal-dialog-scrollable"
                            role="document">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="exampleModalCenterTitle">Ajouter une sociéte
                                    </h5>
                                    <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
                                        <i data-feather="x"></i>
                                    </button>
                                </div>
                                <div class="modal-body">
                                    <form method="POST" action="{{ route('reglements.store') }}"
                                        class="form form-vertical" id="financeform" enctype="multipart/form-data">


                                        <input type="hidden" name="_token" value="{{ csrf_token() }}">
                                        <input type="hidden" name="statement_id" value="{{ $statement->id }}">

                                        <div class="row">
                                            <div class="col-12">
                                                <div class="form-group has-icon-left">
                                                    <label for="first-name-icon">Date</label>
                                                    <div class="position-relative">
                                                        <input type="date" class="form-control" name="date"
                                                            placeholder="{{ __('Date') }}" required
                                                            id="first-name-icon">
                                                        <div class="form-control-icon">
                                                            <i class="bi bi-lock"></i>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-12">
                                                <div class="form-group has-icon-left">
                                                    <label for="first-name-icon">Montant</label>
                                                    <div class="position-relative">
                                                        <input type="number" step="0.001" class="form-control"
                                                            name="montant" placeholder="{{ __('Montant') }}" required
                                                            id="first-name-icon">
                                                        <div class="form-control-icon">
                                                            <i class="bi bi-lock"></i>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-12">
                                                <div class="form-group has-icon-left">
                                                    <label for="first-name-icon">Mode</label>
                                                    <div class="position-relative">
                                                        <select name="mode_paiment_id" class="form-control "
                                                            style="border-radius: 50px;" required>

                                                            @foreach ($modes as $mode)
                                                                <option value="{{ $mode->id }}">
                                                                    {{ $mode->libelle }}</option>
                                                            @endforeach

                                                        </select>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="col-12">
                                                <div class="form-group has-icon-left">
                                                    <label for="first-name-icon">Statut</label>
                                                    <div class="position-relative">
                                                        <select name="statut" class="form-control "
                                                            style="border-radius: 50px;" required>
                                                            <option value="0">Non Payé</option>
                                                            <option value="1">Payé</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-12 d-flex justify-content-end">
                                                <button type="submit"
                                                    class="btn btn-primary me-1 mb-1">Confirmer</button>
                                                <button type="reset" class="btn btn-light-secondary me-1 mb-1"
                                                    data-bs-dismiss="modal">Annuler</button>
                                            </div>
                                        </div>
                                    </form>
                                </div>

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

                    <div class="modal fade" id="edit" tabindex="-1" role="dialog"
                        aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered modal-dialog-centered modal-dialog-scrollable"
                            role="document">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="exampleModalCenterTitle">Modifier
                                    </h5>
                                    <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
                                        <i data-feather="x"></i>
                                    </button>
                                </div>
                                <div class="modal-body">
                                    <form method="POST" action="{{ route('reglements.store') }}"
                                        class="form form-vertical" enctype="multipart/form-data">
                                        @method('PUT')
                                        <input type="hidden" name="_method" value="PUT">
                                        <input type="hidden" name="_token" value="{{ csrf_token() }}">
                                        <input type="hidden" name="statement_id" value="{{ $statement->id }}">
                                        <div class="row">
                                            <div class="col-12">
                                                <div class="form-group has-icon-left">
                                                    <label for="first-name-icon">Date</label>
                                                    <div class="position-relative">
                                                        <input type="date" class="form-control" name="date"
                                                            placeholder="{{ __('Date') }}" required
                                                            id="first-name-icon">
                                                        <div class="form-control-icon">
                                                            <i class="bi bi-lock"></i>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-12">
                                                <div class="form-group has-icon-left">
                                                    <label for="first-name-icon">Montant</label>
                                                    <div class="position-relative">
                                                        <input type="number" step="0.001" class="form-control"
                                                            name="montant" placeholder="{{ __('Montant') }}" required
                                                            id="first-name-icon">
                                                        <div class="form-control-icon">
                                                            <i class="bi bi-lock"></i>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-12">
                                                <div class="form-group has-icon-left">
                                                    <label for="first-name-icon">Mode</label>
                                                    <div class="position-relative">
                                                        <select name="mode_paiment_id" class="form-control "
                                                            style="border-radius: 50px;" required>

                                                            @foreach ($modes as $mode)
                                                                <option value="{{ $mode->id }}">
                                                                    {{ $mode->libelle }}</option>
                                                            @endforeach

                                                        </select>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="col-12">
                                                <div class="form-group has-icon-left">
                                                    <label for="first-name-icon">Statut</label>
                                                    <div class="position-relative">
                                                        <select name="statut" class="form-control "
                                                            style="border-radius: 50px;" required>
                                                            <option value="0">Non Payé</option>
                                                            <option value="1">Payé</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-12 d-flex justify-content-end">
                                                <button type="submit"
                                                    class="btn btn-primary me-1 mb-1">Confirmer</button>
                                                <button type="reset" class="btn btn-light-secondary me-1 mb-1"
                                                    data-bs-dismiss="modal">Annuler</button>
                                            </div>
                                        </div>
                                    </form>
                                </div>

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



                </div>
                <!--End Row-->



                <!--start overlay-->
                <div class="overlay toggle-menu"></div>
                <!--end overlay-->
            </div>
            <!-- End container-fluid-->
        </div>
    @endif
@endsection

@section('scripts')
    <script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.js"></script>
    <script src="{{ asset('dist/js/datatables.net-bs5/js/dataTables.bootstrap5.min.js') }}"></script>
    <script src="{{ asset('dist/js/vendors.js') }}"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.15.2/js/selectize.min.js"
        integrity="sha512-IOebNkvA/HZjMM7MxL0NYeLYEalloZ8ckak+NDtOViP7oiYzG5vn6WVXyrJDiJPhl4yRdmNAG49iuLmhkUdVsQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script>
        let productSelectize;
        let codeSelectize;
        let clientSelectize
        $(document).ready(function() {
            const items = [];
            const options = {
                persist: false,
                maxItems: 1,
                items: items,
                valueField: 'id',
                plugins: ["restore_on_backspace", "clear_button"],
                onChange: function(value) {
                    const product = originalProducts.find((p) => p.id == value);
                    const selectedProducts = products.filter((p) => p.id == value);

                    const sumQuantity = selectedProducts.reduce((acc, product) => {
                        return acc + (parseInt(product.quantité) || 0);
                    }, 0);
                    @if ($type != 3)
                        const price = document.getElementById('priceProducts');
                        const discount = document.getElementById('discountProducts');
                        const tva = document.getElementById('tvaProducts');
                    @endif
                    const quantité = document.getElementById('quantitéProducts');
                    const qteDispo = document.getElementById('qteDispo');
                    if (product && product.hasOwnProperty("quantity")) {
                        qteDispo.value = product.quantity - sumQuantity;
                        quantité.setAttribute('max', product.quantity);
                        @if ($type != 3)
                            price.value = product.price;
                            discount.value = 0;
                            if (getClient()) {
                                tva.value = 0;
                            } else {
                                tva.value = product.tva;
                            }
                        @endif
                        const article = document.getElementById('articleNom')
                        article.value = product.name;

                    }
                    codeSelectize[0].selectize.setValue(value);
                }



            }

            const codeOptions = {
                persist: false,
                maxItems: 1,
                items: items,
                valueField: 'id',
                plugins: ["restore_on_backspace", "clear_button"],
                onChange: function(value) {
                    productSelectize[0].selectize.setValue(value);
                }
            }

            productSelectize = $('#selectProducts').selectize(options);
            codeSelectize = $('#codeProduct').selectize(codeOptions);

            $('#searchForm').find('.clear').each(function(index, button) {
                button.click();
            });
            $('#codeForm').find('.clear').each(function(index, button) {
                button.click();
            });
            const clientOptions = {
                persist: false,
                maxItems: 1,
                items: items,
                valueField: 'id',
                plugins: ["restore_on_backspace", "clear_button"],
            }
            clientSelectize = $('#selectClients').selectize(clientOptions);

            @if ($statement)
            @else
                $('#clientDiv').find('.clear').each(function(index, button) {
                    button.click();
                });
            @endif

        })
        @if ($statement)
            const products = {!! json_encode(
                $statement->items->map(function ($item) {
                        return [
                            'id' => $item->product_id,
                            'name' => $item->name,
                            'quantité' => $item->quantity,
                            'price' => $item->price,
                            'discount' => $item->discount,
                            'tva' => $item->tva,
                            'code' => $item->code,
                        ];
                    })->values(),
            ) !!};
        @else
            const products = [];
        @endif
        let index = 0;
        let update = false;
        const originalProducts = {!! json_encode(
            $products->map(function ($product) {
                return [
                    'id' => $product->id,
                    'name' => $product->name,
                    'price' => $product->price,
                    'tva' => $product->tva,
                    'quantity' => $product->quantity,
                    'code' => $product->code,
                ];
            }),
        ) !!};
        const clients = @json($clients);
        let client = null;
        const button = document.getElementById('addProduct');
        button.addEventListener('click', () => {
            if (update) {
                const select = document.getElementById('selectProducts');
                const quantité = document.getElementById('quantitéProducts');
                const price = document.getElementById('priceProducts');
                const discount = document.getElementById('discountProducts');
                const tva = document.getElementById('tvaProducts');
                const qteDispo = document.getElementById('qteDispo');
                const article = document.getElementById('articleNom');
                const code = document.getElementById('codeProduct');
                if (select.value == null || select.value == undefined || select.value == 0 || select.value == '') {
                    return;
                } else {
                    @if ($type != 3)
                        products[index] = {
                            id: select.value,
                            name: article.value,
                            quantité: parseFloat(quantité.value).toFixed(0),
                            price: parseFloat(price.value).toFixed(3),
                            discount: parseFloat(discount.value).toFixed(2),
                            tva: parseFloat(tva.value).toFixed(2),
                            code: code.value,

                        };
                    @else
                        const p = originalProducts.find((p) => p.id == products[index].id);
                        products[index] = {
                            id: select.value,
                            name: article.value,
                            quantité: parseFloat(quantité.value).toFixed(0),
                            price: parseFloat(p.price).toFixed(3),
                            discount: parseFloat(0).toFixed(2),
                            tva: parseFloat(p.tva).toFixed(2),
                            code: code.value,

                        };
                    @endif
                    $('#searchForm').find('.clear').each(function(index, button) {
                        button.click();
                    });
                    select.value = 0;
                    article.value = "";
                    code.value = "";
                    quantité.value = 0;
                    @if ($type != 3)
                        price.value = 0;
                        discount.value = 0;
                        tva.value = 0;
                    @endif
                    qteDispo.value = 0;
                    button.innerHTML = 'Ajouter';
                    update = false;
                    index = 0;
                    const annuler = document.getElementById('annuler');
                    annuler.innerHTML = '';
                    updateTable();
                }
            } else {
                const select = document.getElementById('selectProducts');
                const quantité = document.getElementById('quantitéProducts');
                @if ($type != 3)
                    const price = document.getElementById('priceProducts');
                    const discount = document.getElementById('discountProducts');
                    const tva = document.getElementById('tvaProducts');
                    const qteDispo = document.getElementById('qteDispo');
                @endif
                const article = document.getElementById('articleNom');
                const code = document.getElementById('codeProduct');
                if (select.value == null || select.value == undefined || select.value == 0 || select.value == '') {
                    return;
                } else {
                    @if ($type != 3)
                        products.push({
                            id: select.value,
                            name: article.value,
                            quantité: parseFloat(quantité.value).toFixed(0),
                            price: parseFloat(price.value).toFixed(3),
                            discount: parseFloat(discount.value).toFixed(2),
                            tva: parseFloat(tva.value).toFixed(2),
                            code: code.value,

                        });
                    @else
                        const p = originalProducts.find((p) => p.id == select.value);
                        products.push({
                            id: select.value,
                            name: article.value,
                            quantité: parseFloat(quantité.value).toFixed(0),
                            price: parseFloat(p.price).toFixed(3),
                            discount: parseFloat(0).toFixed(2),
                            tva: parseFloat(p.tva).toFixed(2),
                            code: code.value,

                        });
                    @endif
                    $('#searchForm').find('.clear').each(function(index, button) {
                        button.click();
                    });
                    article.value = "";
                    code.value = "";
                    select.value = 0;
                    quantité.value = 0;
                    @if ($type != 3)
                        price.value = 0;
                        discount.value = 0;
                        tva.value = 0;
                    @endif
                    qteDispo.value = 0;
                    updateTable();
                }
            }
        })

        function updateTable() {
            const tbody = document.getElementById('tbody');
            tbody.innerHTML = '';
            let totalHtFooter = 0;
            let totalRemiseFooter = 0;
            let totalHtNetFooter = 0;
            let totalTvaFooter = 0;
            let totalFooter = 0;

            products.forEach((product) => {
                const p = originalProducts.find((p) => p.id == product.id);
                totalHtFooter += parseFloat(product.quantité * product.price);
                totalRemiseFooter += parseFloat(product.quantité * product.price * product.discount / 100);
                totalHtNetFooter += parseFloat(product.quantité * product.price - product.quantité * product.price *
                    product.discount / 100);
                totalTvaFooter += parseFloat(product.quantité * product.price * product.tva / 100);
                totalFooter += parseFloat((product.quantité * product.price - product.quantité * product.price *
                    product.discount / 100) + (product.quantité * product.price * product.tva / 100));
                const price = parseFloat(product.quantité * product.price * (100 - product.discount) / 100);
                tbody.innerHTML += `
                    <tr id="p-${product.id}">
                        <td>${p.code == null ? "":p.code}</td>
                        <td>${product.name ? product.name : p.name}</td>
                        <td>${parseFloat(product.quantité).toFixed(0)}</td>
                        @if ($type != 3)
                        <td>${product.price}</td>
                        <td>${parseFloat(product.quantité * product.price).toFixed(3)}</td>
                        <td>${parseFloat(product.discount).toFixed(2)} %</td>
                        <td>${parseFloat(product.quantité * product.price * product.discount / 100).toFixed(3)}</td>
                        <td>${parseFloat(product.quantité * product.price - product.quantité * product.price * product.discount / 100).toFixed(3)}</td>
                        <td>${parseFloat(product.tva).toFixed(2)} %</td>
                        <td>${parseFloat(price * product.tva / 100).toFixed(3)}</td>
                        <td>${parseFloat(price+(price* product.tva / 100)).toFixed(3)}</td>
                        @endif
                        @if (Auth::user()->role_id == 1)
                        <td>
                            <button type="button" class="btn btn-warning" onclick="updateProduct('${product.id}','${product.quantité}','${product.price}')">Modifier</button>
                            <button type="button" class="btn btn-danger" onclick="removeProduct('p-${product.id}','${product.quantité}','${product.price}')">Supprimer</button>
                        </td>
                        @endif
                    </tr>
                `;
            })
            const tfoot = document.getElementById('tfoot');
            tfoot.innerHTML = `
                <tr>
                    <th colspan="4"></th>
                    @if ($type != 3)
                    <th style="color: red;">${parseFloat(totalHtFooter).toFixed(3)}</th>
                    <td></td>
                    <th style="color: red;">${parseFloat(totalRemiseFooter).toFixed(3)}</th>
                    <th style="color: red;">${parseFloat(totalHtNetFooter).toFixed(3)}</th>
                    <td></td>
                    <th style="color: red;">${parseFloat(totalTvaFooter).toFixed(3)}</th>
                    <th style="color: red;">${parseFloat(totalFooter).toFixed(3)}</th>
                    @endif
                    @if (Auth::user()->role_id == 1)
                    <td></td>
                    @endif
                </tr>
            `;
        }
        updateTable();

        function removeProduct(id, quantité, prix) {
            const p_id = id.split('-')[1];
            const prod = products.find((p) => p.id == p_id && p.quantité == quantité
                @if ($type != 3)
                    &&
                    p.price == prix
                @endif );
            const index = products.indexOf(prod);
            products.splice(index, 1);
            updateTable();
        }

        function updateProduct(id, quantity, prix) {
            const select = document.getElementById('selectProducts');
            const article = document.getElementById('articleNom')
            const quantité = document.getElementById('quantitéProducts');
            @if ($type != 3)
                const price = document.getElementById('priceProducts');
                const discount = document.getElementById('discountProducts');
                const tva = document.getElementById('tvaProducts');
            @endif
            const product = products.find((p) => p.id == id && p.quantité == quantity && p.price == prix);
            const selectedProducts = products.filter((p) => p.id == select.value);

            const sumQuantity = selectedProducts.reduce((acc, product) => {
                return acc + (parseInt(product.quantity) || 0);
            }, 0);
            const qteDispo = document.getElementById('qteDispo');
            const p = originalProducts.find((p) => p.id == product.id);
            productSelectize[0].selectize.setValue(product.id);
            qteDispo.value = p.quantity - sumQuantity + parseFloat(product.quantité);
            article.value = product.name ? product.name : p.name;
            select.value = product.id;
            quantité.value = parseFloat(product.quantité).toFixed(0);
            @if ($type != 3)
                price.value = parseFloat(product.price).toFixed(3);
                discount.value = parseFloat(product.discount).toFixed(2);
                if (getClient()) {
                    tva.value = 0;
                } else {
                    tva.value = parseFloat(product.tva).toFixed(2);
                }
            @endif
            const annuler = document.getElementById('annuler');

            annuler.innerHTML = `
            <div class="form-group">
                <button type="button" class="btn btn-danger w-100" id="annulerProduct">Annuler</button>
            </div>`;
            const annulerProduct = document.getElementById('annulerProduct');
            annulerProduct.addEventListener('click', () => {
                $('#searchForm').find('.clear').each(function(index, button) {
                    button.click();
                });
                select.value = 0;
                article.value = "";
                quantité.value = 0;
                @if ($type != 3)
                    price.value = 0;
                    discount.value = 0;
                    qteDispo.value = 0;
                    if (getClient()) {
                        tva.value = 0;
                    } else {
                        tva.value = product.tva;
                    }
                @endif
                annuler.innerHTML = '';
                button.innerHTML = 'Ajouter';
                update = false;
                index = 0;
            })
            button.innerHTML = 'Modifier';
            update = true;
            index = products.indexOf(product);
            window.scrollTo({
                top: 100, // Scroll to the top of the page
                behavior: "smooth", // Smooth scrolling effect
            });
        }


        const form = document.getElementById('form');
        const formSubmit = document.getElementById('formSubmit');
        formSubmit.addEventListener('click', (e) => {
            e.preventDefault();
            const productsInput = document.getElementById('productsInput');
            productsInput.value = JSON.stringify(products);

            // Define the URL dynamically if $statement exists
            let url = "{{ route('statements.store') }}";
            @if ($statement)
                url = `{{ route('statements.update', $statement->id) }}`;
            @endif
            formSubmit.disabled = true;


            axios.post(url, {
                    _token: '{{ csrf_token() }}', // CSRF token
                    client_id: clientSelectize[0].selectize.getValue(), // Client ID
                    date: form.querySelector('input[name="date"]').value, // Date
                    type: "{{ $type }}",
                    @if ($type == 1)

                        timbreFiscal: form.querySelector('input[name="timbreFiscal"]').value, // Timbre fiscal
                    @endif
                    items: productsInput.value,
                    comment: form.querySelector('textarea[name="comment"]').value,
                })
                .then((response) => {

                    Toastify({
                        text: response.data.success,
                        duration: 3000,
                        close: true,
                        gravity: "bottom",
                        position: "right",
                        backgroundColor: "#4fbe87",
                    }).showToast()
                    setTimeout(() => {
                        window.location.href = response.data.redirect
                    }, 1500);
                })
                .catch((error) => {
                    console.log(error)

                    Toastify({
                        text: error.response.data.message,
                        duration: 3000,
                        close: true,
                        gravity: "bottom",
                        position: "left",
                        backgroundColor: "red",
                    }).showToast();
                    window.scrollTo({
                        top: 0, // Scroll to the top of the page
                        behavior: "smooth", // Smooth scrolling effect
                    });
                    formSubmit.disabled = false;
                });
        });



        function getClient() {
            const selectClients = document.getElementById('selectClients');
            const client_id = selectClients.value;
            client = clients.find((c) => c.id == client_id);
            return client != null && client != 'undefined' ? client.is_exempt_tva : false;
        }
        @if ($type == 1)
            function updateItem(id, job) {
                var route = "{{ route('reglements.update', 5) }}";
                route = route.slice(0, route.lastIndexOf("/")) + "/" + id

                $('#edit').modal('show');
                $('#edit form input[name="date"]').val(job.date);
                $('#edit form input[name="montant"]').val(job.montant);
                $('#edit form select[name="mode_paiment_id"]').val(job.mode_paiment_id);
                $('#edit form select[name="statut"]').val(job.statut);
                $('#edit form').attr('action', route);
            }

            function deleteItem(id) {
                var route = "{{ route('reglements.delete', 5) }}";
                route = route.slice(0, route.lastIndexOf("/")) + "/" + id
                $('#deleteForm').attr('action', route);
                $('#deleteForm').submit();

            }
        @endif
    </script>
@endsection
