<? 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>

    /* Row highlight */
    
    tr.selected {
        background-color: #cfe2ff !important;
    }

    /* Optional: disabled button styling improvement */
    #btn-merge-customers:disabled {
        opacity: 0.6;
        cursor: not-allowed;
    }

    .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">
                                                        Primary Customer
                                                    </div>
                                                </div>
                                                <div class="card-body">
                                                    <div id="customer-primary-container">
                                                        <div class="table-responsive">
                                                            <table id="datatable-customers-primary" class="table table-bordered table-hover text-nowrap" style="width:100%"></table>
                                                        </div>                                                          
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-xl-12">
                                            <div class="card custom-card">
                                                <div class="card-header">
                                                    <div class="card-title">
                                                        Customer to Merge
                                                    </div>
                                                </div>
                                                <div class="card-body">
                                                    <div id="customer-merge-container">
                                                        <div class="table-responsive">
                                                            <table id="datatable-customers-merge" class="table table-bordered table-hover text-nowrap" style="width:100%"></table>
                                                        </div>                                                          
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                    
                                        <button id="btn-merge-customers" class="btn btn-danger">
                                            Merge Customers
                                        </button>

                                    </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>

    <!-- INTERNAL DATATABLES JS -->


<script>
$(function (e) {

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

$(document).ready(function () {

// =============================
// GLOBAL STATE
// =============================
let primaryCustomerKey = null;
let mergeCustomerKey = null;

// Disable merge button initially
$('#btn-merge-customers').prop('disabled', true);

// =============================
// ENABLE / DISABLE BUTTON LOGIC
// =============================
function updateMergeButtonState() {
    if (primaryCustomerKey && mergeCustomerKey) {
        $('#btn-merge-customers').prop('disabled', false);
    } else {
        $('#btn-merge-customers').prop('disabled', true);
    }
}

// =============================
// TABLE FACTORY
// =============================
function createCustomerTable(selector) {
    return $(selector).DataTable({
        lengthMenu: [[3, 5, 12], [3, 5, 12]],
        pageLength: 3,
        dom: '<"top-container"<"left-controls"l>f>rtip',
        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();
        }
    });
}

// =============================
// INIT TABLES
// =============================
let primaryTable = createCustomerTable('#datatable-customers-primary');
let mergeTable   = createCustomerTable('#datatable-customers-merge');

// =============================
// PRIMARY SELECTION
// =============================
$('#datatable-customers-primary tbody').on('click', 'tr', function () {

    let data = primaryTable.row(this).data();
    if (!data) return;

    let selectedKey = data[3];

    // Duplicate detection
    if (mergeCustomerKey && selectedKey === mergeCustomerKey) {
        alert("This customer is already selected as the merge target. Please choose a different customer.");
        return;
    }

    $('#datatable-customers-primary tbody tr').removeClass('selected');
    $(this).addClass('selected');

    primaryCustomerKey = selectedKey;

    updateMergeButtonState();
});

// =============================
// MERGE SELECTION
// =============================
$('#datatable-customers-merge tbody').on('click', 'tr', function () {

    let data = mergeTable.row(this).data();
    if (!data) return;

    let selectedKey = data[3];

    // Duplicate detection
    if (primaryCustomerKey && selectedKey === primaryCustomerKey) {
        alert("You cannot merge a customer into itself. Please select a different customer.");
        return;
    }

    $('#datatable-customers-merge tbody tr').removeClass('selected');
    $(this).addClass('selected');

    mergeCustomerKey = selectedKey;

    updateMergeButtonState();
});

// =============================
// MERGE BUTTON CLICK
// =============================
$('#btn-merge-customers').on('click', function () {

    // Safety check (extra guard)
    if (!primaryCustomerKey || !mergeCustomerKey) {
        alert('Please select both customers.');
        return;
    }

    if (primaryCustomerKey === mergeCustomerKey) {
        alert('Invalid selection. Customers must be different.');
        return;
    }

    // Strong confirmation warning
    let confirmMerge = confirm(
        "Are you absolutely sure you want to merge these customers?\n\n" +
        "⚠️ This action CANNOT be undone.\n" +
        "All data from the selected customer will be merged into the primary customer."
    );

    if (!confirmMerge) return;

    $.ajax({
        url: 'assets/php/_merge_customers.php',
        type: 'POST',
        dataType: 'json',
        data: {
            primary_customer_key: primaryCustomerKey,
            merge_customer_key: mergeCustomerKey
        },
        success: function (response) {

            if (response && response.error) {
                alert('Merge failed: ' + response.error);
                return;
            }

            alert('Customers merged successfully.');

            // Reload tables
            primaryTable.ajax.reload(null, false);
            mergeTable.ajax.reload(null, false);

            // Reset state
            primaryCustomerKey = null;
            mergeCustomerKey = null;

            $('tr.selected').removeClass('selected');
            updateMergeButtonState();
        },
        error: function () {
            alert('Merge failed due to a server error.');
        }
    });
});

});

</script>




</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 -->