<?php

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

auth_start_session();
auth_bootstrap();

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

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

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

// 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: scmining.php');
        exit;
    }

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

    // Add mineral to list
    if ($action === 'add_mineral') {
        $obj_id = (int)$_POST['obj_id'];
        $return_search = trim($_POST['return_search'] ?? '');
        $return_page = max(1, (int)($_POST['return_page'] ?? 1));

        if ($obj_id > 0) {
            try {
                $stmt = $db->prepare("INSERT INTO tbl_scmining (cl_scmining_obj_id, cl_scmining_scan_value, cl_scmining_max_occurrence) VALUES (:obj_id, 0, 1)");
                $stmt->execute(['obj_id' => $obj_id]);
                auth_flash_set('success', 'Minéral ajouté avec succès.');
            } catch (PDOException $e) {
                if ($e->getCode() == 23000) {
                    auth_flash_set('error', 'Ce minéral est déjà dans la liste.');
                } else {
                    auth_flash_set('error', "Erreur lors de l'ajout : " . $e->getMessage());
                }
            }
        }
        header('Location: ' . scmining_search_url($return_search, $return_page));
        exit;
    }

    // Update mineral values
    if ($action === 'update_mineral') {
        $mining_id = (int)$_POST['mining_id'];
        $scan_value = (int)$_POST['scan_value'];
        $max_occurrence = (int)$_POST['max_occurrence'];
        $can_manual = isset($_POST['can_manual']) ? 1 : 0;
        $can_land = isset($_POST['can_land']) ? 1 : 0;
        $can_space = isset($_POST['can_space']) ? 1 : 0;

        $stmt = $db->prepare("UPDATE tbl_scmining SET cl_scmining_scan_value = :scan, cl_scmining_max_occurrence = :occ, cl_scmining_can_manual = :manual, cl_scmining_can_land = :land, cl_scmining_can_space = :space WHERE cl_scmining_id = :id");
        $stmt->execute([
            'scan' => $scan_value, 
            'occ' => $max_occurrence, 
            'manual' => $can_manual, 
            'land' => $can_land, 
            'space' => $can_space, 
            'id' => $mining_id
        ]);

        auth_flash_set('success', 'Valeurs mises à jour.');
        header('Location: scmining.php');
        exit;
    }

    // Remove mineral
    if ($action === 'delete_mineral') {
        $mining_id = (int)$_POST['mining_id'];
        $stmt = $db->prepare("DELETE FROM tbl_scmining WHERE cl_scmining_id = :id");
        $stmt->execute(['id' => $mining_id]);

        auth_flash_set('success', 'Minéral retiré de la liste.');
        header('Location: scmining.php');
        exit;
    }
}

// Search for adding items
function sc_normalize_rarity(?string $rarity): string
{
    return strtoupper(trim((string) $rarity));
}

function sc_rarity_class(?string $rarity): string
{
    $rarity = sc_normalize_rarity($rarity);

    return in_array($rarity, ['L', 'E', 'R', 'U', 'C'], true) ? 'rarity-' . $rarity : 'rarity-none';
}

function sc_rarity_style(?string $rarity): string
{
    return match (sc_normalize_rarity($rarity)) {
        'L' => 'color:#ff8000 !important;text-shadow:0 0 10px rgba(255,128,0,0.3);',
        'E' => 'color:#a335ee !important;text-shadow:0 0 10px rgba(163,53,238,0.3);',
        'R' => 'color:#0070dd !important;text-shadow:0 0 10px rgba(0,112,221,0.3);',
        'U' => 'color:#1eff00 !important;text-shadow:0 0 10px rgba(30,255,0,0.3);',
        'C' => 'color:#ffffff !important;',
        default => 'color:#8f96a3 !important;',
    };
}

function scmining_search_url(string $search = '', int $page = 1): string
{
    $params = [];

    if ($search !== '') {
        $params['search'] = $search;
    }

    if ($page > 1) {
        $params['search_page'] = $page;
    }

    return 'scmining.php' . ($params ? '?' . http_build_query($params) : '');
}

