<?php
switch ($_REQUEST['view']) {
    default: ?>
<?php break;
    case 'new':
        require_once(ROOT_URL . "/includes/client/client-new.php");
        $allowform = 1;
        break;

    case 'edit':
        require_once(ROOT_URL . "/includes/client/client-edit.php");
        $allowform = 1;
        break;

    case "load":
        require_once(ROOT_URL . "/includes/client/client-load.php");
        $allowform = 1;
        break;

    case "list":
        require_once(ROOT_URL . "/includes/client/client-list.php");
        break;

    case "asset":
        require_once(ROOT_URL . "/includes/master/form_functions.php");
        $_SESSION['returnLanding'] = 'index.php?t=includes/master&p=client.php&clientnumber=' . $_REQUEST['clientnumber'] . '&view=asset';
        switch ($_SESSION['scheduleMode']) {
            default:
                require_once(ROOT_URL . "/includes/client/client-asset.php");
                break;
            case "0":
                require_once(ROOT_URL . "/includes/client/client-asset.php");
                break;
            case "1":
                require_once(ROOT_URL . "/includes/client/client-asset_light.php");
                break;
        }
    ?>
<script>
function scheduleMode(mode) {
    $.post('<?= ROOT_URL ?>/includes/client/client_mode.php', {
        scheduleMode: mode
    }, function() {

        location.href =
            'index.php?t=includes/master&p=client.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&view=asset'
    })
}
</script>
<?php
        break;
} ?>

<script>
<?php if ($allowform == 1) { ?>
// Function to handle form submission
document.getElementById('clientForm').addEventListener('submit', function(event) {
    event.preventDefault();
    const formData = new FormData(this);

    const contIds = [
        'cont_company', 'cont_company_short', 'cont_address1', 'cont_address2', 'cont_town', 'cont_county',
        'cont_post',
        'cont_tel', 'cont_fax', 'cont_main_email', 'cont_finance_email', 'cont_web', 'cont_vatno',
        'cont_compno'
    ];
    const modeEl = document.querySelector('input[name="clientMode"]:checked');
    if (modeEl) formData.set('clientMode', modeEl.value);

    formData.append('save_contract', '1');
    contIds.forEach(id => {
        const el = document.getElementById(id);
        formData.append(id, el ? el.value.trim() : '');
    });

    formData.append('tenant', '<?= TENANT_URL ?>');

    const url = '<?= ROOT_URL ?>/includes/client/client_functions.php';
    fetch(url, {
            method: 'POST',
            body: new URLSearchParams(formData)
        })
        .then(r => r.text())
        .then(result => {
            const func = document.getElementById('function').value;
            if (func === "insert") {
                window.location.href =
                    `index.php?t=includes/master&p=client.php&clientnumber=${result.trim()}&clientname=${document.getElementById('clientname').value}&view=asset`;
            } else {
                if (result.trim() === "success") {
                    showResponse('success', 'Your changes have been saved successfully');
                } else {
                    showResponse('danger',
                        `There was a problem, please check your details and try again<br><br>${result}`);
                }
            }
        })
        .catch(err => showResponse('danger', 'Save failed'));
});

<?php } ?>
// Function to archive a client
function archiveClient(clientNumber) {
    fetch('<?= ROOT_URL ?>/includes/client/client_functions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                FUNCTION: 'archive',
                clientnumber: clientNumber,
                tenant: TENANT_URL,
            }),
        })
        .then(response => response.text())
        .then(result => {
            if (result.trim() === "success") {
                showResponse('success', 'Your changes have been saved successfully');
            }
            window.location.href = 'index.php?t=includes/master&p=client.php&view=list';
        })
        .catch(error => console.error('Error:', error));
}

// Function to activate a client
function activateClient(clientNumber) {
    fetch('<?= ROOT_URL ?>/includes/client/client_functions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                FUNCTION: 'activate',
                clientnumber: clientNumber,
                tenant: TENANT_URL,
            }),
        })
        .then(response => response.text())
        .then(result => {
            if (result.trim() === "success") {
                showResponse('success', 'Your changes have been saved successfully');
            }
            window.location.href = 'index.php?t=includes/master&p=client.php&view=list';
        })
        .catch(error => console.error('Error:', error));
}

// Function to load client by site
function loadClientBySite() {
    const clientNumber = document.getElementById('loadClientBySite').value;
    window.location.href = `index.php?t=includes/master&p=client.php&clientnumber=${clientNumber}&view=asset`;
}

function imageRemoved(data) {
    console.log(data);
    var name = data.input.name
    $.post('images/clientimage_remove.php', {
        image: name
    }, function(data2) {})
}
// Function to print details
function printDetails() {
    printElement('detailsBox', {
        addGlobalStyles: false,
        stylesheet: '<?= ROOT_URL ?>/src/css/printer.css',
        rejectWindow: true,
        noPrintSelector: ".no-print",
        iframe: true,
        prepend: '<div class="col-12 text-end"><img src="images/company/logo.jpg"></div>',
        append: `<div class="col-12 text-end"><small>Printed <?= date('d-m-Y') ?></small></div>`,
    });
}

// Function to print labels
function printLabel() {
    printContainer('label', {
        orientation: 'landscape',
        header: `<p>${header}</p>`,
        footer: `<p>Generated by EnRep Reporting System: ${new Date().toLocaleDateString()}</p>`,
        logoUrl: 'images/company/logo.jpg',
        styles: [
            `${ROOT_URL}/src/css/print.css`,
        ],
    });


}
</script>