<?php
$_REQUEST['clientname'] = str_replace("'", "", $_REQUEST['clientname']);
switch ($_REQUEST['view']) {
    default:
        $r = mysqli_query($GLOBALS['con'], "SELECT * FROM `locations` WHERE `clientnumber`='" . $_REQUEST['clientnumber'] . "' AND `statuslive`='1'"); ?>

<div class="row">
    <div class="col text-end">
        <a href="index.php?t=includes/master&p=locations.php&view=new&clientnumber=<?= $_REQUEST['clientnumber'] ?>&clientname=<?= $_REQUEST['clientname'] ?>"
           class="btn btn-secondary btn-sm"><i class="fa fa-plus" aria-hidden="true"></i> New
            Location</a>
        <a href="index.php?t=includes/master&p=locations.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&clientname=<?= $_REQUEST['clientname'] ?>&view=archive"
           class="btn btn-sm btn-secondary m-0 px-3 waves-effect waves-light" data-mdb-tooltip-init
           data-mdb-placement="bottom" data-mdb-trigger="hover" totitle="hover" title="View Archived Locations"><i
               class="fad fa-archive" aria-hidden="true"></i> View Archived Locations</a>
    </div>
</div>

<h3 class="lead"><span class="text-muted">Locations for</span> <strong><?= $_REQUEST['clientname'] ?></strong></h3>
<table id="datatables" class="table table-striped table-sm table-bordered table-hover responsive" width="100%"
       style="width:100%">
    <thead>
        <tr>
            <th class="no-sort"></th>
            <th>Location Name</th>
            <th>Address</th>
            <th>Post Code</th>
            <th>Contact</th>
            <th>Phone</th>
            <th>Notes</th>
            <th class="no-sort"></th>
        </tr>
    </thead>
    <tbody>
        <?php while ($d = mysqli_fetch_array($r)) {
                    $addressParts = [
                        $d['locaddress1'],
                        $d['locaddress2'],
                        $d['locaddress3'],
                        $d['locaddress4']
                    ];

                    $filteredAddress = array_filter($addressParts);
                    $addressString = implode(', ', $filteredAddress);
                ?>
        <tr>
            <td><?= $d['locnumber'] ?></td>
            <td><?= $d['locname'] ?></td>
            <td><?= $addressString ?></td>
            <td><?= $d['postcode'] ?></td>
            <td><?= $d['contactlc'] ?></td>
            <td><?= $d['contacttel'] ?></td>
            <td><?= $d['locnotes'] ?></td>
            <td class=" text-center">
                <div class="btn-group" role="group">
                    <a href="javascript:void(0)"
                       onclick="loadModalContent('<?= ROOT_URL ?>/includes/locations/location_plant.php?clientnumber=<?= $_REQUEST['clientnumber'] ?>&locnumber=<?= $d['locnumber'] ?>&tenant=<?= TENANT_URL ?>','popupBox', 'modal-xl', 1060, 'true','Plant List','close')"
                       style="z-index:999" class="text-light btn btn-secondary noprint me-3" data-mdb-tooltip-init
                       data-mdb-placement="bottom" data-mdb-trigger="hover" totitle="hover"
                       title="Location Plant Summary"><i class="fa-duotone fa-clipboard-list"></i></a>

                    <!--<a href="javascript:void(0)" onclick="showPop('Item Summary','includes/master/itemSummary.php?clientnumber=<?= $_REQUEST['clientnumber'] ?>&location=<?= $d['locnumber'] ?>','','')" style="z-index:999" class="text-light btn btn-secondary noprint me-3" data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover"totitle="hover"  title="Location Item Summary" ><i class="fad fa-layer-group"></i></a>-->

                    <a href="javascript:void(0)"
                       onclick="printSchedule('<?= $_REQUEST['clientnumber'] ?>','<?= $d['locnumber'] ?>','<?= $d['postcode'] ?>')"
                       style="z-index:999" class="text-light btn btn-secondary noprint me-3" data-mdb-tooltip-init
                       data-mdb-placement="bottom" data-mdb-trigger="hover" totitle="hover"
                       title="Pretty print schedule"><i class="fad fa-print"></i></a>
                    <a href="index.php?t=includes/master&p=locations.php&view=edit&clientnumber=<?= $_REQUEST['clientnumber'] ?>&clientname=<?= $_REQUEST['clientname'] ?>&locnumber=<?= $d['locnumber'] ?>"
                       class="btn btn-secondary noprint me-3"><i class="fad fa-info-circle"></i></a>
                    <a href="index.php?t=includes/master&p=locations.php&view=manage&clientnumber=<?= $_REQUEST['clientnumber'] ?>&clientname=<?= $_REQUEST['clientname'] ?>&&locnumber=<?= $d['locnumber'] ?>"
                       class="btn btn-secondary noprint  me-3"><i class="fad fa-arrow-right-arrow-left"></i></a>
                    <a href="javascript:void(0)"
                       class="btn btn-secondary noprint archiveButton me-2 waves-effect waves-light"
                       data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Archive Item"
                       onclick="archive('<?= $d['locnumber'] ?>')"><i class="fad fa-archive"
                           aria-hidden="true"></i></a>
                </div>
            </td>
        </tr>
        <?php } ?>
    </tbody>
</table>

<script>
document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&view=list">Client List</a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li><li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&clientname=<?= addslashes($_REQUEST['clientname']) ?>&view=asset"><?= addslashes($_REQUEST['clientname']) ?></a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li><li class="breadcrumb-item active">Locations</li>'
</script>
<?php $table = "datatables";
        require_once(ROOT_URL . '/includes/tables/single_table.php');
        break;
    case "archive":
        require_once(ROOT_URL . '/includes/locations/locations_archive.php');
        break;
    case "new":
        require_once(ROOT_URL . '/includes/locations/locations_new.php');
        break;
    case "edit":
        require_once(ROOT_URL . '/includes/locations/locations_edit.php');
        break;
    case "remove":
        require_once(ROOT_URL . '/includes/locations/locations_archive.php');
        break;
    case "manage":
        require_once(ROOT_URL . '/includes/locations/locations_manage.php');
        break;
} ?>

