<?php 
require(ROOT_URL.'/includes/finance/finance_functions.php');

function enrep_statement_options(string $table, string $idColumn, string $nameColumn, string $where = ''): string
{
    $sql = "SELECT `$idColumn` AS id, `$nameColumn` AS name FROM `$table`";
    if ($where !== '') {
        $sql .= " WHERE $where";
    }
    $sql .= " ORDER BY `$nameColumn` ASC";

    $ret = '';
    $stmt = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $rows = $stmt->get_result();
    $stmt->close();

    while ($row = mysqli_fetch_assoc($rows)) {
        $ret .= '<option value="' . (int)$row['id'] . '">' . htmlspecialchars((string)$row['name'], ENT_QUOTES, 'UTF-8') . '</option>';
    }

    return $ret;
}

$today = date('d-m-Y');
$monthStart = date('01-m-Y');
$statementTenant = defined('TENANT_URL') ? trim((string)TENANT_URL, "/\\") : (string)($_REQUEST['tenant'] ?? '');
?>

<style>

.statement-panel {
    border: 1px solid rgba(0, 0, 0, .08);
    border-radius: 8px;
    background: #fff;
    box-shadow: 0 2px 10px rgba(0, 0, 0, .04);
}
.statement-target {
    display: none;
}
.statement-target.is-active {
    display: block;
}
.statement-toolbar {
    display: flex;
    flex-wrap: wrap;
    gap: .5rem;
    justify-content: flex-end;
}
#statementResult {
    min-height: 9rem;
}
</style>

<div class="statement-workspace">
    <div class="note note-secondary mb-3">
        <strong>Live statement generation</strong><br>
        Statements are built from invoice records for the selected target and date range. Client statements show client invoices; broker and agent statements show invoices raised to that account, with an optional client filter.
    </div>

    <div class="statement-panel p-3 p-md-4 mb-3">
        <div class="row align-items-end g-3">
            <div class="col-12 col-lg-3">
                <label for="statementTarget" class="form-label">Statement target</label>
                <select id="statementTarget" name="target" class="form-select form-select-sm" data-mdb-select-init>
                    <option value="client">Client statement</option>
                    <option value="broker">Broker statement</option>
                    <option value="agent">Agent statement</option>
                </select>
            </div>

            <div class="col-12 col-lg-3 statement-target is-active" data-target-field="client">
                <label for="statementClient" class="form-label">Client</label>
                <select id="statementClient" class="form-select form-select-sm" data-mdb-select-init data-mdb-filter="true">
                    <option value="0">All clients</option>
                    <?= enrep_statement_options('clientdetails', 'clientnumber', 'clientname', "`statuslive`='1'") ?>
                </select>
            </div>

            <div class="col-12 col-lg-3 statement-target" data-target-field="broker">
                <label for="statementBroker" class="form-label">Broker</label>
                <select id="statementBroker" class="form-select form-select-sm" data-mdb-select-init data-mdb-filter="true">
                    <option value="">Select broker</option>
                    <?= enrep_statement_options('brokers', 'broker_number', 'broker_name', "`statuslive`='1'") ?>
                </select>
            </div>

            <div class="col-12 col-lg-3 statement-target" data-target-field="agent">
                <label for="statementAgent" class="form-label">Agent</label>
                <select id="statementAgent" class="form-select form-select-sm" data-mdb-select-init data-mdb-filter="true">
                    <option value="">Select agent</option>
                    <?= enrep_statement_options('agents', 'agent_number', 'agent_name', "`statuslive`='1'") ?>
                </select>
            </div>

            <div class="col-12 col-lg-3 statement-target" data-target-field="broker-agent-client">
                <label for="statementRelatedClient" class="form-label">Client filter</label>
                <select id="statementRelatedClient" class="form-select form-select-sm" data-mdb-select-init data-mdb-filter="true">
                    <option value="0">All linked clients</option>
                    <?= enrep_statement_options('clientdetails', 'clientnumber', 'clientname', "`statuslive`='1'") ?>
                </select>
            </div>

            <div class="col-12 col-md-4 col-lg-2">
                <label for="statementStatus" class="form-label">Invoice status</label>
                <select id="statementStatus" class="form-select form-select-sm" data-mdb-select-init>
                    <option value="both">Paid and unpaid</option>
                    <option value="unpaid">Unpaid only</option>
                    <option value="paid">Paid only</option>
                </select>
            </div>

            <div class="col-12 col-md-4 col-lg-2">
                <label for="statementStart" class="form-label">From</label>
                <div class="date-picker" data-date-type="open" data-mdb-toggle-button="false">
                    <input id="statementStart" class="form-control form-control-sm" type="text" value="<?= $monthStart ?>" data-mdb-confirm-date-on-select="true" data-mdb-toggle="datepicker" data-mdb-format="dd-mm-yyyy">
                </div>
            </div>

            <div class="col-12 col-md-4 col-lg-2">
                <label for="statementEnd" class="form-label">To</label>
                <div class="date-picker" data-date-type="open" data-mdb-toggle-button="false">
                    <input id="statementEnd" class="form-control form-control-sm" type="text" value="<?= $today ?>" data-mdb-confirm-date-on-select="true" data-mdb-toggle="datepicker" data-mdb-format="dd-mm-yyyy">
                </div>
            </div>

            <div class="col-12 col-lg-2 statement-toolbar">
                <button type="button" id="statementRun" class="btn btn-info btn-sm">
                    <i class="fad fa-file-invoice-dollar me-1"></i> Generate
                </button>
                <button type="button" id="statementReset" class="btn btn-outline-secondary btn-sm">
                    <i class="fad fa-undo me-1"></i> Reset
                </button>
            </div>
        </div>
    </div>

    <div id="statementResult" class="statement-panel p-3 p-md-4">
        <div class="text-center text-muted py-4">
            <i class="fad fa-file-invoice fa-2x mb-2"></i>
            <div>Select the target, date range, and invoice status to generate a live statement.</div>
        </div>
    </div>
