<?php
require_once __DIR__ . '/../../functions/security.php';

$tenant = enrep_tenant_segment();
if ($tenant !== '' && file_exists('../../../' . $tenant . '/config.php')) {
    require_once('../../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    enrep_fail(400, 'Tenant config not found');
}

enrep_require_user();

function ws_data_e($value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

$clientnumber = enrep_request_int('clientnumber');
if ($clientnumber < 1) {
    enrep_fail(400, 'Invalid client');
}

$stmt = $GLOBALS['con']->prepare("SELECT `id` FROM `writtenscheme` WHERE `clientnumber`=? AND `no`='WS00' LIMIT 1");
if (!$stmt) {
    enrep_fail(500, 'Unable to load written schemes');
}
$stmt->bind_param('i', $clientnumber);
$stmt->execute();
$cc = $stmt->get_result();
$stmt->close();

if (mysqli_num_rows($cc) < 1) {
    $created = time();
    $stmt = $GLOBALS['con']->prepare(
        "INSERT INTO `writtenscheme` VALUES(NULL,?,'CATCHALL','System Default WS for exclusions','','WS00',NULL,?,'0','','','0','0','',NULL)"
    );
    if (!$stmt) {
        enrep_fail(500, 'Unable to create default written scheme');
    }
    $stmt->bind_param('ii', $clientnumber, $created);
    if (!$stmt->execute()) {
        $stmt->close();
        enrep_fail(500, 'Unable to create default written scheme');
    }
    $stmt->close();
}

$stmt = $GLOBALS['con']->prepare("SELECT * FROM `writtenscheme` WHERE `clientnumber`=? ORDER BY abs(`no`) ASC");
if (!$stmt) {
    enrep_fail(500, 'Unable to load written schemes');
}
$stmt->bind_param('i', $clientnumber);
$stmt->execute();
$cc = $stmt->get_result();
$stmt->close();

while ($cd = mysqli_fetch_array($cc)) { ?>
<div class="mb-2 card p-2 list-group-item-action wsEntry w-100">
    <div class="row">
        <div class="col-8">
            <p class="p-0 m-0" style="font-size: 16px"><small><?= ws_data_e($cd['no']) ?></small>:<?= ws_data_e($cd['title']) ?></p>
        </div>
        <div class="col-4 text-end">
            <a href="javascript:void(0)" class="btn btn-info btn-sm m-0 px-3 py-2 waves-effect" onClick="editWSC('<?= (int)$cd['id'] ?>')" data-toggle="tooltip" data-placement="left" title="View <?= ws_data_e($cd['title']) ?> details"><i
                   class="fad fa-search"></i></a>
            <?php if ($_SESSION['usertype'] == "admins" && $cd['no'] != "WS00") { ?><a href="javascript:void(0)" class="btn btn-danger btn-sm m-0 px-3 py-2 waves-effect" onClick="delWSC('<?= (int)$cd['id'] ?>')" data-toggle="tooltip"
               data-placement="left"
               title="Remove <?= ws_data_e($cd['title']) ?>"><i class="fad fa-times"></i></a><?php } ?>
        </div>
    </div>
</div>
<?php } ?>
<script>

</script>
