

<?php $__env->startSection('title', 'Cost Center Management'); ?>

<?php $__env->startSection('content'); ?>
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Cost Center Management</h3>
                </div>
                <div class="card-body">
                    <!-- Finished Goods Selection -->
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <label for="finished_goods_select" class="form-label">Select Finished Good:</label>
                            <select id="finished_goods_select" class="form-select">
                                <option value="">Loading finished goods...</option>
                            </select>
                            <div id="loading_indicator" class="spinner-border spinner-border-sm mt-2" role="status" style="display: none;">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                        </div>
                    </div>

                    <!-- Chart of Accounts Tree -->
                    <div id="chart_of_accounts_tree" class="border p-3" style="max-height: 600px; overflow-y: auto;">
                        <div class="text-center text-muted">
                            <i class="fas fa-info-circle"></i> Select a finished good to view cost factors
                        </div>
                    </div>

                    <!-- Action Buttons -->
                    <div class="row mt-4" id="action_buttons" style="display: none;">
                        <div class="col-12">
                            <button type="button" class="btn btn-primary" id="update_cost_centers">
                                <i class="fas fa-save"></i> Update Cost Centers
                            </button>
                            <button type="button" class="btn btn-secondary" id="reset_selection">
                                <i class="fas fa-undo"></i> Reset
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('styles'); ?>
<style>
.chart-of-account-checkbox {
    transform: scale(1.2);
    margin-right: 8px;
}
.chart-of-account-checkbox:checked + label {
    color: #0d6efd;
    font-weight: bold;
}
.account-checkbox {
    margin-left: 20px;
}
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
$(document).ready(function() {
    let selectedItemId = null;
    let chartOfAccountsTree = null;
    let preSelectedAccounts = [];

    // Load finished goods on page load
    loadFinishedGoods();

    // Handle finished goods selection
    $('#finished_goods_select').on('change', function() {
        selectedItemId = $(this).val();
        if (selectedItemId) {
            loadCostCenterData(selectedItemId);
        } else {
            resetInterface();
        }
    });

    // Handle update button click
    $('#update_cost_centers').on('click', function() {
        if (selectedItemId) {
            updateCostCenters(selectedItemId);
        }
    });

    // Handle reset button click
    $('#reset_selection').on('click', function() {
        if (selectedItemId) {
            loadCostCenterData(selectedItemId);
        }
    });

    // Handle chart of account checkbox changes
    $(document).on('change', '.chart-of-account-checkbox', function() {
        const chartOfAccountId = $(this).data('chart-of-account-id');
        const isChecked = $(this).is(':checked');

        // Toggle all account checkboxes under this chart of account
        $(`.account-checkbox[data-chart-of-account-id="${chartOfAccountId}"]`).prop('checked', isChecked);
    });

    // Handle account checkbox changes
    $(document).on('change', '.account-checkbox', function() {
        const chartOfAccountId = $(this).data('chart-of-account-id');
        const accountCheckboxes = $(`.account-checkbox[data-chart-of-account-id="${chartOfAccountId}"]`);
        const checkedCount = accountCheckboxes.filter(':checked').length;
        const totalCount = accountCheckboxes.length;

        // Update chart of account checkbox based on account selections
        const chartCheckbox = $(`.chart-of-account-checkbox[data-chart-of-account-id="${chartOfAccountId}"]`);
        if (checkedCount === 0) {
            chartCheckbox.prop('checked', false);
        } else if (checkedCount === totalCount) {
            chartCheckbox.prop('checked', true);
        } else {
            chartCheckbox.prop('indeterminate', true);
        }
    });

    function loadFinishedGoods() {
        console.log('Loading finished goods...');
        $('#loading_indicator').show();

        $.ajax({
            url: '/api/cost-centers/finished-goods',
            method: 'GET',
            success: function(response) {
                console.log('Finished goods response:', response);
                $('#loading_indicator').hide();

                if (response.success) {
                    const select = $('#finished_goods_select');
                    select.empty().append('<option value="">Choose a finished good...</option>');

                    if (response.data && response.data.length > 0) {
                        console.log('Found', response.data.length, 'finished goods');
                        response.data.forEach(function(item) {
                            console.log('Adding finished good:', item.name, 'ID:', item.id);
                            select.append(`<option value="${item.id}">${item.name}</option>`);
                        });
                    } else {
                        console.log('No finished goods found');
                        select.append('<option value="">No finished goods found</option>');
                    }
                } else {
                    console.error('Error loading finished goods:', response.message);
                    $('#finished_goods_select').html('<option value="">Error loading finished goods</option>');
                }
            },
            error: function(xhr) {
                $('#loading_indicator').hide();
                console.error('Error loading finished goods:', xhr.responseText);
                $('#finished_goods_select').html('<option value="">Error loading finished goods</option>');
            }
        });
    }

    function loadCostCenterData(itemId) {
        $.ajax({
            url: `/api/cost-centers/form-data?item_id=${itemId}`,
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    chartOfAccountsTree = response.data.chart_of_accounts_tree;
                    preSelectedAccounts = response.data.pre_selected_accounts;
                    renderChartOfAccountsTree();
                    $('#action_buttons').show();
                }
            },
            error: function(xhr) {
                console.error('Error loading cost center data:', xhr.responseText);
            }
        });
    }

    function renderChartOfAccountsTree() {
        const container = $('#chart_of_accounts_tree');
        container.empty();

        if (!chartOfAccountsTree || chartOfAccountsTree.length === 0) {
            container.html('<div class="text-center text-muted">No chart of accounts data available</div>');
            return;
        }

        chartOfAccountsTree.forEach(function(parentAccount) {
            const parentDiv = createAccountDiv(parentAccount, 0);
            container.append(parentDiv);
        });
    }

    function createAccountDiv(account, level) {
        const div = $(`
            <div class="mb-2" style="margin-left: ${level * 20}px;">
                <div class="d-flex align-items-center">
                    <div class="form-check me-2">
                        <input class="form-check-input chart-of-account-checkbox"
                               type="checkbox"
                               value="${account.id}"
                               data-chart-of-account-id="${account.id}"
                               id="chart-${account.id}">
                        <label class="form-check-label fw-bold" for="chart-${account.id}">
                            ${account.name}
                        </label>
                    </div>
                </div>
            </div>
        `);

        // Check if this chart of account is pre-selected
        const isChartOfAccountSelected = preSelectedAccounts.some(selected =>
            selected.chart_of_account_id === account.id && !selected.account_id
        );

        // Update the chart of account checkbox
        if (isChartOfAccountSelected) {
            div.find('.chart-of-account-checkbox').prop('checked', true);
        }

        // Add accounts if they exist
        if (account.accounts && account.accounts.length > 0) {
            account.accounts.forEach(function(acc) {
                const isChecked = preSelectedAccounts.some(selected =>
                    selected.chart_of_account_id === account.id && selected.account_id === acc.id
                );

                const accountDiv = $(`
                    <div class="form-check ms-3 mb-1" style="margin-left: ${(level + 1) * 20}px;">
                        <input class="form-check-input account-checkbox"
                               type="checkbox"
                               value="${account.id}-${acc.id}"
                               data-chart-of-account-id="${account.id}"
                               data-account-id="${acc.id}"
                               ${isChecked ? 'checked' : ''}>
                        <label class="form-check-label">${acc.name}</label>
                    </div>
                `);
                div.append(accountDiv);
            });
        }

        // Add children recursively
        if (account.children && account.children.length > 0) {
            account.children.forEach(function(child) {
                const childDiv = createAccountDiv(child, level + 1);
                div.append(childDiv);
            });
        }

        return div;
    }

    function updateCostCenters(itemId) {
        const selectedAccounts = [];
        const selectedChartOfAccounts = [];

        // Collect selected accounts
        $('.account-checkbox:checked').each(function() {
            selectedAccounts.push({
                chart_of_account_id: $(this).data('chart-of-account-id'),
                account_id: $(this).data('account-id')
            });
        });

        // Collect selected chart of accounts
        $('.chart-of-account-checkbox:checked').each(function() {
            selectedChartOfAccounts.push({
                chart_of_account_id: $(this).data('chart-of-account-id')
            });
        });

        $.ajax({
            url: '/api/cost-centers/assignments',
            method: 'POST',
            data: {
                item_id: itemId,
                assignments: selectedAccounts,
                chart_of_accounts: selectedChartOfAccounts,
                _token: $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    alert('Cost centers updated successfully!');
                    // Reload the data to reflect changes
                    loadCostCenterData(itemId);
                } else {
                    alert('Error updating cost centers: ' + response.message);
                }
            },
            error: function(xhr) {
                console.error('Error updating cost centers:', xhr.responseText);
                alert('Error updating cost centers. Please try again.');
            }
        });
    }

    function resetInterface() {
        $('#chart_of_accounts_tree').html('<div class="text-center text-muted"><i class="fas fa-info-circle"></i> Select a finished good to view cost factors</div>');
        $('#action_buttons').hide();
        selectedItemId = null;
        chartOfAccountsTree = null;
        preSelectedAccounts = [];
    }
});
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\habibcables-ERP\resources\views\manufacturing\cost-centers\index.blade.php ENDPATH**/ ?>