</div>

<script>
var statementTenant = <?= json_encode($statementTenant, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_SLASHES) ?>;

(function() {
    var targetSelect = document.getElementById('statementTarget');
    var clientSelect = document.getElementById('statementClient');
    var relatedClientSelect = document.getElementById('statementRelatedClient');
    var brokerSelect = document.getElementById('statementBroker');
    var agentSelect = document.getElementById('statementAgent');
    var statusSelect = document.getElementById('statementStatus');
    var startInput = document.getElementById('statementStart');
    var endInput = document.getElementById('statementEnd');
    var result = document.getElementById('statementResult');
    var initialResult = result.innerHTML;

    var navBox = document.getElementById('navBox');
    if (navBox) {
        navBox.innerHTML = '<li class="breadrumb-item"><a href="index.php?t=includes/finance&p=finance_invoices.php">Finance</a><i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadrumb-item active">Statements</li>';
    }

    function notify(type, message) {
        if (typeof showResponse === 'function') {
            showResponse(type, message);
            return;
        }
        result.insertAdjacentHTML('afterbegin', '<div class="alert alert-' + (type === 'warning' ? 'warning' : 'info') + '">' + message + '</div>');
    }

    function updateTargetFields() {
        var target = targetSelect.value;
        document.querySelectorAll('.statement-target').forEach(function(el) {
            var field = el.dataset.targetField;
            var active = field === target || (field === 'broker-agent-client' && target !== 'client');
            el.classList.toggle('is-active', active);
        });
    }

    function selectedAccountNumber(target) {
        if (target === 'broker') {
            return brokerSelect.value;
        }
        if (target === 'agent') {
            return agentSelect.value;
        }
        return clientSelect.value;
    }

    async function loadStatement() {
        var target = targetSelect.value;
        var accountNumber = selectedAccountNumber(target);
        var clientNumber = target === 'client' ? clientSelect.value : relatedClientSelect.value;

        if ((target === 'broker' || target === 'agent') && accountNumber === '') {
            notify('warning', 'Please select a ' + target + ' before generating the statement');
            return;
        }
        if (startInput.value === '' || endInput.value === '') {
            notify('warning', 'Please select a statement date range');
            return;
        }

        result.innerHTML = '<div class="text-center py-5"><i class="fad fa-spinner-third fa-spin fa-2x text-info mb-2"></i><div>Generating statement</div></div>';

        var params = new URLSearchParams();
        params.set('mode', 'render');
        params.set('tenant', statementTenant);
        params.set('target', target);
        params.set('account_number', accountNumber);
        params.set('clientnumber', clientNumber);
        params.set('status', statusSelect.value);
        params.set('start', startInput.value);
        params.set('end', endInput.value);

        try {
            var rootUrl = typeof ROOT_URL !== 'undefined' ? ROOT_URL.replace(/\/$/, '') : '';
            var statementUrl = rootUrl + '/includes/finance/statement_data.php?' + params.toString();
            var response = await fetch(statementUrl, {
                credentials: 'same-origin',
                headers: {
                    'X-Requested-With': 'fetch'
                }
            });
            result.innerHTML = await response.text();
        } catch (error) {
            result.innerHTML = '<div class="alert alert-danger mb-0">Statement generation failed. Please try again.</div>';
        }
    }

    targetSelect.addEventListener('change', updateTargetFields);
    document.getElementById('statementRun').addEventListener('click', loadStatement);
    document.getElementById('statementReset').addEventListener('click', function() {
        targetSelect.value = 'client';
        clientSelect.value = '0';
        relatedClientSelect.value = '0';
        brokerSelect.value = '';
        agentSelect.value = '';
        statusSelect.value = 'both';
        startInput.value = '<?= $monthStart ?>';
        endInput.value = '<?= $today ?>';
        result.innerHTML = initialResult;
        updateTargetFields();
    });
    updateTargetFields();
})();

