<? session_start();
require_once("assets/php/_user_authenticate.php"); ?>
<!-- Login the User -->

<!-- This code generates the base URL for the website by combining the protocol, domain name, and directory path -->
<?php
    $rootFolder = basename($_SERVER['DOCUMENT_ROOT']);
    $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . str_replace('/pages', '', dirname($_SERVER['SCRIPT_NAME']));
?>
<!-- This code generates the base URL for the website by combining the protocol, domain name, and directory path -->

<!-- This code is useful for internal styles  -->
<?php ob_start(); ?>

    <!-- DATA TABLES CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.3.0/css/responsive.bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.2.3/css/buttons.bootstrap5.min.css">
    
    <!-- Style button location for datatable -->
    <style>
    .top-container {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 10px;
        gap: 10px;
    }

    .left-controls {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .dataTables_length {
        margin: 0;
    }

    .dt-buttons {
        display: flex;
        gap: 5px;
    }

    .dataTables_filter {
        margin: 0;
    }

    .dataTables_filter input {
        height: 30px;
        width: 200px;
    }
    
    #datatable-mailboxes thead th {
        white-space: nowrap;
        padding: 12px 10px;
        font-weight: 600;
        font-size: 1rem;
    }
    </style>
    <!-- Style button location for datatable -->

<?php $styles = ob_get_clean(); ?>
<!-- This code is useful for internal styles  -->

<!-- This code is useful for content -->
<?php ob_start(); ?>

                <div class="container-fluid">

                    <!-- Page Header -->
                    <div class="d-md-flex d-block align-items-center justify-content-between my-4 page-header-breadcrumb">
                        <h1 class="page-title fw-semibold fs-18 mb-0">Manage Customers</h1>
                        <div class="ms-md-1 ms-0">
                            <nav>
                                <ol class="breadcrumb mb-0">
                                    <li class="breadcrumb-item"><a href="javascript:void(0);">ShipApps</a></li>
                                    <li class="breadcrumb-item active" aria-current="page">Manage Customers</li>
                                </ol>
                            </nav>
                        </div>
                    </div>
                    <!-- Page Header Close -->

                    <!-- Start:: row-1 -->
                    <div class="row">
                        <div class="col-xxl-12">
                            <div class="card custom-card">
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-xl-12">
                                            <div class="card custom-card">
                                                <div class="card-header">
                                                    <div class="card-title">
                                                        Responsive Datatable
                                                    </div>
                                                </div>
                                                <div class="card-body">
                                                    <div id="customers-container">
                                                        <div class="table-responsive">
                                                            <table id="datatable-customers" class="table table-bordered table-hover text-nowrap" style="width:100%"></table>
                                                        </div>                                                          
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- End:: row-1 -->

                </div>

<?php $content = ob_get_clean(); ?>
<!-- This code is useful for content -->

<!-- This code is useful for internal scripts  -->
<?php ob_start(); ?>

    <!-- JQUERY JS -->
    <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>

    <!-- DATATABLES CDN JS -->
    <script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.12.1/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.3.0/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.3/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.3/js/buttons.print.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.6/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.3/js/buttons.html5.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>

<script>


$(function (e) {

    // responsive datatable
    $('#responsiveDataTable').DataTable({
        responsive: true,
        language: {
            searchPlaceholder: 'Search...',
            sSearch: '',
        },
        "pageLength": 10,
    });
    // responsive datatable
});

</script>

