<?php
// certificate_settings.php — Admin only.
//
// Three independent things live here now:
//   1. Logo — replaces the "Liftek" wordmark on every certificate.
//   2. Footer margin texts — the actual bottom margin space. Add as many
//      separate lines as you want, each with its own size/color/alignment/
//      bold, like typing separate lines into a Word footer.
//   3. Disclaimer — plain legal note text, rendered as part of the
//      certificate CONTENT (near the signature block), not the margin.

require_once 'includes/auth.php';
require_role(['admin']);

require_once 'db.php';

// Shared footer-rendering code (pdfImageSrc, renderCertFooterImage,
// renderCertFooterBand) — the SAME functions generate_certificate.php uses
// for the real certificates. Required here so the Live Preview panel below
// calls the identical rendering code instead of a hand-copied look-alike,
// which is what let past "fixes" look right in a preview but stay wrong in
// the real PDF (see claude/operating-notes-and-lessons.md).
require_once __DIR__ . '/includes/cert_footer_render.php';

// One-time, idempotent schema migration for the "Bottom Margin — Custom
// Image" feature (Footer_Mode / Footer_Image_Path). ADD COLUMN IF NOT
// EXISTS is a safe no-op once the columns already exist, so this can run
// on every page load without harm. Wrapped in try/catch — if the DB user
// lacks ALTER privileges, or is on an old MySQL without IF NOT EXISTS
// support, the page still degrades safely to the existing text-only
// footer (see the getSettingsSafe() defaults below) rather than fatally
// erroring on an admin settings page — see the $settings fallback array
// further down, which already defaults every key safely.
try {
    $pdo->exec("ALTER TABLE tbl_certificate_settings ADD COLUMN IF NOT EXISTS Footer_Mode VARCHAR(10) NOT NULL DEFAULT 'text'");
    $pdo->exec("ALTER TABLE tbl_certificate_settings ADD COLUMN IF NOT EXISTS Footer_Image_Path VARCHAR(255) NULL");
} catch (\PDOException $e) {}

// One-time, idempotent schema migration adding the "Center" zone to the
// bottom-margin footer (3-column layout: right=Arabic, center=note,
// left=English). MODIFY COLUMN is a safe no-op to re-run — it just resets
// the column to the same definition — so, like the migration above, this
// can run on every page load. Wrapped in try/catch for the same reason:
// if it fails (restricted DB privileges), the page must still degrade
// safely rather than fatally error on an admin settings page — inserting
// a 'center' line would then simply be rejected by the still-old enum,
// caught below same as any other DB error.
try {
    $pdo->exec("ALTER TABLE tbl_certificate_footer_texts MODIFY COLUMN Column_Side ENUM('left','center','right') NOT NULL DEFAULT 'left'");
} catch (\PDOException $e) {}

$me = current_user();
$message = '';
$error = '';

