<?php
// item_summary_modal.php
// Load tenant-specific or global config for db connection ($con), TENANT_URL, ROOT_URL
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (file_exists('../../../'.$_REQUEST['tenant'].'/config.php')) {
    require_once('../../../'.$_REQUEST['tenant'].'/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

$tenant       = $_REQUEST['tenant'];
$clientNumber = filter_input(INPUT_GET, 'clientnumber', FILTER_SANITIZE_STRING);
$locNumber    = filter_input(INPUT_GET, 'locnumber', FILTER_SANITIZE_STRING);
?>

<div class="row mb-5">
    <div class="col-12">
        <h4>
            Item Overview - <span id="name"><?= htmlspecialchars(getClientName($clientNumber)) ?></span>
            <span class="float-end">

                <button type="button" class="btn btn-sm btn-secondary" data-mdb-tooltip-init data-mdb-placement="top" title="Print label"
                        onclick="printContent('tableContainer','Item Overview - <?= htmlspecialchars(getClientName($clientNumber)) ?>')">
                    <i class="fad fa-print"></i> Print
                </button>
            </span>
        </h4>
    </div>
</div>

<section id="start" class="dark-grey-text">
    <div class="row">
        <div class="col-12 col-md-6 mb-4">
            <div class="card hoverable" role="button" onclick="document.getElementById('date_start').focus()">
                <div class="card-body d-flex align-items-center">
                    <i class="fad fa-calendar-alt fa-2x text-info me-3"></i>
                    <div class="w-100 date-picker" data-date-type=" open" data-mdb-toggle-button="false">
                        <h5 class="mb-3">Examination Period Start</h5>
                        <input
                               type="text"
                               id="date_start"
                               name="date_start"
                               class="form-control"
                               placeholder="Click or tap to begin"
                               data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker"
                               data-mdb-format="dd-mm-yyyy" />
                    </div>
                </div>
            </div>
        </div>

        <div class="col-12 col-md-6 mb-4">
            <div class="card hoverable" role="button" onclick="document.getElementById('date_end').focus()">
                <div class="card-body d-flex align-items-center">
                    <i class="fad fa-calendar-alt fa-2x purple-text me-3"></i>
                    <div class="w-100 date-picker" data-date-type=" open" data-mdb-toggle-button="false">
                        <h5 class="mb-3">Examination Period End</h5>
                        <input
                               type="text"
                               id="date_end"
                               name="date_end"
                               class="form-control"
                               placeholder="End date"
                               value="<?= date('d-m-Y') ?>"
                               data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker"
                               data-mdb-format="dd-mm-yyyy" />
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="text-center mt-4">
        <button
                type="button"
                id="btnLoadData"
                class="btn btn-info"
                data-mdb-tooltip-init
                data-mdb-placement="top"
                title="Load item data"
                onclick="loadData()">Load Data</button>
    </div>
</section>

<div id="tableContainer" class="w-100">
</div>

<script>
(() => {
    const CLIENT_NUMBER = '<?= $clientNumber ?>';
    const LOC_NUMBER = '<?= $locNumber ?>';

    // Initialize MDB datepickers
    document.addEventListener('DOMContentLoaded', () => {
        const dpElements = document.querySelectorAll('[data-mdb-toggle=" datepicker"]');
        dpElements.forEach(el => new mdb.Datepicker(el, {
            format: 'dd-mm-yyyy',
            autoHide: true
        }));
    });

    function loadData() {
        const loadingBox = document.getElementById('loadingBox');
        const tableContainer = document.getElementById('tableContainer');
        const dateStart = document.getElementById('date_start').value;
        const dateEnd = document.getElementById('date_end').value;

        if (dateStart.length === 0) {
            tableContainer.innerHTML = '<p class="text-center mt-4 alert alert-warning">Please select a start date</p>'
            return
        }

        if (loadingBox) loadingBox.classList.remove('d-none');
        if (tableContainer) tableContainer.classList.add('d-none');

        const params = new URLSearchParams({
            FCN: 'load',
            locnumber: LOC_NUMBER,
            clientnumber: CLIENT_NUMBER,
            start: dateStart,
            end: dateEnd,
            tenant: TENANT_URL
        });

        fetch(`${ROOT_URL}/includes/master/itemSummary_functions.php`, {
                method: 'POST',
                body: params
            })
            .then(res => res.text())
            .then(html => {
                tableContainer.innerHTML = html;
                const tbl = tableContainer.querySelector('#tableData');
                if (tbl) tbl.classList.remove('d-none');
                fadeOut(loadingBox);
                fadeIn(tableContainer);
            })
            .catch(err => {
                console.error('Error loading data:', err);
                if (loadingBox) loadingBox.classList.add('d-none');
                if (tableContainer) tableContainer.classList.remove('d-none');
            });
    }

    function fadeOut(el) {
        if (!el) return;
        el.style.transition = 'opacity 0.4s';
        el.style.opacity = '0';
        setTimeout(() => el.classList.add('d-none'), 400);
    }

    function fadeIn(el) {
        if (!el) return;
        el.classList.remove('d-none');
        el.style.display = 'table';
        el.style.opacity = '0';
        el.style.transition = 'opacity 0.4s';
        setTimeout(() => el.style.opacity = '1', 50);
    }

    window.loadData = loadData;

})();

var modalElement = document.getElementById('start');
var datepickerElements = modalElement.querySelectorAll(".date-picker");
datepickerElements.forEach((datepickerEl) => {
    const options = {
        confirmDateOnSelect: true,
        format: "dd-mm-yyyy",
    };

    new mdb.Datepicker(datepickerEl, options);
});

function printContent(target, header) {
    printContainer(target, {
        orientation: 'landscape', // or 'Portrait'
        header: '<p>' + header + '</p>',
        footer: '<p>Generated by EnRep Reporting System: <?= date('d-m-Y')?></p>',
        logoUrl: 'images/company/logo.jpg',
        styles: [
            ROOT_URL + '/src/css/print.css'
        ],
    });
}
</script>