<script>
$(document).ready(function() {
        
    // customers datatable tab
    // Opens assets/php/_get_table_customers.php
    // Calls 
    //       

    var customersTable = $('#datatable-customers').DataTable({
        lengthMenu: [ [8, 25, 50, 100], [8, 25, 50, 100] ],
        pageLength: 8,
        dom: '<"top-container"<"left-controls"lB>f>rtip',
        buttons: [
            {
                text: 'New Customer',
                className: 'btn btn-secondary',
                action: function ( e, dt, node, config ) {
                    window.location.href = 'customer-new.php';
                }
            },
            {
                text: 'Merge Customers',
                className: 'btn btn-secondary',
                action: function ( e, dt, node, config ) {
                    window.location.href = 'customer-merge.php';
                }
            }
        ],
        order: [[0, 'asc']],
        language: {
            searchPlaceholder: 'Search...',
            sSearch: '',
        },
        processing: true,
        serverSide: true,
        ajax: 'assets/php/_get_customers.php',
        columns: [
            { title: "Name (Alias)" },
            { title: "Email" },
            { title: "Business" },
            { title: "customer_key", visible: false, searchable: false }
        ],
        autoWidth: false,
        scrollX: false,
        initComplete: function() {
            this.api().columns.adjust().draw();
        }
    });

    function loadEditForm(customerKey) {
        // Replace the whole container with the form loaded via AJAX
        // Assuming your container has id="customers-container"
        // And you have a PHP endpoint that returns the edit form HTML, e.g. 'customer-edit-form.php?customer_key=...'

        $.ajax({
            url: 'assets/php/form-customer-edit.php',
            method: 'GET',
            data: { customer_key: customerKey },
            success: function(response) {
                $('#customers-container').html(response);

                // Append Save and Close buttons below the form
                var buttonsHtml = `
                    <div class="mt-3">
                        <button id="saveCustomerBtn" class="btn btn-primary">Save</button>
                        <button id="closeFormBtn" class="btn btn-secondary ms-2">Close</button>
                    </div>
                `;
                $('#customers-container').append(buttonsHtml);

                // Bind Save and Close button events
                $('#saveCustomerBtn').on('click', function() {
                    saveCustomerForm(customerKey);
                });

                $('#closeFormBtn').on('click', function() {
                    reloadCustomersTable();
                });
            },
            error: function() {
                alert('Failed to load edit form.');
            }
        });
    }

    function saveCustomerForm(customerKey) {
        var form = $('#customerEditForm');
        if (!form.length) {
            alert('Form not found');
            return;
        }

        $.ajax({
            url: form.attr('action'), // form's action attribute
            method: form.attr('method') || 'POST',
            data: form.serialize(),
            success: function(response) {
                // Assuming response is JSON with success status
                if (response.success) {
                    alert('Customer updated successfully.');
                    reloadCustomersTable();
                } else {
                    alert(response.error || 'Failed to save customer.');
                }
            },
            error: function() {
                alert('Error saving customer.');
            }
        });
    }

    function reloadCustomersTable() {
    

        $('#customers-container').html('<table id="datatable-customers" class="table table-bordered table-hover text-nowrap" style="width:100%"></table>');
        // Reinitialize the DataTable (reuse your DataTable init code)
        customersTable = $('#datatable-customers').DataTable({
            lengthMenu: [ [8, 25, 50, 100], [8, 25, 50, 100] ],
            pageLength: 8,
            dom: '<"top-container"<"left-controls"lB>f>rtip',
            buttons: [
                {
                    text: 'New Customer',
                    className: 'btn btn-secondary',
                    action: function ( e, dt, node, config ) {
                        window.location.href = 'customer-new.php';
                    }
                },
                {
                    text: 'Merge Customers',
                    className: 'btn btn-secondary',
                    action: function ( e, dt, node, config ) {
                        window.location.href = 'customer-merge.php';
                    }
                }
            ],
            order: [[0, 'asc']],
            language: {
                searchPlaceholder: 'Search...',
                sSearch: '',
            },
            processing: true,
            serverSide: true,
            ajax: 'assets/php/_get_table_customers.php',
            columns: [
                { title: "Name (Alias)" },
                { title: "Email" },
                { title: "Business" },
                { title: "customer_key", visible: false, searchable: false }
            ],
            autoWidth: false,
            scrollX: false,
            initComplete: function() {
                this.api().columns.adjust().draw();
            }
        });

        // Re-attach row click handler
        $('#datatable-customers tbody').on('click', 'tr', function () {
            var data = customersTable.row(this).data();
            if (!data) return;
            var customerKey = data[3];
            if (!customerKey) {
                alert('Customer key not found.');
                return;
            }
            loadEditForm(customerKey);
        });
    }

    // Handle row click to load edit form via AJAX
    $('#datatable-customers tbody').on('click', 'tr', function () {
        var data = customersTable.row(this).data();
        if (!data) return;

        var customerKey = data[3]; // hidden customer_key column
        if (!customerKey) {
            alert('Customer key not found.');
            return;
        }
        loadEditForm(customerKey);
    });

    // Because customer_key is needed but not shown in table, add it as a row attribute when rendering table rows.
    // We can do this by listening to 'rowCallback' event and setting attribute for each row:
    $('#datatable-customers').on('xhr.dt', function ( e, settings, json, xhr ) {
        // After data loaded, add data-customer-key attributes to rows
        customersTable.rows().every(function(rowIdx, tableLoop, rowLoop){
            var rowData = this.data();
            var customerKey = json.data[rowIdx][3]; // If customer_key is returned as hidden 4th element - 
                                                // But currently, your PHP does not send customer_key in data array.
        });
    });

});
</script>
 

<?php $scripts = ob_get_clean(); ?>
<!-- This code is useful for internal scripts  -->

<!-- This code use for render base file -->
<?php include 'layouts/base.php'; ?>
<!-- This code use for render base file -->