// --- Logo + Disclaimer save ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_general'])) {
    require_csrf();
    $disclaimerText = trim($_POST['disclaimer_text'] ?? '');
    $removeLogo = isset($_POST['remove_header_logo']);
    $removeCounterSig = isset($_POST['remove_counter_signature']);
    $removeFooterImage = isset($_POST['remove_footer_image']);

    // Whitelisted: only 'text' (existing per-line footer) or 'image' (the
    // new admin-uploaded footer image, see renderCertFooterImage() in
    // generate_certificate.php) are ever accepted — anything else silently
    // falls back to 'text' rather than storing an unrecognised mode.
    $footerMode = ($_POST['footer_mode'] ?? 'text') === 'image' ? 'image' : 'text';

    $current = $pdo->query("SELECT * FROM tbl_certificate_settings WHERE id = 1")->fetch(PDO::FETCH_ASSOC);
    $headerLogoPath = $current['Header_Logo_Path'] ?? null;
    $counterSigPath = $current['Counter_Signature_Path'] ?? null;
    $footerImagePath = $current['Footer_Image_Path'] ?? null;
    if ($removeLogo) $headerLogoPath = null;
    if ($removeCounterSig) $counterSigPath = null;
    if ($removeFooterImage) { $footerImagePath = null; $footerMode = 'text'; }

    $allowedTypes = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
    $uploadDir = __DIR__ . '/uploads/branding/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

    if (isset($_FILES['header_logo']) && $_FILES['header_logo']['error'] === UPLOAD_ERR_OK) {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $_FILES['header_logo']['tmp_name']);
        finfo_close($finfo);

        if (isset($allowedTypes[$mime]) && $_FILES['header_logo']['size'] <= 5 * 1024 * 1024) {
            $filename = bin2hex(random_bytes(12)) . '.' . $allowedTypes[$mime];
            move_uploaded_file($_FILES['header_logo']['tmp_name'], $uploadDir . $filename);
            $headerLogoPath = 'uploads/branding/' . $filename;
        } else {
            $error = 'Logo file must be JPG/PNG/WEBP under 5MB.';
        }
    }

    if (isset($_FILES['counter_signature']) && $_FILES['counter_signature']['error'] === UPLOAD_ERR_OK) {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $_FILES['counter_signature']['tmp_name']);
        finfo_close($finfo);

        if (isset($allowedTypes[$mime]) && $_FILES['counter_signature']['size'] <= 3 * 1024 * 1024) {
            $filename = 'countersig_' . bin2hex(random_bytes(12)) . '.' . $allowedTypes[$mime];
            move_uploaded_file($_FILES['counter_signature']['tmp_name'], $uploadDir . $filename);
            $counterSigPath = 'uploads/branding/' . $filename;
        } else {
            $error = 'Counter Signature file must be JPG/PNG/WEBP under 3MB.';
        }
    }

    // Bottom-margin custom image ("تعطيل الهامش السفلي ورفع صورة مكانه") —
    // same validated-upload pattern as the logo/counter-signature above
    // (MIME sniffed via finfo, never trusted from the client; random
    // filename so nothing user-controlled ever reaches the filesystem
    // path). Kept at 5MB like the logo, since it's the same kind of asset.
    if (isset($_FILES['footer_image']) && $_FILES['footer_image']['error'] === UPLOAD_ERR_OK) {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $_FILES['footer_image']['tmp_name']);
        finfo_close($finfo);

        if (isset($allowedTypes[$mime]) && $_FILES['footer_image']['size'] <= 5 * 1024 * 1024) {
            $filename = 'footer_' . bin2hex(random_bytes(12)) . '.' . $allowedTypes[$mime];
            move_uploaded_file($_FILES['footer_image']['tmp_name'], $uploadDir . $filename);
            $footerImagePath = 'uploads/branding/' . $filename;
        } else {
            $error = 'Footer image file must be JPG/PNG/WEBP under 5MB.';
        }
    }

    // Selecting "Custom Image" mode with no image on file yet (existing OR
    // just uploaded) makes no sense to persist — fall back to 'text' so
    // generate_certificate.php's own safe-fallback logic is never the only
    // thing standing between an incomplete setup and a blank margin.
    if ($footerMode === 'image' && empty($footerImagePath)) $footerMode = 'text';

    if (!$error) {
        $stmt = $pdo->prepare("UPDATE tbl_certificate_settings SET Header_Logo_Path = ?, Disclaimer_Text = ?, Counter_Signature_Path = ?, Footer_Mode = ?, Footer_Image_Path = ?, Updated_By = ? WHERE id = 1");
        $stmt->execute([$headerLogoPath, $disclaimerText, $counterSigPath, $footerMode, $footerImagePath, $me['id']]);
        $message = 'Saved.';
    }
}