$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$search_page = max(1, (int)($_GET['search_page'] ?? 1));
$search_per_page = 10;
$search_results = [];
$search_total_results = 0;
$search_total_pages = 0;
$configured_matches = [];

if ($search !== '') {
    $stmt_configured = $db->prepare("SELECT o.* FROM tbl_scobjs o JOIN tbl_scmining m ON m.cl_scmining_obj_id = o.cl_scobjs_id WHERE o.cl_scobjs_name LIKE :search ORDER BY o.cl_scobjs_name ASC, o.cl_scobjs_id ASC");
    $stmt_configured->execute(['search' => "%$search%"]);
    $configured_matches = $stmt_configured->fetchAll();

    $search_where = "FROM tbl_scobjs o WHERE o.cl_scobjs_name LIKE :search AND o.cl_scobjs_id NOT IN (SELECT cl_scmining_obj_id FROM tbl_scmining)";

    $stmt_search_count = $db->prepare("SELECT COUNT(*) " . $search_where);
    $stmt_search_count->execute(['search' => "%$search%"]);
    $search_total_results = (int)$stmt_search_count->fetchColumn();
    $search_total_pages = max(1, (int)ceil($search_total_results / $search_per_page));
    $search_page = min($search_page, $search_total_pages);
    $search_offset = ($search_page - 1) * $search_per_page;

    $stmt_search = $db->prepare("SELECT o.* " . $search_where . " ORDER BY o.cl_scobjs_name ASC, o.cl_scobjs_id ASC LIMIT :limit OFFSET :offset");
    $stmt_search->bindValue(':search', "%$search%", PDO::PARAM_STR);
    $stmt_search->bindValue(':limit', $search_per_page, PDO::PARAM_INT);
    $stmt_search->bindValue(':offset', $search_offset, PDO::PARAM_INT);
    $stmt_search->execute();
    $search_results = $stmt_search->fetchAll();
}

// Fetch current mining list
$sql_list = "SELECT m.*, o.cl_scobjs_name, o.cl_scobjs_uuid, o.cl_scobjs_type, o.cl_scobjs_subtype, o.cl_scobjs_rarity
             FROM tbl_scmining m 
             JOIN tbl_scobjs o ON m.cl_scmining_obj_id = o.cl_scobjs_id 
             ORDER BY o.cl_scobjs_name ASC";
$stmt_list = $db->query($sql_list);
$mining_list = $stmt_list->fetchAll();

