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

$clientnumber = (int)($_REQUEST['clientnumber'] ?? 0);
$search = trim((string)($_REQUEST['search'] ?? ''));

if ($clientnumber <= 0) {
    echo '<div class="p-3 text-danger">Invalid client.</div>';
    exit;
}

$sql = "
    SELECT
        s.`id`,
        s.`set_title`,
        s.`status`,
        t.`template_title`
    FROM `puwer_item_sets` s
    LEFT JOIN `puwer_templates` t
        ON t.`id` = s.`template_id`
    WHERE s.`clientnumber` = ?
    ORDER BY s.`status` DESC, s.`id` DESC
";

$stmt = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $clientnumber);
$stmt->execute();
$res = $stmt->get_result();
$stmt->close();

$rows = [];
while ($row = mysqli_fetch_assoc($res)) {
    $haystack = strtolower(
        trim(
            (string)($row['set_title'] ?? '') . ' ' .
            (string)($row['template_title'] ?? '')
        )
    );

    if ($search !== '' && strpos($haystack, strtolower($search)) === false) {
        continue;
    }

    $rows[] = $row;
}

if (empty($rows)) {
    echo '<div class="p-3 text-muted">No PUWER sets found for this client.</div>';
    exit;
}

foreach ($rows as $row) {
    $statusBadge = (int)$row['status'] === 1
        ? '<span class="badge badge-success">Active</span>'
        : '<span class="badge badge-secondary">Inactive</span>';

    $templateTitle = trim((string)($row['template_title'] ?? ''));
    if ($templateTitle === '') {
        $templateTitle = 'Unknown template';
    }

    echo '
    <div class="puwerEntry border-bottom px-3 py-2">
        <div class="d-flex justify-content-between align-items-start">
            <div style="min-width:0;">
                <p class="mb-1 fw-bold">' . htmlspecialchars((string)$row['set_title'], ENT_QUOTES) . '</p>
                <p class="mb-0 small text-muted">Template: ' . htmlspecialchars($templateTitle, ENT_QUOTES) . '</p>
            </div>
            <div class="ms-2 text-end">
                <div class="mb-2">' . $statusBadge . '</div>
                <button type="button"
                        class="btn btn-secondary btn-sm"
                        onClick="editPuwerSet(' . (int)$row['id'] . ')"
                        data-mdb-tooltip-init
                        data-mdb-placement="left"
                        title="Edit PUWER Set">
                    <i class="fad fa-search"></i>
                </button>
            </div>
        </div>
    </div>';
}
?>