function enrepEscapeStatementHtml(value) {
    return String(value === null || typeof value === 'undefined' ? '' : value).replace(/[&<>"']/g, function(char) {
        if (char === '&') return '&amp;';
        if (char === '<') return '&lt;';
        if (char === '>') return '&gt;';
        if (char === '"') return '&quot;';
        return '&#039;';
    });
}

window.enrepPrintStatement = async function(scriptPath, header, client) {
    if (typeof printContainer !== 'function') {
        window.print();
        return;
    }

    var rootUrl = typeof ROOT_URL !== 'undefined' ? ROOT_URL.replace(/\/$/, '') : '';
    var tenant = statementTenant || (typeof TENANT_URL !== 'undefined' ? TENANT_URL : '');
    var basePath = /^https?:\/\//i.test(scriptPath) || scriptPath.charAt(0) === '/'
        ? scriptPath
        : rootUrl + '/' + scriptPath.replace(/^\/+/, '');
    var url = new URL(basePath, window.location.origin);

    if (client !== null && typeof client !== 'undefined') {
        url.searchParams.set('clientnumber', client);
    }
    if (!url.searchParams.has('tenant')) {
        url.searchParams.set('tenant', tenant);
    }

    var response = await fetch(url.toString(), {
        credentials: 'same-origin'
    });
    if (!response.ok) return;

    var contentHtml = await response.text();
    var safeHeader = enrepEscapeStatementHtml(header);

    printContainer(contentHtml, {
        orientation: 'landscape',
        header: '<p>' + safeHeader + '</p>',
        footer: '<p>Generated by EnRep Reporting System: ' + new Date().toLocaleDateString() + '</p>',
        logoUrl: 'images/company/logo.jpg',
        styles: [rootUrl + '/src/css/print.css']
    });
};
</script>