$current_session_user = $_SESSION['user'] ?? '';
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scanner Minage | 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;

            --rarity-L: #ff8000;
            --rarity-E: #a335ee;
            --rarity-R: #0070dd;
            --rarity-U: #1eff00;
            --rarity-C: #ffffff;
        }

        @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.active {
            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); }

        .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; }

        .item-preview {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 4px;
            border: 1px solid var(--border-glow);
            background: rgba(0,0,0,0.5);
        }

        .search-result-item {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 10px;
            background: rgba(255,255,255,0.05);
            margin-bottom: 10px;
            border-radius: 8px;
            border: 1px solid rgba(255,255,255,0.1);
        }

        .search-result-info { flex: 1; }
        .search-result-name { display: block; color: var(--primary); font-weight: bold; }
        .search-result-uuid { display: block; font-size: 0.75rem; color: #777; font-family: monospace; word-break: break-all; margin-top: 2px; }
        .search-result-meta { display: block; font-size: 0.75rem; color: #888; }
        .search-results-section { margin-bottom: 1.25rem; }
        .search-results-caption {
            margin: 0 0 0.75rem;
            font-size: 0.78rem;
            color: #9a9a9a;
            text-transform: uppercase;
            letter-spacing: 0.04em;
        }
        .search-result-item.is-configured {
            border-color: rgba(162, 155, 120, 0.35);
            background: rgba(162, 155, 120, 0.08);
        }
        .search-result-badge {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 0.35rem 0.65rem;
            border-radius: 999px;
            border: 1px solid rgba(162, 155, 120, 0.35);
            color: var(--primary);
            font-size: 0.72rem;
            text-transform: uppercase;
            letter-spacing: 0.04em;
            white-space: nowrap;
        }
        .search-results-summary {
            margin-bottom: 1rem;
            font-size: 0.8rem;
            color: #9a9a9a;
        }
        .pagination-controls {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            gap: 8px;
            margin-top: 1rem;
        }
        .pagination-controls .btn-modern {
            min-width: 42px;
        }
        .pagination-status {
            font-size: 0.8rem;
            color: #9a9a9a;
            margin-left: auto;
        }

        .rarity-L { color: var(--rarity-L) !important; text-shadow: 0 0 10px rgba(255, 128, 0, 0.3); }
        .rarity-E { color: var(--rarity-E) !important; text-shadow: 0 0 10px rgba(163, 53, 238, 0.3); }
        .rarity-R { color: var(--rarity-R) !important; text-shadow: 0 0 10px rgba(0, 112, 221, 0.3); }
        .rarity-U { color: var(--rarity-U) !important; text-shadow: 0 0 10px rgba(30, 255, 0, 0.3); }
        .rarity-C { color: var(--rarity-C) !important; }
        .rarity-none { color: #8f96a3 !important; }

        .val-input { width: 100px; text-align: center; }

        .recovery-options {
            display: flex;
            flex-direction: column;
            gap: 2px;
            font-size: 0.75rem;
            text-align: left;
        }
        .recovery-options label {
            display: flex;
            align-items: center;
            gap: 5px;
            cursor: pointer;
            color: #ccc;
        }
        .recovery-options label:hover { color: var(--primary); }
        .recovery-options input[type="checkbox"] {
            accent-color: var(--primary);
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="admin-layout">
        <header class="admin-topbar">
            <div class="topbar-info">
                <h1>R.E.A.C.T. Mining Scanner</h1>
                <p>Niveau d\'accès : <strong>Administrateur</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">
            <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" class="active">Scanner Minage</a>
            <a href="scmanufactures.php">Manufactures</a>
            <a href="scvaisseaux.php">Vaisseaux</a>
            <a href="scpreset.php">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: Search and Add -->
            <div class="side-panel">
                <section class="glass-card">
                    <h2>Ajouter un Minéral</h2>
                    <form method="get" action="scmining.php" style="display: flex; gap: 10px; margin-bottom: 1.5rem;">
                        <input type="text" name="search" class="form-control" placeholder="Rechercher (ex: Copper)" value="<?php echo htmlspecialchars($search); ?>">
                        <button type="submit" class="btn-modern">OK</button>
                    </form>

                    <?php if ($search !== ''): ?>
                        <div class="search-results">
                            <?php if (!empty($configured_matches)): ?>
                                <div class="search-results-section">
                                    <div class="search-results-caption">Déjà configuré<?php echo count($configured_matches) > 1 ? 's' : ''; ?> pour cette recherche</div>
                                    <?php foreach ($configured_matches as $configured):
                                        if (is_array($configured) && isset($configured['cl_scobjs_uuid']) && isset($configured['cl_scobjs_name']) && isset($configured['cl_scobjs_type']) && isset($configured['cl_scobjs_subtype'])) {
                                            $configured_rarity_code = $configured['cl_scobjs_rarity'] ?? '';
                                            $configured_rarity_class = sc_rarity_class($configured_rarity_code);
                                    ?>
                                        <div class="search-result-item is-configured">
                                            <img src="https://cstone.space/uifimages/<?php echo $configured['cl_scobjs_uuid']; ?>.png" class="item-preview" alt="">
                                            <div class="search-result-info">
                                                <span class="search-result-name <?php echo htmlspecialchars($configured_rarity_class); ?>" style="<?php echo htmlspecialchars(sc_rarity_style($configured_rarity_code)); ?>"><?php echo htmlspecialchars($configured['cl_scobjs_name']); ?></span>
                                                <span class="search-result-uuid">UUID: <?php echo htmlspecialchars($configured['cl_scobjs_uuid']); ?></span>
                                                <span class="search-result-meta"><?php echo htmlspecialchars($configured['cl_scobjs_type']); ?> / <?php echo htmlspecialchars($configured['cl_scobjs_subtype']); ?> — déjà présent dans Configuration Minerais</span>
                                            </div>
                                            <span class="search-result-badge">Déjà configuré</span>
                                        </div>
                                    <?php } endforeach; ?>
                                </div>
                            <?php endif; ?>

                            <?php if (empty($search_results)): ?>
                                <p style="text-align: center; color: #666;">Aucun objet non listé trouvé.</p>
                            <?php else: ?>
                                <?php $search_first_result = (($search_page - 1) * $search_per_page) + 1; ?>
                                <?php $search_last_result = min($search_total_results, $search_first_result + count($search_results) - 1); ?>
                                <div class="search-results-summary">
                                    Résultats <?php echo $search_first_result; ?> à <?php echo $search_last_result; ?> sur <?php echo $search_total_results; ?> — page <?php echo $search_page; ?>/<?php echo $search_total_pages; ?>
                                </div>
                                <?php foreach ($search_results as $res):
                                    if (is_array($res) && isset($res['cl_scobjs_uuid']) && isset($res['cl_scobjs_name']) && isset($res['cl_scobjs_type']) && isset($res['cl_scobjs_subtype']) && isset($res['cl_scobjs_id'])) {
                                        $rarity_code = $res['cl_scobjs_rarity'] ?? '';
                                        $rarity_class = sc_rarity_class($rarity_code);
                                    ?>
                                    <div class="search-result-item">
                                        <img src="https://cstone.space/uifimages/<?php echo $res['cl_scobjs_uuid']; ?>.png" class="item-preview" alt="">
                                        <div class="search-result-info">
                                            <span class="search-result-name <?php echo htmlspecialchars($rarity_class); ?>" style="<?php echo htmlspecialchars(sc_rarity_style($rarity_code)); ?>"><?php echo htmlspecialchars($res['cl_scobjs_name']); ?></span>
                                            <span class="search-result-uuid">UUID: <?php echo htmlspecialchars($res['cl_scobjs_uuid']); ?></span>
                                            <span class="search-result-meta"><?php echo htmlspecialchars($res['cl_scobjs_type']); ?> / <?php echo htmlspecialchars($res['cl_scobjs_subtype']); ?></span>
                                        </div>
                                        <form method="post">
                                            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                            <input type="hidden" name="action" value="add_mineral">
                                            <input type="hidden" name="obj_id" value="<?php echo $res['cl_scobjs_id']; ?>">
                                            <input type="hidden" name="return_search" value="<?php echo htmlspecialchars($search); ?>">
                                            <input type="hidden" name="return_page" value="<?php echo $search_page; ?>">
                                            <button type="submit" class="btn-modern btn-mini">+</button>
                                        </form>
                                    </div>
                                <?php } endforeach; ?>

                                <?php if ($search_total_pages > 1): ?>
                                    <?php
                                        $page_window_start = max(1, $search_page - 2);
                                        $page_window_end = min($search_total_pages, $search_page + 2);
                                    ?>
                                    <div class="pagination-controls">
                                        <?php if ($search_page > 1): ?>
                                            <a href="<?php echo htmlspecialchars(scmining_search_url($search, $search_page - 1)); ?>" class="btn-modern btn-mini">&laquo;</a>
                                        <?php endif; ?>

                                        <?php for ($page_number = $page_window_start; $page_number <= $page_window_end; $page_number++): ?>
                                            <a href="<?php echo htmlspecialchars(scmining_search_url($search, $page_number)); ?>" class="btn-modern btn-mini<?php echo $page_number === $search_page ? ' active' : ''; ?>"><?php echo $page_number; ?></a>
                                        <?php endfor; ?>

                                        <?php if ($search_page < $search_total_pages): ?>
                                            <a href="<?php echo htmlspecialchars(scmining_search_url($search, $search_page + 1)); ?>" class="btn-modern btn-mini">&raquo;</a>
                                        <?php endif; ?>

                                        <span class="pagination-status">Navigation des homonymes activée</span>
                                    </div>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </section>
            </div>

            <!-- Right Column: List -->
            <main class="main-panel">
                <section class="glass-card">
                    <h2>Configuration Minerais</h2>
                    <div style="overflow-x: auto;">
                        <table class="modern-table">
                            <thead>
                                <tr>
                                    <th style="width: 60px;">Aperçu</th>
                                    <th>Nom / Type</th>
                                    <th style="text-align: center;">Récupération</th>
                                    <th style="text-align: center;">Valeur Scan</th>
                                    <th style="text-align: center;">Max Occur.</th>
                                    <th style="text-align: right;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($mining_list)): ?>
                                    <tr><td colspan="6" style="text-align: center; padding: 3rem; color: #666;">Aucun minéral configuré.</td></tr>
                                <?php else: ?>
                                    <?php foreach ($mining_list as $item):
                                        if (is_array($item) && isset($item['cl_scobjs_uuid']) && isset($item['cl_scobjs_name']) && isset($item['cl_scobjs_type']) && isset($item['cl_scobjs_subtype']) && isset($item['cl_scmining_id']) && isset($item['cl_scmining_scan_value']) && isset($item['cl_scmining_max_occurrence'])) {
                                            $rarity_code = $item['cl_scobjs_rarity'] ?? '';
                                            $rarity_class = sc_rarity_class($rarity_code);
                                        ?>
                                    <tr>
                                        <td>
                                            <img src="https://cstone.space/uifimages/<?php echo $item['cl_scobjs_uuid']; ?>.png" class="item-preview" alt="">
                                        </td>
                                        <td>
                                            <strong class="<?php echo htmlspecialchars($rarity_class); ?>" style="<?php echo htmlspecialchars(sc_rarity_style($rarity_code)); ?>"><?php echo htmlspecialchars($item['cl_scobjs_name']); ?></strong><br>
                                            <span style="font-size: 0.75rem; color: #888;"><?php echo htmlspecialchars($item['cl_scobjs_type']); ?> / <?php echo htmlspecialchars($item['cl_scobjs_subtype']); ?></span>
                                        </td>
                                        <form method="post">
                                            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                            <input type="hidden" name="action" value="update_mineral">
                                            <input type="hidden" name="mining_id" value="<?php echo $item['cl_scmining_id']; ?>">
                                            <td style="text-align: center;">
                                                <div class="recovery-options">
                                                    <label><input type="checkbox" name="can_manual" <?php echo ($item['cl_scmining_can_manual'] ?? 0) ? 'checked' : ''; ?>> Manuel</label>
                                                    <label><input type="checkbox" name="can_land" <?php echo ($item['cl_scmining_can_land'] ?? 0) ? 'checked' : ''; ?>> Terrestre</label>
                                                    <label><input type="checkbox" name="can_space" <?php echo ($item['cl_scmining_can_space'] ?? 0) ? 'checked' : ''; ?>> Spatial</label>
                                                </div>
                                            </td>
                                            <td style="text-align: center;">
                                                <input type="number" name="scan_value" class="form-control val-input" required value="<?php echo $item['cl_scmining_scan_value']; ?>">
                                            </td>
                                            <td style="text-align: center;">
                                                <input type="number" name="max_occurrence" class="form-control val-input" required value="<?php echo $item['cl_scmining_max_occurrence']; ?>" min="1" max="10">
                                            </td>
                                            <td style="text-align: right;">
                                                <div style="display: flex; gap: 5px; justify-content: flex-end;">
                                                    <button type="submit" class="btn-modern btn-mini">Save</button>
                                        </form>
                                                    <form method="post" onsubmit="return confirm('Retirer ce minéral ?');">
                                                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                                        <input type="hidden" name="action" value="delete_mineral">
                                                        <input type="hidden" name="mining_id" value="<?php echo $item['cl_scmining_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>
</body>
</html>