// --- Add / update a footer margin text line ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_footer_text'])) {
    require_csrf();
    $textId = $_POST['text_id'] ?? '';
    $content = trim($_POST['text_content'] ?? '');
    $fontSize = (int) ($_POST['font_size'] ?? 9);
    $color = trim($_POST['text_color'] ?? '#333333');
    $align = $_POST['text_align'] ?? 'left';
    $side = $_POST['column_side'] ?? 'left';
    $weight = isset($_POST['bold']) ? 'bold' : 'normal';
    $sortOrder = (int) ($_POST['sort_order'] ?? 1);

    if (!in_array($align, ['left', 'center', 'right', 'justify'], true)) $align = 'left';
    if (!in_array($side, ['left', 'center', 'right'], true)) $side = 'left';
    if ($fontSize < 5 || $fontSize > 20) $fontSize = 9;

    if ($content === '') {
        $error = 'Text content cannot be empty.';
    } else {
        if (!empty($textId)) {
            $stmt = $pdo->prepare(
                "UPDATE tbl_certificate_footer_texts SET Text_Content=?, Font_Size=?, Text_Color=?, Text_Align=?, Column_Side=?, Font_Weight=?, Sort_Order=? WHERE id=?"
            );
            $stmt->execute([$content, $fontSize, $color, $align, $side, $weight, $sortOrder, $textId]);
            $message = 'Footer line updated.';
        } else {
            $stmt = $pdo->prepare(
                "INSERT INTO tbl_certificate_footer_texts (Text_Content, Font_Size, Text_Color, Text_Align, Column_Side, Font_Weight, Sort_Order) VALUES (?, ?, ?, ?, ?, ?, ?)"
            );
            $stmt->execute([$content, $fontSize, $color, $align, $side, $weight, $sortOrder]);
            $message = 'Footer line added.';
        }
        header('Location: certificate_settings.php?saved=1');
        exit;
    }
}

// --- Delete a footer margin text line ---
if (isset($_GET['delete_text_id'])) {
    require_csrf();
    $stmt = $pdo->prepare("DELETE FROM tbl_certificate_footer_texts WHERE id = ?");
    $stmt->execute([(int) $_GET['delete_text_id']]);
    header('Location: certificate_settings.php?deleted=1');
    exit;
}

$settings = $pdo->query("SELECT * FROM tbl_certificate_settings WHERE id = 1")->fetch(PDO::FETCH_ASSOC);
if (!$settings) {
    $settings = ['Header_Logo_Path' => null, 'Disclaimer_Text' => '', 'Counter_Signature_Path' => null, 'Footer_Mode' => 'text', 'Footer_Image_Path' => null];
}
$settings['Footer_Mode'] = $settings['Footer_Mode'] ?? 'text';

// Real pixel dimensions of the currently-saved footer image, shown to the
// admin so it's clear exactly what will be scaled (never distorted —
// generate_certificate.php renders it with object-fit:contain) into the
// certificate's fixed footer slot on every category.
$footerImageDims = null;
if (!empty($settings['Footer_Image_Path'])) {
    $absFooterImg = __DIR__ . '/' . $settings['Footer_Image_Path'];
    if (is_file($absFooterImg)) {
        $dims = @getimagesize($absFooterImg);
        if ($dims) $footerImageDims = $dims[0] . ' × ' . $dims[1] . ' px';
    }
}

$footerTexts = $pdo->query("SELECT * FROM tbl_certificate_footer_texts ORDER BY Sort_Order ASC, id ASC")->fetchAll(PDO::FETCH_ASSOC);

