<?php

require_once __DIR__ . '/db/auth.php';

auth_start_session();
auth_bootstrap();

if (!auth_is_logged_in()) {
    header('Location: index.php');
    exit;
}

$flash = auth_flash_get();
$flash_type = $flash['type'] ?? '';
$flash_message = $flash['message'] ?? '';

$db = db();
$csrf_token = auth_csrf_token();

$current_session_user = $_SESSION['user'] ?? '';
$current_session_role = $_SESSION['role'] ?? 'member';
$role_label = ($current_session_role === 'admin') ? 'Administrateur' : 'Membre';

function normalize_catalog_label(string $value): string {
    $value = trim($value);
    return function_exists('mb_strtolower') ? mb_strtolower($value, 'UTF-8') : strtolower($value);
}

function find_preset_ship_relation(PDO $db, int $manufactureId, int $shipId): ?array {
    if ($manufactureId <= 0 || $shipId <= 0) {
        return null;
    }

    $stmt = $db->prepare(
        "SELECT
            m.cl_scmanufactures_id,
            m.cl_scmanufactures_name,
            v.cl_scvaisseaux_id,
            v.cl_scvaisseaux_name
        FROM tbl_scvaisseaux v
        INNER JOIN tbl_scmanufactures m
            ON m.cl_scmanufactures_id = v.cl_scvaisseaux_manufacture_id
        WHERE m.cl_scmanufactures_id = :manufacture_id
          AND v.cl_scvaisseaux_id = :ship_id
        LIMIT 1"
    );
    $stmt->execute([
        'manufacture_id' => $manufactureId,
        'ship_id' => $shipId,
    ]);

    $relation = $stmt->fetch();
    return $relation ?: null;
}

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $submitted_csrf = $_POST['csrf_token'] ?? '';
    if (!auth_validate_csrf($submitted_csrf)) {
        auth_flash_set('error', 'Jeton CSRF invalide.');
        header('Location: scpreset.php');
        exit;
    }

    $action = $_POST['action'] ?? '';

    // Add preset
    if ($action === 'add_preset') {
        $manufacture_id = (int)($_POST['manufacture_id'] ?? 0);
        $ship_id = (int)($_POST['ship_id'] ?? 0);
        $description = trim($_POST['description'] ?? '');
        $link = trim($_POST['link'] ?? '');
        $creator = $current_session_user ?: 'Inconnu';
        $relation = find_preset_ship_relation($db, $manufacture_id, $ship_id);

        if ($relation && $link !== '') {
            try {
                $stmt = $db->prepare("INSERT INTO tbl_scpreset (
                    cl_scpreset_manufacture_id,
                    cl_scpreset_vaisseau_id,
                    cl_scpreset_name,
                    cl_scpreset_manufacturer,
                    cl_scpreset_description,
                    cl_scpreset_link,
                    cl_scpreset_creator
                ) VALUES (
                    :manufacture_id,
                    :ship_id,
                    :name,
                    :manufacturer,
                    :description,
                    :link,
                    :creator
                )");
                $stmt->execute([
                    'manufacture_id' => $relation['cl_scmanufactures_id'],
                    'ship_id' => $relation['cl_scvaisseaux_id'],
                    'name' => $relation['cl_scvaisseaux_name'],
                    'manufacturer' => $relation['cl_scmanufactures_name'],
                    'description' => $description,
                    'link' => $link,
                    'creator' => $creator,
                ]);
                auth_flash_set('success', 'Preset ajouté avec succès.');
            } catch (PDOException $e) {
                auth_flash_set('error', 'Erreur lors de l\'ajout : ' . $e->getMessage());
            }
        } else {
            auth_flash_set('error', 'Veuillez sélectionner une manufacture, un vaisseau valide et renseigner le lien.');
        }
        header('Location: scpreset.php');
        exit;
    }

    // Update preset
    if ($action === 'update_preset') {
        $preset_id = (int)($_POST['preset_id'] ?? 0);
        $manufacture_id = (int)($_POST['manufacture_id'] ?? 0);
        $ship_id = (int)($_POST['ship_id'] ?? 0);
        $description = trim($_POST['description'] ?? '');
        $link = trim($_POST['link'] ?? '');
        $relation = find_preset_ship_relation($db, $manufacture_id, $ship_id);

        if ($preset_id > 0 && $relation && $link !== '') {
            try {
                $stmt = $db->prepare("UPDATE tbl_scpreset SET
                    cl_scpreset_manufacture_id = :manufacture_id,
                    cl_scpreset_vaisseau_id = :ship_id,
                    cl_scpreset_name = :name,
                    cl_scpreset_manufacturer = :manufacturer,
                    cl_scpreset_description = :description,
                    cl_scpreset_link = :link
                    WHERE cl_scpreset_id = :id");
                $stmt->execute([
                    'manufacture_id' => $relation['cl_scmanufactures_id'],
                    'ship_id' => $relation['cl_scvaisseaux_id'],
                    'name' => $relation['cl_scvaisseaux_name'],
                    'manufacturer' => $relation['cl_scmanufactures_name'],
                    'description' => $description,
                    'link' => $link,
                    'id' => $preset_id,
                ]);
                auth_flash_set('success', 'Preset mis à jour.');
            } catch (PDOException $e) {
                auth_flash_set('error', 'Erreur lors de la mise à jour : ' . $e->getMessage());
            }
        } else {
            auth_flash_set('error', 'Données invalides : sélectionne une manufacture, un vaisseau valide et un lien.');
        }
        header('Location: scpreset.php');
        exit;
    }

    // Delete preset
    if ($action === 'delete_preset') {
        $preset_id = (int)($_POST['preset_id'] ?? 0);
        if ($preset_id > 0) {
            $stmt = $db->prepare("DELETE FROM tbl_scpreset WHERE cl_scpreset_id = :id");
            $stmt->execute(['id' => $preset_id]);
            auth_flash_set('success', 'Preset supprimé.');
        } else {
            auth_flash_set('error', 'ID de preset invalide.');
        }
        header('Location: scpreset.php');
        exit;
    }
}