<div id="detailsBox" class="hidden"></div>
<script>
function printSchedule(client, loc, locname) {
    $.post(ROOT_URL + '/functions/print_schedule.php', {
        clientnumber: client,
        location: loc,
        name: locname,
        tenant: TENANT_URL
    }, function(ret) {
        $('#detailsBox').html(ret)
        printDetails()
    })

}

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>`,
    });
}

async function loadInfo(clientnumber) {
  const form = new URLSearchParams({
    FUNCTION: 'loadInfo',
    clientnumber: String(clientnumber),
    tenant: TENANT_URL
  });

  const res = await fetch(ROOT_URL + '/includes/locations/location_functions.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: form.toString()
  });

  if (!res.ok) { console.error('loadInfo HTTP', res.status); return; }

  const data = await res.json(); // expects JSON
  const setVal = (id, val) => { const el = document.getElementById(id); if (el) el.value = val ?? ''; };

  setVal('locaddress1', data.address1);
  setVal('locaddress2', data.address2);
  setVal('locaddress3', data.town);
  setVal('locaddress4', data.county);
  setVal('postcode',   data.postcode);
  setVal('phone1',     data.phone1);
  setVal('mobile',     data.mobile);
  setVal('email',      data.email);
  setVal('contactlc',  data.pri_contact_name);
  setVal('contacttel', data.pri_contact_tel);
}



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'
        ],
    });
}

function archive(i) {
  var dest =  '<p class="text-center">Are you sure you wish to archive this location and all items listed at this location?</p>';
            loadModalContent(dest, "archiveBox", "modal-md", 1060, "true", "Archive Location","cancelConfirm", () =>  confirmArchive(i));
}

function confirmArchive(i) {
    const formData = new URLSearchParams();
    formData.append('FUNCTION', 'archiveLoc');
    formData.append('locnumber', i);
    formData.append('clientnumber', '<?= $_REQUEST['clientnumber'] ?>');
    formData.append('tenant', TENANT_URL);

    fetch(ROOT_URL+'/includes/locations/location_functions.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: formData.toString()
    })
    .then(response => response.text())
    .then(ret => {
        if (ret.trim() === 's') {
            window.location.href = `index.php?t=includes/master&p=locations.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&clientname=<?= $_REQUEST['clientname'] ?>`;
        }
    })
    .catch(() => {
        showResponse('danger', 'Error reinstating location.');
    });
}


function reinstate(i) {
  var dest =  '<p class="text-center">Are you sure you wish to reinstate this location and all items listed at this location?</p>';
            loadModalContent(dest, "reinstateBox", "modal-md", 1060, "true", "Reinstate Location","cancelConfirm", () =>  confirmReinstate(i));
}

function confirmReinstate(i) {
    const formData = new URLSearchParams();
    formData.append('FUNCTION', 'reinstate');
    formData.append('locnumber', i);
    formData.append('clientnumber', '<?= $_REQUEST['clientnumber'] ?>');
    formData.append('tenant', TENANT_URL);

    fetch(ROOT_URL+'/includes/locations/location_functions.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: formData.toString()
    })
    .then(response => response.text())
    .then(ret => {
        if (ret.trim() === 's') {
            window.location.href = `index.php?t=includes/master&p=locations.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&clientname=<?= $_REQUEST['clientname'] ?>`;
        }
    })
    .catch(() => {
        showResponse('danger', 'Error reinstating location.');
    });
}

</script>