// Load a specific line into the edit form if requested
$editingId = $_GET['edit_text_id'] ?? null;
$editingText = ['id' => '', 'Text_Content' => '', 'Font_Size' => 9, 'Text_Color' => '#333333', 'Text_Align' => 'left', 'Column_Side' => 'left', 'Font_Weight' => 'normal', 'Sort_Order' => count($footerTexts) + 1];
if ($editingId) {
    foreach ($footerTexts as $ft) {
        if ($ft['id'] == $editingId) { $editingText = $ft; break; }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Certificate Branding — Liftek</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container my-4" style="max-width: 850px;">

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold m-0"><i class="fa-solid fa-stamp text-primary me-2"></i> Certificate Branding</h3>
        <a href="index.php" class="btn btn-outline-secondary btn-sm"><i class="fa-solid fa-arrow-left me-1"></i> Back to Register</a>
    </div>

    <?php if ($message): ?><div class="alert alert-success py-2"><?= htmlspecialchars($message); ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-danger py-2"><?= htmlspecialchars($error); ?></div><?php endif; ?>
    <?php if (isset($_GET['saved'])): ?><div class="alert alert-success py-2">Saved.</div><?php endif; ?>
    <?php if (isset($_GET['deleted'])): ?><div class="alert alert-secondary py-2">Line removed.</div><?php endif; ?>

    <!-- Logo + Disclaimer -->
    <form method="POST" enctype="multipart/form-data" class="mb-5">
        <input type="hidden" name="save_general" value="1">
        <?php csrf_field(); ?>

        <div class="card mb-4">
            <div class="card-header bg-primary text-white fw-bold"><i class="fa-solid fa-image me-1"></i> Logo</div>
            <div class="card-body">
                <p class="small text-muted">Replaces the "Liftek" wordmark at the top of every certificate. No logo uploaded = default text wordmark is used instead.</p>
                <?php if (!empty($settings['Header_Logo_Path'])): ?>
                    <div class="mb-3 p-2 border rounded d-inline-block">
                        <img src="<?= htmlspecialchars($settings['Header_Logo_Path']); ?>" style="max-height: 70px; display:block;">
                    </div>
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="remove_header_logo" id="removeLogo" value="1">
                        <label class="form-check-label small" for="removeLogo">Remove this logo and revert to the default text wordmark</label>
                    </div>
                <?php endif; ?>
                <label class="form-label small fw-bold">Upload New Logo</label>
                <input type="file" name="header_logo" accept="image/jpeg,image/png,image/webp" class="form-control">
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header bg-secondary text-white fw-bold"><i class="fa-solid fa-scale-balanced me-1"></i> Legal Disclaimer</div>
            <div class="card-body">
                <p class="small text-muted">This is part of the certificate's actual content (shown near the signature block) — not the bottom margin.</p>
                <textarea name="disclaimer_text" class="form-control" rows="5"><?= htmlspecialchars($settings['Disclaimer_Text'] ?? ''); ?></textarea>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header bg-dark text-white fw-bold"><i class="fa-solid fa-pen-fancy me-1"></i> Counter Signature (fixed, all certificates)</div>
            <div class="card-body">
                <p class="small text-muted">Same on every certificate — this is separate from each Inspector's personal signature (set individually via My Account).</p>
                <?php if (!empty($settings['Counter_Signature_Path'])): ?>
                    <div class="mb-3 p-2 border rounded d-inline-block">
                        <img src="<?= htmlspecialchars($settings['Counter_Signature_Path']); ?>" style="max-height: 60px; display:block;">
                    </div>
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="remove_counter_signature" id="removeCounterSig" value="1">
                        <label class="form-check-label small" for="removeCounterSig">Remove counter signature</label>
                    </div>
                <?php endif; ?>
                <input type="file" name="counter_signature" accept="image/jpeg,image/png,image/webp" class="form-control">
            </div>
        </div>

        <div class="card mb-4 border-danger">
            <div class="card-header bg-danger text-white fw-bold"><i class="fa-solid fa-image me-1"></i> Bottom Margin — Display Mode</div>
            <div class="card-body">
                <p class="small text-muted">Choose how the bottom margin renders on <strong>every certificate, every category</strong> (Training, Appliance/Crane, LLG, Misc). "Custom Image" completely replaces the text-line footer below with one uploaded image — the image is never stretched or cropped, it is always scaled down to fit the same fixed margin slot while keeping its own true proportions.</p>

                <div class="form-check mb-2">
                    <input class="form-check-input" type="radio" name="footer_mode" id="footerModeText" value="text" <?= $settings['Footer_Mode'] !== 'image' ? 'checked' : ''; ?>>
                    <label class="form-check-label" for="footerModeText">Text Lines (configured below)</label>
                </div>
                <div class="form-check mb-3">
                    <input class="form-check-input" type="radio" name="footer_mode" id="footerModeImage" value="image" <?= $settings['Footer_Mode'] === 'image' ? 'checked' : ''; ?>>
                    <label class="form-check-label" for="footerModeImage">Custom Image (disables the text-line footer)</label>
                </div>

                <?php if (!empty($settings['Footer_Image_Path'])): ?>
                    <div class="mb-3 p-2 border rounded d-inline-block">
                        <img src="<?= htmlspecialchars($settings['Footer_Image_Path']); ?>" style="max-height: 70px; display:block;">
                        <?php if ($footerImageDims): ?>
                            <div class="small text-muted mt-1">Uploaded size: <?= htmlspecialchars($footerImageDims); ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="remove_footer_image" id="removeFooterImage" value="1">
                        <label class="form-check-label small" for="removeFooterImage">Remove this footer image and revert to Text Lines</label>
                    </div>
                <?php endif; ?>

                <label class="form-label small fw-bold">Upload <?= !empty($settings['Footer_Image_Path']) ? 'Replacement' : 'New'; ?> Footer Image</label>
                <input type="file" name="footer_image" accept="image/jpeg,image/png,image/webp" class="form-control">
                <p class="small text-muted mt-2 mb-0">JPG/PNG/WEBP, up to 5MB. Uploading a file here automatically saves it whichever mode is selected above — but it only actually appears on certificates once "Custom Image" is selected and saved.</p>
            </div>
        </div>

        <div class="text-end">
            <button type="submit" class="btn btn-primary fw-bold px-4"><i class="fa-solid fa-save me-1"></i> Save Logo, Disclaimer, Counter Signature &amp; Footer</button>
        </div>
    </form>

    <!-- Footer margin text lines -->
    <div class="card mb-4 border-warning">
        <div class="card-header bg-warning fw-bold"><i class="fa-solid fa-shoe-prints me-1"></i> Bottom Margin — <?= $editingText['id'] ? 'Edit Line' : 'Add New Line'; ?></div>
        <div class="card-body">
            <p class="small text-muted">Only used when the Display Mode above is set to "Text Lines". The margin itself starts blank. Add as many separate lines as you want here — each keeps its own size, color, alignment, and boldness, like separate lines typed into a Word footer.</p>
            <form method="POST">
                <input type="hidden" name="save_footer_text" value="1">
                <?php csrf_field(); ?>
                <input type="hidden" name="text_id" value="<?= htmlspecialchars($editingText['id']); ?>">
                <div class="row g-2">
                    <div class="col-12">
                        <textarea name="text_content" class="form-control" rows="2" placeholder="Text for this line..." dir="<?= $editingText['Column_Side'] === 'right' ? 'rtl' : 'ltr'; ?>" required><?= htmlspecialchars($editingText['Text_Content']); ?></textarea>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label small mb-1 fw-bold">Side</label>
                        <select name="column_side" class="form-select">
                            <option value="left" <?= $editingText['Column_Side'] === 'left' ? 'selected' : ''; ?>>Left — English (LTR)</option>
                            <option value="center" <?= $editingText['Column_Side'] === 'center' ? 'selected' : ''; ?>>Center — Note (any language)</option>
                            <option value="right" <?= $editingText['Column_Side'] === 'right' ? 'selected' : ''; ?>>Right — Arabic (RTL)</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small mb-1">Size (px)</label>
                        <input type="number" name="font_size" class="form-control" min="5" max="20" value="<?= htmlspecialchars($editingText['Font_Size']); ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label small mb-1">Align</label>
                        <select name="text_align" class="form-select">
                            <?php foreach (['left', 'center', 'right', 'justify'] as $a): ?>
                                <option value="<?= $a; ?>" <?= $editingText['Text_Align'] === $a ? 'selected' : ''; ?>><?= ucfirst($a); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small mb-1">Color</label>
                        <input type="color" name="text_color" class="form-control form-control-color w-100" value="<?= htmlspecialchars($editingText['Text_Color']); ?>">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small mb-1 d-block">Bold</label>
                        <div class="form-check form-switch mt-2">
                            <input class="form-check-input" type="checkbox" name="bold" <?= $editingText['Font_Weight'] === 'bold' ? 'checked' : ''; ?>>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label small mb-1">Order</label>
                        <input type="number" name="sort_order" class="form-control" value="<?= htmlspecialchars($editingText['Sort_Order']); ?>">
                    </div>
                </div>
                <div class="text-end mt-3">
                    <?php if ($editingText['id']): ?>
                        <a href="certificate_settings.php" class="btn btn-outline-secondary me-2">Cancel Edit</a>
                    <?php endif; ?>
                    <button type="submit" class="btn btn-warning fw-bold px-4"><?= $editingText['id'] ? 'Update Line' : 'Add Line'; ?></button>
                </div>
            </form>
        </div>
    </div>

    <!-- Live Preview — renders the SAME renderCertFooterBand() function the
         real certificate PDF uses (required in via includes/cert_footer_render.php
         above), not a hand-copied look-alike, so this preview can never
         silently drift from what actually prints. Only used when Display
         Mode is "Text Lines" (the image mode already shows its own preview
         thumbnail above). $pdf_mode is explicitly forced to false here —
         this page is browser-only and never sets that global itself, so
         without this renderCertFooterBand()'s `global $pdf_mode;` would see
         an undefined variable. Wrapper is real physical mm units (210mm ×
         40mm) so what's on screen is true to scale, not an approximation. -->
    <?php if ($settings['Footer_Mode'] !== 'image'): ?>
    <div class="card mb-4 border-info">
        <div class="card-header bg-info text-dark fw-bold"><i class="fa-solid fa-eye me-1"></i> Live Preview — Bottom Margin (as it will appear on the certificate)</div>
        <div class="card-body" style="overflow-x:auto;">
            <?php $pdf_mode = false; ?>
            <div style="position:relative; width:210mm; max-width:100%; height:40mm; margin:0 auto; background:#fff; border:1px dashed #999;">
                <?php renderCertFooterBand($footerTexts, $settings); ?>
            </div>
            <p class="small text-muted mt-2 mb-0">Right = Arabic (RTL), Center = note, Left = English (LTR). The dashed box is the full certificate page width; the margin is pinned to its bottom edge exactly as shown here.</p>
        </div>
    </div>
    <?php endif; ?>

    <div class="card mb-4">
        <div class="card-header bg-dark text-white fw-bold">Current Margin Lines (in display order)</div>
        <ul class="list-group list-group-flush">
            <?php if (empty($footerTexts)): ?>
                <li class="list-group-item text-muted small">No lines yet — the margin is blank.</li>
            <?php endif; ?>
            <?php
            // Side badge — label/color per zone. Kept as one lookup table
            // (rather than a chain of ternaries) now that there are three
            // zones instead of two, so a future fourth zone is a one-line
            // change here instead of another nested ternary.
            $sideBadges = [
                'left'   => ['bg-primary', 'Left / EN'],
                'center' => ['bg-info text-dark', 'Center'],
                'right'  => ['bg-success', 'Right / AR'],
            ];
            ?>
            <?php foreach ($footerTexts as $ft): ?>
                <?php [$badgeClass, $badgeLabel] = $sideBadges[$ft['Column_Side']] ?? $sideBadges['left']; ?>
                <li class="list-group-item d-flex justify-content-between align-items-center">
                    <span>
                        <span class="badge <?= $badgeClass; ?> me-2"><?= htmlspecialchars($badgeLabel); ?></span>
                        <span style="font-size: <?= (int) $ft['Font_Size']; ?>px; color: <?= htmlspecialchars($ft['Text_Color']); ?>; font-weight: <?= htmlspecialchars($ft['Font_Weight']); ?>;">
                            <?= htmlspecialchars(mb_strimwidth($ft['Text_Content'], 0, 80, '...')); ?>
                        </span>
                    </span>
                    <span>
                        <a href="certificate_settings.php?edit_text_id=<?= (int) $ft['id']; ?>" class="btn btn-sm btn-outline-primary"><i class="fa-solid fa-pen"></i></a>
                        <a href="certificate_settings.php?delete_text_id=<?= (int) $ft['id']; ?>&amp;csrf_token=<?= urlencode(csrf_token()); ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Remove this line?');"><i class="fa-solid fa-trash"></i></a>
                    </span>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>

</div>
</body>
</html>
