<style>
    .card {
        border-radius: 12px;
        box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
    }

    .table {
        border-radius: 8px;
        overflow: hidden;
    }

    th {
        text-align: center;
        background-color: #343a40 !important;
        color: white;
    }

    tbody tr:hover {
        background-color: rgba(0, 0, 0, 0.05);
    }

    .btn-primary {
        border-radius: 8px;
        font-weight: bold;
    }

    .bg-primary {
        background-color: #007bff !important;
    }

    .bg-success {
        background-color: #28a745 !important;
    }

    .bg-warning {
        background-color: #ffc107 !important;
    }
</style>

<div class="content-wrapper">
    <section class="content-header">
        <h1> Rapports des performances</h1>
        <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-home"></i> Accueil</a></li>
            <li class="active" onclick="window.history.back()" style="cursor: pointer;"> Rapports</li>
        </ol>
    </section>

    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-12">
                    <div class="card shadow-sm border-0">
                        <div class="card-header bg-primary text-white">
                            <h3 class="card-title m-0"> Gérer les Performances</h3>
                        </div>

                        <div class="card-body">
                            <!-- Product Details -->
                            <div class="row mt-4">
                                <div class="col-md-12 col-lg-12">
                                    <div class="card shadow-sm border-0">
                                        <div class="card-header bg-success text-white">
                                            <h3 class="card-title m-0"> performances des commercials</h3>
                                        </div>
                                        <div class="card-body">
                                            <div class="row g-3 align-items-center mb-4" style="margin: 5px 0 5px 5px;">
                                                <div class="col-md-3">
                                                    <label for="startDate" class="form-label">Date de début</label>
                                                    <input type="date" id="startDate" class="form-control">
                                                </div>
                                                <div class="col-md-3">
                                                    <label for="endDate" class="form-label">Date de fin</label>
                                                    <input type="date" id="endDate" class="form-control">
                                                </div>
                                                <div class="col-md-3">
                                                    <label for="pvente" class="form-label">Points de ventes</label>
                                                    <select name="" id="pvente" class="form-control">
                                                        <option value="TOUS">TOUS</option>
                                                        <?php
                                                        foreach ($stores as $value) {
                                                            ?>
                                                            <option value="<?= $value['name']; ?>"><?= $value['name']; ?>
                                                            </option>
                                                            <?php
                                                        }

                                                        ?>
                                                    </select>
                                                </div>
                                                <div class="col-md-3 d-flex align-items-end">
                                                    <br>
                                                    <button id="filteredB1" class="btn btn-primary w-100">Filtrer
                                                        🔍</button>
                                                    <button id="ExportBTN1" class="btn btn-success w-100">Exporter
                                                        📤</button>
                                                </div>
                                            </div>
                                            <table id="commperformance" class="table table-hover table-striped">
                                                <thead>
                                                    <tr>
                                                        <th>Nom et prénom</th>
                                                        <th>Email</th>
                                                        <th>Motos vendue</th>
                                                        <th>Date de vente</th><!-- return 2025-04-18  -->
                                                        <th>Prix d'achat</th>
                                                        <th>Prix de vente</th>
                                                        <th>Point de ventes</th>
                                                        <th>Bénefices</th>
                                                    </tr>
                                                </thead>
                                                <tfoot>
                                                    <tr>
                                                        <th colspan="5" style="text-align:right">Total:</th>
                                                        <th></th> <!-- total Prix de vente -->
                                                        <th></th>
                                                        <th></th> <!-- total Bénéfices -->
                                                    </tr>
                                                </tfoot>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card shadow-sm border-0">
                        <div class="card-body">
                            <!-- Product Details -->
                            <div class="row mt-4">
                                <div class="col-md-12 col-lg-12">
                                    <div class="card shadow-sm border-0">
                                        <div class="card-header bg-success text-white">
                                            <h3 class="card-title m-0">📈 performances des Mécanicien</h3>
                                        </div>
                                        <div class="card-body">
                                            <div class="row g-3 align-items-center mb-4" style="margin: 5px 0 5px 5px;">
                                                <div class="col-md-3">
                                                    <label for="startDate2" class="form-label">Date de début</label>
                                                    <input type="date" id="startDate" class="form-control">
                                                </div>
                                                <div class="col-md-3">
                                                    <label for="endDate2" class="form-label">Date de fin</label>
                                                    <input type="date" id="endDate" class="form-control">
                                                </div>
                                                <div class="col-md-3">
                                                    <label for="pvente" class="form-label">Points de ventes</label>
                                                    <select name="" id="pvente2" class="form-control">
                                                        <option value="TOUS">TOUS</option>
                                                        <?php
                                                        foreach ($stores as $value) {
                                                            ?>
                                                            <option value="<?= $value['name']; ?>"><?= $value['name']; ?>
                                                            </option>
                                                            <?php
                                                        }

                                                        ?>
                                                    </select>
                                                </div>
                                                <div class="col-md-3 d-flex align-items-end">
                                                    <br>
                                                    <button id="filteredB2" class="btn btn-primary w-100">Filtrer
                                                        🔍</button>
                                                    <button id="ExportBTN2" class="btn btn-success w-100">Exporter
                                                        📤</button>
                                                </div>
                                            </div>
                                            <table id="mecperformance" class="table table-hover table-striped">
                                                <thead>
                                                    <tr>
                                                        <th>Nom et prénom</th>
                                                        <th>Email</th>
                                                        <th>Motos vendue</th>
                                                        <th>Date de vente</th><!-- return 2025-04-18  -->
                                                        <th>Prix d'achat</th>
                                                        <th>Prix de vente</th>
                                                        <th>Point de ventes</th>
                                                        <th>Bénefices</th>
                                                    </tr>
                                                </thead>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
    </section>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script>
    var manageTable;

    $(document).ready(function () {
        $("#reportNav").addClass('active');

        // Initialize the datatable
        
        manageTable = $('#commperformance').DataTable({
            'ajax': 'fetchPerformances',
            'order': [],
            'pageLength': 5,
            'lengthMenu': [
                [5, 10, 25, 50, -1],
                [5, 10, 25, 50, "All"]
            ],
            "columnDefs": [{
                "targets": 3, // Ensure date column is not searchable (we handle it manually)
                "searchable": false
            }],
            "footerCallback": function (row, data, start, end, display) {
                const api = this.api();

                // Helper function to parse string to float
                const parseNumber = function (i) {
                    return typeof i === 'string' ?
                        parseFloat(i.replace(/[^\d.-]/g, '')) : // remove currency symbols, commas
                        typeof i === 'number' ?
                            i : 0;
                };

                // Calculate total for Prix de vente (column 5)
                const totalPrixVente = api
                    .column(5, { page: 'current' })
                    .data()
                    .reduce((a, b) => parseNumber(a) + parseNumber(b), 0);

                // Calculate total for Bénefices (column 7)
                const totalBenefices = api
                    .column(7, { page: 'current' })
                    .data()
                    .reduce((a, b) => parseNumber(a) + parseNumber(b), 0);

                // Update footer
                $(api.column(5).footer()).html(totalPrixVente.toFixed(2));
                $(api.column(7).footer()).html(totalBenefices.toFixed(2));
            }
        });

        $('#filteredB1').on('click', function () {
            const startDate = $('#startDate').val();
            const endDate = $('#endDate').val();
            const pvente = $('#pvente').val();

            // Get all original data (you may need to fetch from server or already loaded)
            manageTable.ajax.url('fetchPerformances').load(function () {
                const filteredData = [];

                manageTable.rows().every(function () {
                    const data = this.data();
                    const saleDate = data[3].split(' ')[0]; // extract YYYY-MM-DD from date
                    const store = data[6];

                    // Filter logic
                    const dateMatch = (!startDate && !endDate) ||
                        (startDate && endDate && saleDate >= startDate && saleDate <= endDate) ||
                        (startDate && !endDate && saleDate >= startDate) ||
                        (!startDate && endDate && saleDate <= endDate);

                    const storeMatch = (pvente === 'TOUS' || pvente === store);

                    if (dateMatch && storeMatch) {
                        filteredData.push(data);
                    }
                });

                // Clear and reload table with filtered data
                manageTable.clear().rows.add(filteredData).draw();
            });
        });
    });

    document.getElementById('ExportBTN1').addEventListener('click', function () {
        // Select your table
        var table = document.getElementById('commperformance');

        // Convert it to a workbook
        var wb = XLSX.utils.table_to_book(table, {
            sheet: "Feuille1"
        });

        // Export it
        XLSX.writeFile(wb, 'export-commercial-performance.xlsx');
    });
</script>