$stmt_mans = $db->query("SELECT * FROM tbl_scmanufactures ORDER BY cl_scmanufactures_name ASC");
$manufactures = $stmt_mans->fetchAll();

$stmt_ships = $db->query("SELECT
    v.cl_scvaisseaux_id,
    v.cl_scvaisseaux_name,
    v.cl_scvaisseaux_manufacture_id,
    m.cl_scmanufactures_name
FROM tbl_scvaisseaux v
INNER JOIN tbl_scmanufactures m ON m.cl_scmanufactures_id = v.cl_scvaisseaux_manufacture_id
ORDER BY m.cl_scmanufactures_name ASC, v.cl_scvaisseaux_name ASC");
$ships = $stmt_ships->fetchAll();

$manufacture_lookup = [];
$ships_by_manufacture = [];
$ships_by_id = [];
$ship_lookup = [];

foreach ($manufactures as $manufacture) {
    $manufacture_lookup[normalize_catalog_label($manufacture['cl_scmanufactures_name'])] = (int)$manufacture['cl_scmanufactures_id'];
    $ships_by_manufacture[(int)$manufacture['cl_scmanufactures_id']] = [];
}

foreach ($ships as $ship) {
    $manufactureId = (int)$ship['cl_scvaisseaux_manufacture_id'];
    $shipId = (int)$ship['cl_scvaisseaux_id'];
    $shipName = $ship['cl_scvaisseaux_name'];
    $manufacturerName = $ship['cl_scmanufactures_name'];

    $ships_by_manufacture[$manufactureId][] = [
        'id' => $shipId,
        'name' => $shipName,
    ];
    $ships_by_id[$shipId] = [
        'id' => $shipId,
        'name' => $shipName,
        'manufacture_id' => $manufactureId,
        'manufacturer_name' => $manufacturerName,
    ];
    $ship_lookup[$manufactureId . '|' . normalize_catalog_label($shipName)] = $shipId;
}

$stmt_list = $db->query("SELECT
    p.*,
    m.cl_scmanufactures_name AS relation_manufacturer_name,
    v.cl_scvaisseaux_name AS relation_ship_name,
    v.cl_scvaisseaux_manufacture_id AS relation_ship_manufacture_id
FROM tbl_scpreset p
LEFT JOIN tbl_scmanufactures m ON m.cl_scmanufactures_id = p.cl_scpreset_manufacture_id
LEFT JOIN tbl_scvaisseaux v ON v.cl_scvaisseaux_id = p.cl_scpreset_vaisseau_id
ORDER BY COALESCE(m.cl_scmanufactures_name, p.cl_scpreset_manufacturer) ASC,
         COALESCE(v.cl_scvaisseaux_name, p.cl_scpreset_name) ASC");
$presets = $stmt_list->fetchAll();

foreach ($presets as &$preset) {
    $resolvedManufactureId = (int)($preset['cl_scpreset_manufacture_id'] ?? 0);
    if ($resolvedManufactureId <= 0) {
        $manufacturerKey = normalize_catalog_label((string)($preset['cl_scpreset_manufacturer'] ?? ''));
        if ($manufacturerKey !== '' && isset($manufacture_lookup[$manufacturerKey])) {
            $resolvedManufactureId = $manufacture_lookup[$manufacturerKey];
        }
    }

    $resolvedShipId = (int)($preset['cl_scpreset_vaisseau_id'] ?? 0);
    if ($resolvedShipId <= 0 && $resolvedManufactureId > 0) {
        $shipKey = $resolvedManufactureId . '|' . normalize_catalog_label((string)($preset['cl_scpreset_name'] ?? ''));
        if (isset($ship_lookup[$shipKey])) {
            $resolvedShipId = $ship_lookup[$shipKey];
        }
    }

    $displayManufacturer = $preset['relation_manufacturer_name'] ?: $preset['cl_scpreset_manufacturer'];
    $displayName = $preset['relation_ship_name'] ?: $preset['cl_scpreset_name'];

    if ($resolvedShipId > 0 && isset($ships_by_id[$resolvedShipId])) {
        $displayName = $ships_by_id[$resolvedShipId]['name'];
        $displayManufacturer = $ships_by_id[$resolvedShipId]['manufacturer_name'];
        $resolvedManufactureId = $ships_by_id[$resolvedShipId]['manufacture_id'];
    }

    $preset['resolved_manufacture_id'] = $resolvedManufactureId;
    $preset['resolved_ship_id'] = $resolvedShipId;
    $preset['display_manufacturer'] = $displayManufacturer;
    $preset['display_name'] = $displayName;
}
unset($preset);
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Presets Vaisseaux | R.E.A.C.T. Admin</title>
    <link rel="stylesheet" type="text/css" href="css/styles.css">
    <link rel="stylesheet" type="text/css" href="css/default.css">
    <style>
        :root {
            --primary: #a29b78;
            --primary-glow: rgba(162, 155, 120, 0.4);
            --bg-dark: #080a0f;
            --card-bg: rgba(20, 24, 33, 0.85);
            --border-glow: rgba(162, 155, 120, 0.25);
            --danger: #ff4d4d;
            --success: #00ff88;
        }

        @font-face {
            font-family: 'Electrolize';
            src: url('fonts/Electrolize-Regular.ttf') format('truetype');
        }

        body {
            background: radial-gradient(circle at top right, #1a1f2e, var(--bg-dark));
            background-attachment: fixed;
            color: #e0e0e0;
            font-family: 'Electrolize', sans-serif;
            margin: 0;
            overflow-x: hidden;
            min-height: 100vh;
        }

        .admin-layout {
            display: flex;
            flex-direction: column;
            max-width: 1400px;
            margin: 0 auto;
            padding: 2rem;
            animation: fadeIn 0.6s ease-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .admin-topbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1.5rem 2rem;
            background: var(--card-bg);
            backdrop-filter: blur(10px);
            border: 1px solid var(--border-glow);
            border-radius: 12px;
            margin-bottom: 2rem;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
        }

        .topbar-info h1 {
            margin: 0;
            font-size: 1.5rem;
            letter-spacing: 2px;
            text-transform: uppercase;
            background: linear-gradient(90deg, #fff, var(--primary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .topbar-info p {
            margin: 0.25rem 0 0;
            font-size: 0.85rem;
            color: var(--primary);
            opacity: 0.8;
        }

        .btn-modern {
            padding: 0.6rem 1.2rem;
            border: 1px solid var(--primary);
            background: transparent;
            color: #fff;
            font-family: 'Electrolize', sans-serif;
            font-size: 0.9rem;
            text-transform: uppercase;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            border-radius: 4px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
        }

        .btn-modern:hover {
            background: var(--primary);
            color: var(--bg-dark);
            box-shadow: 0 0 15px var(--primary-glow);
        }

        .btn-modern.danger { border-color: var(--danger); color: var(--danger); }
        .btn-modern.danger:hover { background: var(--danger); color: #fff; }

        .btn-mini { padding: 0.3rem 0.6rem; font-size: 0.75rem; }

        .nav-tabs { display: flex; gap: 1rem; margin-bottom: 2rem; border-bottom: 1px solid var(--border-glow); padding-bottom: 1rem; }
        .nav-tabs a { text-decoration: none; color: #888; text-transform: uppercase; font-size: 0.9rem; transition: color 0.3s; }
        .nav-tabs a:hover, .nav-tabs a.active { color: var(--primary); }

        .admin-grid {
            display: grid;
            grid-template-columns: 1fr 2fr;
            gap: 2rem;
        }

        @media (max-width: 1024px) {
            .admin-grid { grid-template-columns: 1fr; }
        }

        .glass-card {
            background: var(--card-bg);
            backdrop-filter: blur(12px);
            border: 1px solid var(--border-glow);
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
            height: fit-content;
        }

        .glass-card h2 {
            margin-top: 0;
            margin-bottom: 1.5rem;
            font-size: 1.25rem;
            color: var(--primary);
            border-bottom: 1px solid var(--border-glow);
            padding-bottom: 0.75rem;
        }

        .form-group { margin-bottom: 1.5rem; }
        .form-group label { display: block; margin-bottom: 0.5rem; font-size: 0.85rem; color: #aaa; text-transform: uppercase; }
        .form-control {
            width: 100%;
            padding: 0.8rem 1rem;
            background: rgba(0, 0, 0, 0.3);
            border: 1px solid #444;
            border-radius: 4px;
            color: #fff;
            font-family: 'Electrolize', sans-serif;
            transition: border-color 0.3s;
        }
        .form-control:focus { outline: none; border-color: var(--primary); background: rgba(0, 0, 0, 0.5); }
        .form-control:disabled { opacity: 0.55; cursor: not-allowed; }
        .form-help {
            margin-top: 0.5rem;
            font-size: 0.78rem;
            color: #8f8f8f;
            line-height: 1.45;
        }

        .modern-table { width: 100%; border-collapse: separate; border-spacing: 0 8px; }
        .modern-table th { text-align: left; padding: 1rem; font-size: 0.8rem; text-transform: uppercase; color: var(--primary); opacity: 0.7; }
        .modern-table td { padding: 1rem; background: rgba(255, 255, 255, 0.03); border-top: 1px solid rgba(255, 255, 255, 0.05); border-bottom: 1px solid rgba(255, 255, 255, 0.05); }
        .modern-table td:first-child { border-left: 1px solid rgba(255, 255, 255, 0.05); border-radius: 8px 0 0 8px; }
        .modern-table td:last-child { border-right: 1px solid rgba(255, 255, 255, 0.05); border-radius: 0 8px 8px 0; }
        .modern-table tr:hover td { background: rgba(162, 155, 120, 0.05); }

        .flash { padding: 1rem 1.5rem; border-radius: 8px; margin-bottom: 1.5rem; font-size: 0.9rem; border-left: 4px solid var(--primary); background: rgba(162, 155, 120, 0.1); }
        .flash.error { border-color: var(--danger); background: rgba(255, 77, 77, 0.1); color: #ffbaba; }
        .flash.success { border-color: var(--success); background: rgba(0, 255, 136, 0.1); color: #baffda; }

        .manufacturer-text {
            font-size: 0.65rem;
            color: #888;
            text-transform: uppercase;
            letter-spacing: 1px;
            display: block;
            margin-top: 2px;
        }

        .creator-text {
            font-size: 0.65rem;
            color: #888;
            font-style: italic;
            display: block;
            margin-top: 1px;
        }

        .desc-text {
            font-size: 0.8rem;
            color: #aaa;
            max-width: 300px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .link-text {
            font-size: 0.75rem;
            color: var(--primary);
            opacity: 0.8;
            text-decoration: none;
        }
        .link-text:hover { text-decoration: underline; }
    </style>
</head>
<body>
    <div class="admin-layout">
        <header class="admin-topbar">
            <div class="topbar-info">
                <h1>R.E.A.C.T. Ship Presets</h1>
                <p>Niveau d\'accès : <strong><?php echo htmlspecialchars($role_label); ?></strong> | Session : <strong><?php echo htmlspecialchars($current_session_user); ?></strong></p>
            </div>
            <div class="topbar-actions">
                <a href="index.php" class="btn-modern">Site</a>
                <a href="logout.php" class="btn-modern danger">Exit</a>
            </div>
        </header>

        <nav class="nav-tabs">
            <?php if (auth_is_admin()): ?>
                <a href="admin.php">Utilisateurs</a>
                <a href="scwebhook.php">WEBHOOK</a>
                <a href="scnotification.php">NOTIF DISCORD</a>
                <a href="scitems.php">Base d'Objets</a>
                <a href="scstatsitem.php">Stats Item</a>
                <a href="scitemcustom.php">Item Custom</a>
                <a href="scmining.php">Scanner Minage</a>
                <a href="scmanufactures.php">Manufactures</a>
                <a href="scvaisseaux.php">Vaisseaux</a>
            <?php endif; ?>
            <a href="scpreset.php" class="active">Presets Vaisseau</a>
        </nav>

        <?php if ($flash_message !== ''): ?>
            <div class="flash <?php echo htmlspecialchars($flash_type); ?>">
                <?php echo htmlspecialchars($flash_message); ?>
            </div>
        <?php endif; ?>

        <div class="admin-grid">
            <!-- Left Column: Add/Edit Preset -->
            <div class="side-panel">
                <section class="glass-card">
                    <h2 id="formTitle">Nouveau Preset</h2>
                    <?php if (empty($manufactures)): ?>
                        <p style="color: var(--danger); font-size: 0.9rem;">Aucune manufacture n'est disponible. Ajoute d'abord une manufacture.</p>
                        <a href="scmanufactures.php" class="btn-modern" style="width: 100%;">Gérer les manufactures</a>
                    <?php elseif (empty($ships)): ?>
                        <p style="color: var(--danger); font-size: 0.9rem;">Aucun vaisseau n'est disponible. Ajoute d'abord au moins un vaisseau lié à une manufacture.</p>
                        <a href="scvaisseaux.php" class="btn-modern" style="width: 100%;">Gérer les vaisseaux</a>
                    <?php else: ?>
                    <form id="presetForm" method="post">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                        <input type="hidden" name="action" id="formAction" value="add_preset">
                        <input type="hidden" name="preset_id" id="presetId" value="">
                        
                        <div class="form-group">
                            <label>Manufacture</label>
                            <select name="manufacture_id" id="presetManufactureId" class="form-control" required>
                                <option value="">- Sélectionner une manufacture -</option>
                                <?php foreach ($manufactures as $m): ?>
                                    <option value="<?php echo $m['cl_scmanufactures_id']; ?>"><?php echo htmlspecialchars($m['cl_scmanufactures_name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Vaisseau</label>
                            <select name="ship_id" id="presetShipId" class="form-control" required disabled>
                                <option value="">- Choisissez d'abord une manufacture -</option>
                            </select>
                            <div class="form-help">Le vaisseau affiché dépend de la manufacture choisie. Le nom et la manufacture du preset seront remplis automatiquement.</div>
                        </div>

                        <div class="form-group">
                            <label>Description</label>
                            <textarea name="description" id="presetDescription" class="form-control" rows="3" placeholder="Description du preset..."></textarea>
                        </div>

                        <div class="form-group">
                            <label>Lien Externe</label>
                            <input type="url" name="link" id="presetLink" class="form-control" required placeholder="https://...">
                        </div>

                        <button type="submit" id="submitBtn" class="btn-modern" style="width: 100%;">Ajouter</button>
                        <button type="button" id="cancelBtn" class="btn-modern" style="width: 100%; margin-top: 10px; display: none;" onclick="resetForm()">Annuler</button>
                    </form>
                    <?php endif; ?>
                </section>
            </div>

            <!-- Right Column: List -->
            <main class="main-panel">
                <section class="glass-card">
                    <h2>Liste des Presets</h2>
                    <div style="overflow-x: auto;">
                        <table class="modern-table">
                            <thead>
                                <tr>
                                    <th>Vaisseau / Manufacture</th>
                                    <th>Description</th>
                                    <th>Lien</th>
                                    <th style="text-align: right;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($presets)): ?>
                                    <tr><td colspan="4" style="text-align: center; padding: 3rem; color: #666;">Aucun preset enregistré.</td></tr>
                                <?php else: ?>
                                    <?php foreach ($presets as $p): ?>
                                    <tr>
                                        <td>
                                            <strong style="color: var(--primary); text-transform: uppercase;"><?php echo htmlspecialchars($p['display_name']); ?></strong><br>
                                            <span class="manufacturer-text"><?php echo htmlspecialchars($p['display_manufacturer']); ?></span>
                                            <span class="creator-text">Par <?php echo htmlspecialchars($p['cl_scpreset_creator'] ?: 'Inconnu'); ?></span>
                                        </td>
                                        <td>
                                            <div class="desc-text" title="<?php echo htmlspecialchars($p['cl_scpreset_description']); ?>">
                                                <?php echo htmlspecialchars($p['cl_scpreset_description'] ?: 'Aucune description'); ?>
                                            </div>
                                        </td>
                                        <td>
                                            <a href="<?php echo htmlspecialchars($p['cl_scpreset_link']); ?>" target="_blank" class="link-text">Consulter le lien</a>
                                        </td>
                                        <td style="text-align: right;">
                                            <div style="display: flex; gap: 5px; justify-content: flex-end;">
                                                <button type="button" class="btn-modern btn-mini" 
                                                    onclick='editPreset(<?php echo json_encode([
                                                        "id" => $p["cl_scpreset_id"],
                                                        "manufacture_id" => $p["resolved_manufacture_id"],
                                                        "ship_id" => $p["resolved_ship_id"],
                                                        "name" => $p["display_name"],
                                                        "manufacturer" => $p["display_manufacturer"],
                                                        "description" => $p["cl_scpreset_description"],
                                                        "link" => $p["cl_scpreset_link"]
                                                    ], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP); ?>)'>
                                                    Edit
                                                </button>
                                                <form method="post" onsubmit="return confirm('Supprimer ce preset ?');">
                                                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                                    <input type="hidden" name="action" value="delete_preset">
                                                    <input type="hidden" name="preset_id" value="<?php echo $p['cl_scpreset_id']; ?>">
                                                    <button type="submit" class="btn-modern btn-mini danger">X</button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </section>
            </main>
        </div>
    </div>

    <script>
        const shipsByManufacture = <?php echo json_encode($ships_by_manufacture, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP); ?>;
        const presetForm = document.getElementById('presetForm');
        const manufactureSelect = document.getElementById('presetManufactureId');
        const shipSelect = document.getElementById('presetShipId');

        function populateShipOptions(manufactureId, selectedShipId = '') {
            if (!shipSelect) {
                return;
            }

            shipSelect.innerHTML = '';

            if (!manufactureId || !shipsByManufacture[manufactureId] || shipsByManufacture[manufactureId].length === 0) {
                shipSelect.disabled = true;
                shipSelect.innerHTML = '<option value="">- Choisissez d\'abord une manufacture -</option>';
                return;
            }

            shipSelect.disabled = false;
            shipSelect.innerHTML = '<option value="">- Sélectionner un vaisseau -</option>';

            shipsByManufacture[manufactureId].forEach((ship) => {
                const option = document.createElement('option');
                option.value = String(ship.id);
                option.textContent = ship.name;
                if (selectedShipId && String(selectedShipId) === String(ship.id)) {
                    option.selected = true;
                }
                shipSelect.appendChild(option);
            });
        }

        if (manufactureSelect) {
            manufactureSelect.addEventListener('change', function () {
                populateShipOptions(this.value, '');
            });
            populateShipOptions(manufactureSelect.value, shipSelect ? shipSelect.value : '');
        }

        function editPreset(data) {
            if (!presetForm || !manufactureSelect || !shipSelect) {
                return;
            }

            document.getElementById('formAction').value = 'update_preset';
            document.getElementById('presetId').value = data.id;
            manufactureSelect.value = data.manufacture_id ? String(data.manufacture_id) : '';
            populateShipOptions(manufactureSelect.value, data.ship_id ? String(data.ship_id) : '');
            document.getElementById('presetDescription').value = data.description;
            document.getElementById('presetLink').value = data.link;
            
            document.getElementById('submitBtn').innerText = 'Mettre à jour';
            document.getElementById('cancelBtn').style.display = 'block';
            document.getElementById('formTitle').innerText = data.name && data.manufacturer
                ? `Modifier le Preset · ${data.manufacturer} / ${data.name}`
                : 'Modifier le Preset';
            
            presetForm.scrollIntoView({ behavior: 'smooth' });
        }

        function resetForm() {
            if (!presetForm) {
                return;
            }

            document.getElementById('formAction').value = 'add_preset';
            document.getElementById('presetId').value = '';
            presetForm.reset();
            populateShipOptions('', '');
            
            document.getElementById('submitBtn').innerText = 'Ajouter';
            document.getElementById('cancelBtn').style.display = 'none';
            document.getElementById('formTitle').innerText = 'Nouveau Preset';
        }
    </script>
</body>
</html>