<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
require_once('header.php');

$error_message = '';
$success_message = '';

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header('Location: top-category.php');
    exit;
}

$id = (int) $_GET['id'];

/* LOAD CATEGORY */
$stmt = $pdo->prepare("SELECT * FROM tbl_top_category WHERE id = ?");
$stmt->execute([$id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$row) {
    header('Location: top-category.php');
    exit;
}

/* UPDATE CATEGORY DETAILS */
if (isset($_POST['form1'])) {
    $valid = true;

    $top_category_name = trim($_POST['top_category_name'] ?? '');
    $top_category_slug = trim($_POST['top_category_slug'] ?? '');
    $short_name = trim($_POST['short_name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $meta_title = trim($_POST['meta_title'] ?? '');
    $meta_keyword = trim($_POST['meta_keyword'] ?? '');
    $meta_description = trim($_POST['meta_description'] ?? '');
    $show_on_menu = (int)($_POST['show_on_menu'] ?? 0);

    $features = $_POST['features'] ?? [];
    if (!is_array($features)) {
        $features = [];
    }
    $features = array_values(array_filter(array_map('trim', $features)));
    $features_json = json_encode($features, JSON_UNESCAPED_UNICODE);

    $applications = $_POST['applications'] ?? [];
    if (!is_array($applications)) {
        $applications = [];
    }
    $applications = array_values(array_filter(array_map('trim', $applications)));
    $applications_json = json_encode($applications, JSON_UNESCAPED_UNICODE);

    if ($top_category_name === '') {
        $valid = false;
        $error_message .= 'Category name is required.<br>';
    }

    if ($top_category_slug === '') {
        $valid = false;
        $error_message .= 'Category slug is required.<br>';
    } else {
        $top_category_slug = strtolower($top_category_slug);
        $top_category_slug = preg_replace('/[^a-z0-9]+/', '-', $top_category_slug);
        $top_category_slug = trim($top_category_slug, '-');
    }

    $check = $pdo->prepare("
        SELECT id FROM tbl_top_category
        WHERE top_category_name = ? AND id != ?
        LIMIT 1
    ");
    $check->execute([$top_category_name, $id]);

    if ($check->fetchColumn()) {
        $valid = false;
        $error_message .= 'Category name already exists.<br>';
    }

    $check = $pdo->prepare("
        SELECT id FROM tbl_top_category
        WHERE top_category_slug = ? AND id != ?
        LIMIT 1
    ");
    $check->execute([$top_category_slug, $id]);

    if ($check->fetchColumn()) {
        $valid = false;
        $error_message .= 'Category slug already exists.<br>';
    }

    $banner = $row['banner'] ?? '';
    $new_banner_uploaded = false;

    /* BANNER UPLOAD */
    if (
        isset($_FILES['banner']) &&
        $_FILES['banner']['error'] !== UPLOAD_ERR_NO_FILE
    ) {
        $extension = strtolower(
            pathinfo($_FILES['banner']['name'], PATHINFO_EXTENSION)
        );

        if (!in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'webp'], true)) {
            $valid = false;
            $error_message .= 'Allowed banner formats: JPG, JPEG, PNG, GIF, WEBP.<br>';
        } elseif ($_FILES['banner']['error'] !== UPLOAD_ERR_OK) {
            $valid = false;
            $error_message .= 'Banner upload failed.<br>';
        } else {
            $upload_directory = __DIR__ . '/assets/images/category/';

            if (!is_dir($upload_directory)) {
                mkdir($upload_directory, 0755, true);
            }

            $new_banner = 'category-' . time() . '-' .
                uniqid() . '.' . $extension;

            if (move_uploaded_file(
                $_FILES['banner']['tmp_name'],
                $upload_directory . $new_banner
            )) {
                $banner = $new_banner;
                $new_banner_uploaded = true;
            } else {
                $valid = false;
                $error_message .= 'Could not upload banner.<br>';
            }
        }
    }

    if ($valid) {
        try {
            $update = $pdo->prepare("
                UPDATE tbl_top_category SET
                    top_category_name = ?,
                    top_category_slug = ?,
                    short_name = ?,
                    banner = ?,
                    description = ?,
                    features = ?,
                    applications = ?,
                    show_on_menu = ?,
                    meta_title = ?,
                    meta_keyword = ?,
                    meta_description = ?,
                    updated_at = NOW()
                WHERE id = ?
            ");

            $update->execute([
                $top_category_name,
                $top_category_slug,
                $short_name,
                $banner,
                $description,
                $features_json,
                $applications_json,
                $show_on_menu,
                $meta_title,
                $meta_keyword,
                $meta_description,
                $id
            ]);

            if (
                $new_banner_uploaded &&
                !empty($row['banner']) &&
                $row['banner'] !== $banner
            ) {
                $old_file = __DIR__ . '/assets/images/category/' . $row['banner'];

                if (is_file($old_file)) {
                    @unlink($old_file);
                }
            }

            $success_message = 'Category updated successfully.';

            $stmt = $pdo->prepare("SELECT * FROM tbl_top_category WHERE id = ?");
            $stmt->execute([$id]);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);

        } catch (PDOException $e) {
            if ($new_banner_uploaded) {
                $new_file = __DIR__ . '/assets/images/category/' . $banner;
                if (is_file($new_file)) {
                    @unlink($new_file);
                }
            }

            $error_message = 'Category update failed: ' .
                htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
        }
    }
}

/* SELECTED LOCATION FOR EDITING */
$selected_location_id = (int)($_POST['location_id'] ?? $_GET['location_id'] ?? 0);

/* SAVE CATEGORY LOCATION SEO: description only */
if (isset($_POST['save_category_location'])) {

    $category_id = (int)($_POST['category_id'] ?? 0);
    $location_id = (int)($_POST['location_id'] ?? 0);

    $description_loc = trim($_POST['description_loc'] ?? '');

    try {
        // Check category
        $check = $pdo->prepare(
            "SELECT id FROM tbl_top_category WHERE id = ? LIMIT 1"
        );
        $check->execute([$category_id]);

        if (!$check->fetchColumn()) {
            throw new Exception('Please select a valid category.');
        }

        // Check location
        $check = $pdo->prepare(
            "SELECT id FROM tbl_location WHERE id = ? AND status = 1 LIMIT 1"
        );
        $check->execute([$location_id]);

        if (!$check->fetchColumn()) {
            throw new Exception('Please select a valid location.');
        }

        // Find existing category-location record.
        $check = $pdo->prepare("
            SELECT id
            FROM tbl_service_location
            WHERE category_id = ?
              AND location_id = ?
              AND service_id IS NULL
            LIMIT 1
        ");
        $check->execute([$category_id, $location_id]);

        $existing_id = $check->fetchColumn();

        if ($existing_id) {
            // Update existing record.
            $stmt = $pdo->prepare("
                UPDATE tbl_service_location
                SET description = ?
                WHERE id = ?
                  AND category_id = ?
                  AND location_id = ?
                  AND service_id IS NULL
            ");

            $stmt->execute([
                $description_loc,
                $existing_id,
                $category_id,
                $location_id
            ]);
        } else {
            // Save category ID and keep service_id NULL.
            $stmt = $pdo->prepare("
                INSERT INTO tbl_service_location
                    (service_id, category_id, location_id, description)
                VALUES (NULL, ?, ?, ?)
            ");

            $stmt->execute([
                $category_id,
                $location_id,
                $description_loc
            ]);
        }

        $success_message = 'Category location content saved successfully.';

    } catch (Exception $e) {
        $error_message = 'Location save failed: ' .
            htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
    } catch (PDOException $e) {
        $error_message = 'Database save failed: ' .
            htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
    }
}


/* DELETE CATEGORY LOCATION */
if (isset($_POST['delete_category_location'])) {
    $record_id = (int)($_POST['category_location_id'] ?? 0);
    $delete_category_id = (int)($_POST['category_id'] ?? 0);

    try {
        $delete = $pdo->prepare("
            DELETE FROM tbl_service_location
            WHERE id = ?
              AND category_id = ?
              AND service_id IS NULL
        ");
        $delete->execute([$record_id, $delete_category_id]);

        $success_message = $delete->rowCount()
            ? 'Category location deleted successfully.'
            : 'Category location was not found.';
    } catch (PDOException $e) {
        $error_message = 'Location deletion failed: ' .
            htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
    }
}

/* LOAD ACTIVE LOCATIONS */
$location_options = $pdo->query("
    SELECT id, location_name
    FROM tbl_location
    WHERE status = 1
    ORDER BY location_name ASC
")->fetchAll(PDO::FETCH_ASSOC);

/* LOAD SAVED LOCATIONS FOR CURRENT CATEGORY */
$stmt = $pdo->prepare("
    SELECT sl.id, sl.category_id, sl.location_id,
           sl.short_description, sl.description, sl.content,
           l.location_name
    FROM tbl_service_location sl
    INNER JOIN tbl_location l ON l.id = sl.location_id
    WHERE sl.category_id = ?
      AND sl.service_id IS NULL
    ORDER BY l.location_name ASC
");
$stmt->execute([$id]);
$category_locations = $stmt->fetchAll(PDO::FETCH_ASSOC);

$location_description_map = [];
$selected_location_description = '';
foreach ($category_locations as $saved_location) {
    $location_description_map[(string)$saved_location['location_id']] = $saved_location['description'] ?? '';
    if ((int)$saved_location['location_id'] === $selected_location_id) {
        $selected_location_description = $saved_location['description'] ?? '';
    }
}
$location_description_json = json_encode($location_description_map, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);

/* CATEGORY FORM VALUES */
$top_category_name = $row['top_category_name'] ?? '';
$top_category_slug = $row['top_category_slug'] ?? '';
$short_name = $row['short_name'] ?? '';
$banner = $row['banner'] ?? '';
$description = $row['description'] ?? '';
$show_on_menu = $row['show_on_menu'] ?? 0;
$meta_title = $row['meta_title'] ?? '';
$meta_keyword = $row['meta_keyword'] ?? '';
$meta_description = $row['meta_description'] ?? '';

$features = json_decode($row['features'] ?? '[]', true);
if (!is_array($features) || !$features) {
    $features = [''];
}

$applications = json_decode($row['applications'] ?? '[]', true);
if (!is_array($applications) || !$applications) {
    $applications = [''];
}

/* LOAD CATEGORIES FOR THE LOCATION TAB */
$category_options = $pdo->query("
    SELECT id, top_category_name
    FROM tbl_top_category
    ORDER BY top_category_name ASC
")->fetchAll(PDO::FETCH_ASSOC);
?>

<section class="content-header">
    <div style="display:flex;justify-content:space-between;align-items:center;">
        <h1><i class="fa fa-edit"></i> Edit Category</h1>
        <a href="top-category.php" class="btn btn-primary">View All</a>
    </div>
</section>

<section class="content">

<style>
.category-editor{background:#fff;border:1px solid #e4e7eb;border-radius:4px;overflow:hidden}
.category-tabs{display:flex;border-bottom:1px solid #e4e7eb;background:#fff}
.category-tab{padding:16px 22px;border:0;border-top:3px solid transparent;background:#fff;color:#344054;cursor:pointer;font-size:15px}
.category-tab.active{border-top-color:#333;font-weight:600}
.category-tab-content{display:none;padding:22px}
.category-tab-content.active{display:block}
.category-field{margin-bottom:20px}
.category-field label{display:block;font-weight:600;margin-bottom:8px}
.category-field .form-control{min-height:41px;border-color:#d0d7e2;border-radius:0;box-shadow:none}
.location-card-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px;margin-top:24px}
.location-card{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:18px;min-height:76px;border:1px solid #ff4081;border-radius:14px;color:#e91e63;font-weight:600;background:#fff}
.location-delete{width:35px;height:35px;flex-shrink:0;border:1px solid #ff4081;border-radius:50%;background:#fff;color:#e91e63;cursor:pointer;font-size:19px}
.location-delete:hover{background:#e91e63;color:#fff}
.location-editor{width:100%;min-height:300px;overflow:auto;border:1px solid #ccc;padding:12px;font-family:Arial,sans-serif;background:#fff;line-height:1.6;outline:none}
.location-editor:focus{border-color:#3c8dbc;box-shadow:0 0 0 2px rgba(60,141,188,.12)}
.location-editor:empty:before{content:attr(data-placeholder);color:#999;pointer-events:none}
.location-editor p{margin:0 0 14px}
.location-editor h1,.location-editor h2,.location-editor h3{line-height:1.3;margin:18px 0 10px}
.location-editor-toolbar{display:flex;flex-wrap:wrap;gap:6px;padding:8px;border:1px solid #ccc;border-bottom:0;background:#f7f7f7}
.location-editor-toolbar select,.location-editor-toolbar button{min-height:32px;padding:5px 10px;border:1px solid #ccc;background:#fff;border-radius:3px;cursor:pointer}
.location-editor-toolbar button:hover{background:#eee}
.location-save{margin-top:10px;padding:10px 18px;border:0;border-radius:3px;color:#fff;background:#3498db;font-size:15px}
@media(max-width:900px){.location-card-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media(max-width:600px){.category-tab{white-space:nowrap;padding:13px 15px}.category-tab-content{padding:15px}.location-card-grid{grid-template-columns:1fr}}
</style>

<?php if ($error_message !== ''): ?>
    <div class="alert alert-danger"><?php echo $error_message; ?></div>
<?php endif; ?>

<?php if ($success_message !== ''): ?>
    <div class="alert alert-success"><?php echo htmlspecialchars($success_message, ENT_QUOTES, 'UTF-8'); ?></div>
<?php endif; ?>

<div class="category-editor">

    <div class="category-tabs">
        <button type="button" class="category-tab active" data-tab="category-details">
            Category Details
        </button>
        <button type="button" class="category-tab" data-tab="category-location">
            Location SEO
        </button>
    </div>

    <!-- CATEGORY DETAILS -->
    <div id="category-details" class="category-tab-content active">
        <form method="post" action="" enctype="multipart/form-data">

            <div class="category-field">
                <label>Category Name</label>
                <input type="text" name="top_category_name" class="form-control"
                    value="<?php echo htmlspecialchars($top_category_name, ENT_QUOTES, 'UTF-8'); ?>" required>
            </div>

            <div class="category-field">
                <label>Short Name</label>
                <input type="text" name="short_name" class="form-control"
                    value="<?php echo htmlspecialchars($short_name, ENT_QUOTES, 'UTF-8'); ?>">
            </div>

            <div class="category-field">
                <label>Category Slug</label>
                <input type="text" name="top_category_slug" class="form-control"
                    value="<?php echo htmlspecialchars($top_category_slug, ENT_QUOTES, 'UTF-8'); ?>" required>
            </div>

            <div class="category-field">
                <label>Description</label>
                <textarea name="description" id="editor2" class="form-control" rows="5"><?php
                    echo htmlspecialchars($description, ENT_QUOTES, 'UTF-8');
                ?></textarea>
            </div>

            <div class="category-field">
                <label>Existing Banner</label>
                <?php if ($banner !== ''): ?>
                    <img src="assets/images/category/<?php echo htmlspecialchars($banner, ENT_QUOTES, 'UTF-8'); ?>"
                         alt="Category banner" style="display:block;height:150px;margin-bottom:12px;">
                <?php else: ?>
                    <p>No banner uploaded.</p>
                <?php endif; ?>

                <label>Change Banner</label>
                <input type="file" name="banner" class="form-control"
                    accept=".jpg,.jpeg,.png,.gif,.webp">
            </div>

            <div class="category-field">
                <label>Features</label>
                <div id="features-wrapper">
                    <?php foreach ($features as $feature): ?>
                        <div class="feature-row" style="display:flex;gap:10px;margin-bottom:10px;">
                            <input type="text" name="features[]" class="form-control"
                                value="<?php echo htmlspecialchars($feature, ENT_QUOTES, 'UTF-8'); ?>">
                            <button type="button" class="btn btn-danger remove-feature">×</button>
                        </div>
                    <?php endforeach; ?>
                </div>
                <button type="button" id="add-feature" class="btn btn-default">+ Add Feature</button>
            </div>

            <div class="category-field">
                <label>Applications</label>
                <div id="applications-wrapper">
                    <?php foreach ($applications as $application): ?>
                        <div class="application-row" style="display:flex;gap:10px;margin-bottom:10px;">
                            <input type="text" name="applications[]" class="form-control"
                                value="<?php echo htmlspecialchars($application, ENT_QUOTES, 'UTF-8'); ?>">
                            <button type="button" class="btn btn-danger remove-application">×</button>
                        </div>
                    <?php endforeach; ?>
                </div>
                <button type="button" id="add-application" class="btn btn-default">+ Add Application</button>
            </div>

            <div class="category-field">
                <label>Show on Menu?</label>
                <select name="show_on_menu" class="form-control">
                    <option value="1" <?php echo ($show_on_menu == 1) ? 'selected' : ''; ?>>Yes</option>
                    <option value="0" <?php echo ($show_on_menu == 0) ? 'selected' : ''; ?>>No</option>
                </select>
            </div>

            <div class="category-field">
                <label>Meta Title</label>
                <input type="text" name="meta_title" class="form-control"
                    value="<?php echo htmlspecialchars($meta_title, ENT_QUOTES, 'UTF-8'); ?>">
            </div>

            <div class="category-field">
                <label>Meta Keywords</label>
                <textarea name="meta_keyword" class="form-control" rows="4"><?php
                    echo htmlspecialchars($meta_keyword, ENT_QUOTES, 'UTF-8');
                ?></textarea>
            </div>

            <div class="category-field">
                <label>Meta Description</label>
                <textarea name="meta_description" class="form-control" rows="4"><?php
                    echo htmlspecialchars($meta_description, ENT_QUOTES, 'UTF-8');
                ?></textarea>
            </div>

            <button type="submit" name="form1" class="btn btn-success">Update Category</button>
        </form>
    </div>

    <!-- LOCATION SEO -->
    <div id="category-location" class="category-tab-content">
        <form method="post" action="">

            <div class="category-field">
                <label>Select Category</label>
                <select name="category_id" id="category_id" class="form-control" required>
                    <option value="">Select Category</option>
                    <?php foreach ($category_options as $category): ?>
                        <option value="<?php echo (int)$category['id']; ?>"
                            <?php echo ((int)$category['id'] === $id) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($category['top_category_name'], ENT_QUOTES, 'UTF-8'); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="category-field">
                <label>Select Location</label>
                <select name="location_id" id="location_id" class="form-control" required>
                    <option value="">Select Location</option>
                    <?php foreach ($location_options as $location): ?>
                        <option value="<?php echo (int)$location['id']; ?>"
                            <?php echo ((int)$location['id'] === $selected_location_id) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($location['location_name'], ENT_QUOTES, 'UTF-8'); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="category-field">
                <label>Description</label>

                <div class="location-editor-toolbar" role="toolbar" aria-label="Description formatting">
                    <select id="location-format-block" aria-label="Text style">
                        <option value="p">Paragraph</option>
                        <option value="h1">Heading 1</option>
                        <option value="h2">Heading 2</option>
                        <option value="h3">Heading 3</option>
                    </select>
                    <button type="button" data-command="bold" title="Bold"><strong>B</strong></button>
                    <button type="button" data-command="italic" title="Italic"><em>I</em></button>
                    <button type="button" data-command="insertUnorderedList" title="Bulleted list">• List</button>
                    <button type="button" data-command="insertOrderedList" title="Numbered list">1. List</button>
                </div>

                <div id="description_loc_editor" class="location-editor" contenteditable="true"
                     role="textbox" aria-multiline="true"
                     data-placeholder="Enter paragraphs and headings as needed"><?php
                    echo $selected_location_description;
                ?></div>

                <textarea name="description_loc" id="description_loc" hidden><?php
                    echo htmlspecialchars($selected_location_description, ENT_QUOTES, 'UTF-8');
                ?></textarea>
                <small class="help-block">Choose Paragraph or Heading 1/2/3 for each block. You can use paragraphs only or mix headings and paragraphs.</small>
            </div>

            <button type="submit" name="save_category_location" value="1" class="location-save">
                Save Location Content
            </button>
        </form>

        <hr>
        <h4>Saved Locations for This Category</h4>

        <div class="location-card-grid">
            <?php foreach ($category_locations as $item): ?>
                <div class="location-card">
                    <span><?php echo htmlspecialchars($item['location_name'], ENT_QUOTES, 'UTF-8'); ?></span>

                    <form method="post" action=""
                        onsubmit="return confirm('Delete this category location?');" style="margin:0;">
                        <input type="hidden" name="category_location_id"
                            value="<?php echo (int)$item['id']; ?>">
                        <input type="hidden" name="category_id"
                            value="<?php echo (int)$item['category_id']; ?>">
                        <button type="submit" name="delete_category_location" value="1"
                            class="location-delete" title="Delete location">×</button>
                    </form>
                </div>
            <?php endforeach; ?>

            <?php if (empty($category_locations)): ?>
                <p>No location content has been added for this category yet.</p>
            <?php endif; ?>
        </div>
    </div>

</div>
</section>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const locationDescriptions = <?php echo $location_description_json ?: '{}'; ?>;
    const locationSelect = document.getElementById('location_id');
    const descriptionField = document.getElementById('description_loc');
    const descriptionEditor = document.getElementById('description_loc_editor');
    const formatSelect = document.getElementById('location-format-block');
    const locationForm = descriptionField ? descriptionField.closest('form') : null;

    function syncLocationDescription() {
        if (descriptionField && descriptionEditor) {
            descriptionField.value = descriptionEditor.innerHTML.trim();
        }
    }

    if (descriptionEditor && descriptionField) {
        // Keep the submitted textarea in sync with the rich-text editor.
        descriptionEditor.addEventListener('input', syncLocationDescription);

        if (formatSelect) {
            formatSelect.addEventListener('change', function () {
                descriptionEditor.focus();
                document.execCommand('formatBlock', false, this.value);
                syncLocationDescription();
            });
        }

        document.querySelectorAll('.location-editor-toolbar [data-command]').forEach(function (button) {
            button.addEventListener('click', function () {
                descriptionEditor.focus();
                document.execCommand(this.dataset.command, false, null);
                syncLocationDescription();
            });
        });

        if (locationForm) {
            locationForm.addEventListener('submit', syncLocationDescription);
        }
    }

    if (locationSelect && descriptionField && descriptionEditor) {
        locationSelect.addEventListener('change', function () {
            const html = locationDescriptions[this.value] || '';
            descriptionEditor.innerHTML = html;
            descriptionField.value = html;
        });
    }

    const tabButtons = document.querySelectorAll('.category-tab');
    const tabPanels = document.querySelectorAll('.category-tab-content');

    function activateTab(tabId) {
        tabButtons.forEach(function (button) {
            button.classList.toggle('active', button.dataset.tab === tabId);
        });

        tabPanels.forEach(function (panel) {
            panel.classList.toggle('active', panel.id === tabId);
        });
    }

    tabButtons.forEach(function (button) {
        button.addEventListener('click', function () {
            activateTab(button.dataset.tab);
        });
    });

    <?php if (
        isset($_POST['save_category_location']) ||
        isset($_POST['delete_category_location'])
    ): ?>
        activateTab('category-location');
    <?php endif; ?>

    document.getElementById('add-feature').addEventListener('click', function () {
        const wrapper = document.getElementById('features-wrapper');
        const row = document.createElement('div');
        row.className = 'feature-row';
        row.style.cssText = 'display:flex;gap:10px;margin-bottom:10px;';
        row.innerHTML = '<input type="text" name="features[]" class="form-control">' +
            '<button type="button" class="btn btn-danger remove-feature">×</button>';
        wrapper.appendChild(row);
    });

    document.getElementById('add-application').addEventListener('click', function () {
        const wrapper = document.getElementById('applications-wrapper');
        const row = document.createElement('div');
        row.className = 'application-row';
        row.style.cssText = 'display:flex;gap:10px;margin-bottom:10px;';
        row.innerHTML = '<input type="text" name="applications[]" class="form-control">' +
            '<button type="button" class="btn btn-danger remove-application">×</button>';
        wrapper.appendChild(row);
    });

    document.addEventListener('click', function (event) {
        if (event.target.classList.contains('remove-feature')) {
            const rows = document.querySelectorAll('.feature-row');
            if (rows.length > 1) event.target.closest('.feature-row').remove();
        }

        if (event.target.classList.contains('remove-application')) {
            const rows = document.querySelectorAll('.application-row');
            if (rows.length > 1) event.target.closest('.application-row').remove();
        }
    });
});
</script>

<?php require_once('footer.php'); ?>
