<?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();

// Pagination
$limit = 20;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

// Search
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$where = "1=1";
$params = [];
if ($search !== '') {
    $where = "(cl_scobjs_name LIKE :search OR cl_scobjs_type LIKE :search OR cl_scobjs_subtype LIKE :search OR cl_scobjs_uuid LIKE :search)";
    $params['search'] = "%$search%";
}

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

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

    if ($action === 'import_json') {
        if (!isset($_FILES['json_file']) || $_FILES['json_file']['error'] !== UPLOAD_ERR_OK) {
            auth_flash_set('error', 'Erreur lors du téléchargement du fichier JSON.');
        } else {
            $jsonData = file_get_contents($_FILES['json_file']['tmp_name']);
            $items = json_decode($jsonData, true);

            if (!is_array($items)) {
                auth_flash_set('error', 'Format JSON invalide (doit être un tableau).');
            } else {
                $count_new = 0;
                $count_updated = 0;

                $stmt_check = $db->prepare("SELECT cl_scobjs_id FROM tbl_scobjs WHERE cl_scobjs_uuid = :uuid");
                $stmt_insert = $db->prepare("INSERT INTO tbl_scobjs (cl_scobjs_name, cl_scobjs_type, cl_scobjs_subtype, cl_scobjs_uuid, cl_scobjs_rarity, cl_scobjs_about) VALUES (:name, :type, :subtype, :uuid, '', '')");
                $stmt_update = $db->prepare("UPDATE tbl_scobjs SET cl_scobjs_name = :name, cl_scobjs_type = :type, cl_scobjs_subtype = :subtype WHERE cl_scobjs_uuid = :uuid");

                foreach ($items as $item) {
                    $uuid = $item['reference'] ?? ($item['stdItem']['UUID'] ?? '');
                    if (!$uuid) continue;

                    $name = $item['Name'] ?? ($item['stdItem']['Name'] ?? '');
                    $classification = $item['classification'] ?? ''; $parts = explode('.', $classification); $type = $parts[1] ?? ($item['type'] ?? '');
                    $subtype = $parts[2] ?? ($item['subType'] ?? '');

                    $stmt_check->execute(['uuid' => $uuid]);
                    if ($stmt_check->fetch()) {
                        $stmt_update->execute([
                            'name' => $name,
                            'type' => $type,
                            'subtype' => $subtype,
                            'uuid' => $uuid
                        ]);
                        $count_updated++;
                    } else {
                        $stmt_insert->execute([
                            'name' => $name,
                            'type' => $type,
                            'subtype' => $subtype,
                            'uuid' => $uuid
                        ]);
                        $count_new++;
                    }
                }
                auth_flash_set('success', "Importation terminée : $count_new nouveaux, $count_updated mis à jour.");
            }
        }
        header('Location: scitems.php');
        exit;
    }

    if ($action === 'update_item') {
        $id = (int)$_POST['id'];
        $rarity = trim($_POST['rarity'] ?? '');
        $about = trim($_POST['about'] ?? '');

        $stmt = $db->prepare("UPDATE tbl_scobjs SET cl_scobjs_rarity = :rarity, cl_scobjs_about = :about WHERE cl_scobjs_id = :id");
        $stmt->execute(['rarity' => $rarity, 'about' => $about, 'id' => $id]);

        auth_flash_set('success', "Objet mis à jour avec succès.");
        header('Location: scitems.php?page=' . $page . '&search=' . urlencode($search));
        exit;
    }
}

// Fetch items
$sql_count = "SELECT COUNT(*) FROM tbl_scobjs WHERE $where";
$stmt_count = $db->prepare($sql_count);
$stmt_count->execute($params);
$total_items = (int)$stmt_count->fetchColumn();
$total_pages = ceil($total_items / $limit);

$sql_items = "SELECT * FROM tbl_scobjs WHERE $where ORDER BY cl_scobjs_name ASC LIMIT $limit OFFSET $offset";
$stmt_items = $db->prepare($sql_items);
$stmt_items->execute($params);
$items_list = $stmt_items->fetchAll();

$current_session_user = $_SESSION['user'] ?? '';
$edit_id = isset($_GET['edit']) ? (int)$_GET['edit'] : 0;
$edit_item = null;
if ($edit_id > 0) {
    $stmt_edit = $db->prepare("SELECT * FROM tbl_scobjs WHERE cl_scobjs_id = :id");
    $stmt_edit->execute(['id' => $edit_id]);
    $edit_item = $stmt_edit->fetch();
}

?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestion des Objets | 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 Colors */
            --rarity-L: #ff8000; /* Legendary - Orange */
            --rarity-E: #a335ee; /* Epic - Purple */
            --rarity-R: #0070dd; /* Rare - Blue */
            --rarity-U: #1eff00; /* Uncommon - Green */
            --rarity-C: #ffffff; /* Common - White */
        }

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

        .topbar-actions {
            display: flex;
            gap: 1rem;
        }

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

        .admin-grid {
            display: grid;
            grid-template-columns: 1fr 3fr;
            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;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .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); vertical-align: top; }
        .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; }

        .pagination { display: flex; gap: 0.5rem; margin-top: 2rem; justify-content: center; }
        .page-link {
            padding: 0.5rem 1rem;
            border: 1px solid var(--border-glow);
            background: var(--card-bg);
            color: #fff;
            text-decoration: none;
            border-radius: 4px;
            transition: all 0.2s;
        }
        .page-link:hover, .page-link.active { background: var(--primary); color: var(--bg-dark); }

        .search-container { margin-bottom: 1.5rem; display: flex; gap: 10px; }
        .search-container input { flex: 1; }

        .badge { padding: 0.2rem 0.5rem; border-radius: 4px; font-size: 0.7rem; text-transform: uppercase; background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.2); }
        
        .item-name { color: var(--primary); font-weight: bold; display: block; font-size: 1rem; margin-bottom: 4px; }
        .item-meta { font-size: 0.75rem; color: #888; display: block; }
        .item-uuid { font-size: 0.75rem; color: #777; font-family: monospace; word-break: break-all; display: block; margin-bottom: 4px; }
        .item-about-cell { font-size: 0.85rem; color: #ccc; line-height: 1.4; }

        /* Preview System */
        .preview-container {
            position: relative;
            width: 80px;
            height: 80px;
            cursor: zoom-in;
        }

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

        .preview-floating {
            visibility: hidden;
            opacity: 0;
            position: absolute;
            top: -10px;
            left: 95px;
            z-index: 1000;
            padding: 5px;
            background: var(--card-bg);
            border: 1px solid var(--primary);
            border-radius: 8px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.9), 0 0 20px var(--primary-glow);
            backdrop-filter: blur(15px);
            transition: opacity 0.3s ease, visibility 0.3s;
            pointer-events: none;
        }

        .preview-floating img {
            width: 350px;
            height: 350px;
            object-fit: contain;
            display: block;
            border-radius: 4px;
        }

        .preview-container:hover .preview-floating {
            visibility: visible;
            opacity: 1;
        }

        /* Rarity Classes */
        .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; }

        .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); }
    </style>
</head>
<body>
    <div class="admin-layout">
        <header class="admin-topbar">
            <div class="topbar-info">
                <h1>R.E.A.C.T. Objects Control</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" class="active">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>
            <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">
            <div class="side-panel">
                <section class="glass-card" style="margin-bottom: 2rem;">
                    <h2>Importation JSON</h2>
                    <form method="post" enctype="multipart/form-data">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                        <input type="hidden" name="action" value="import_json">
                        <div class="form-group">
                            <label for="json_file">Fichier JSON</label>
                            <input type="file" name="json_file" id="json_file" class="form-control" accept=".json" required>
                        </div>
                        <button type="submit" class="btn-modern" style="width: 100%;">Importer / Mettre à jour</button>
                    </form>
                </section>

                <?php if ($edit_item): ?>
                <section class="glass-card">
                    <h2>Editer Objet</h2>
                    <form method="post">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                        <input type="hidden" name="action" value="update_item">
                        <input type="hidden" name="id" value="<?php echo $edit_item['cl_scobjs_id']; ?>">
                        
                        <div class="form-group">
                            <label>Nom</label>
                            <div class="form-control" style="background: rgba(255,255,255,0.05); border-color: transparent;">
                                <?php echo htmlspecialchars($edit_item['cl_scobjs_name']); ?>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="rarity">Rareté</label>
                            <select name="rarity" id="rarity" class="form-control">
                                <option value="" <?php echo $edit_item['cl_scobjs_rarity'] === '' ? 'selected' : ''; ?>>- Sélectionner -</option>
                                <option value="L" <?php echo $edit_item['cl_scobjs_rarity'] === 'L' ? 'selected' : ''; ?>>Legendary (L)</option>
                                <option value="E" <?php echo $edit_item['cl_scobjs_rarity'] === 'E' ? 'selected' : ''; ?>>Epic (E)</option>
                                <option value="R" <?php echo $edit_item['cl_scobjs_rarity'] === 'R' ? 'selected' : ''; ?>>Rare (R)</option>
                                <option value="U" <?php echo $edit_item['cl_scobjs_rarity'] === 'U' ? 'selected' : ''; ?>>Uncommon (U)</option>
                                <option value="C" <?php echo $edit_item['cl_scobjs_rarity'] === 'C' ? 'selected' : ''; ?>>Common (C)</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="about">Zone Admin / Infos</label>
                            <textarea name="about" id="about" class="form-control" rows="5" placeholder="Saisir les informations ici..."><?php echo htmlspecialchars($edit_item['cl_scobjs_about']); ?></textarea>
                        </div>

                        <div style="display: flex; gap: 10px;">
                            <button type="submit" class="btn-modern" style="flex: 2;">Sauvegarder</button>
                            <a href="scitems.php?page=<?php echo $page; ?>&search=<?php echo urlencode($search); ?>" class="btn-modern danger" style="flex: 1;">X</a>
                        </div>
                    </form>
                </section>
                <?php endif; ?>
            </div>

            <main class="main-panel">
                <section class="glass-card">
                    <h2>
                        Base de Données d'Objets
                        <span style="font-size: 0.8rem; opacity: 0.6;"><?php echo $total_items; ?> entrées</span>
                    </h2>

                    <div class="search-container">
                        <form method="get" style="display: flex; width: 100%; gap: 10px;">
                            <input type="text" name="search" class="form-control" placeholder="Rechercher par nom, type, uuid..." value="<?php echo htmlspecialchars($search); ?>">
                            <button type="submit" class="btn-modern">Filtrer</button>
                            <?php if ($search !== ''): ?>
            <a href="scitems.php" class="btn-modern danger">Reset</a>
                            <?php endif; ?>
                        </form>
                    </div>

                    <div style="overflow-x: auto;">
                        <table class="modern-table">
                            <thead>
                                <tr>
                                    <th style="width: 80px;">Aperçu</th>
                                    <th style="width: 35%;">Nom / UUID / Type</th>
                                    <th>About</th>
                                    <th style="text-align: right; width: 100px;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($items_list)): ?>
                                    <tr><td colspan="4" style="text-align: center; padding: 3rem; color: #666;">Aucun objet trouvé.</td></tr>
                                <?php else: ?>
                                    <?php foreach ($items_list as $item): ?>
                                    <?php 
                                        $rarityClass = '';
                                        if ($item['cl_scobjs_rarity']) {
                                            $rarityClass = 'rarity-' . $item['cl_scobjs_rarity'];
                                        }
                                        $imageUrl = "https://cstone.space/uifimages/" . $item['cl_scobjs_uuid'] . ".png";
                                    ?>
                                    <tr>
                                        <td>
                                            <div class="preview-container">
                                                <img src="<?php echo $imageUrl; ?>" class="item-preview" alt="" loading="lazy">
                                                <div class="preview-floating">
                                                    <img src="<?php echo $imageUrl; ?>" alt="">
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="item-name <?php echo $rarityClass; ?>"><?php echo htmlspecialchars($item['cl_scobjs_name']); ?></span>
                                            <span class="item-uuid"><?php echo htmlspecialchars($item['cl_scobjs_uuid']); ?></span>
                                            <span class="item-meta">
                                                <?php echo htmlspecialchars($item['cl_scobjs_type']); ?> 
                                                <?php if($item['cl_scobjs_subtype']) echo " / " . htmlspecialchars($item['cl_scobjs_subtype']); ?>
                                            </span>
                                        </td>
                                        <td class="item-about-cell">
                                            <?php echo nl2br(htmlspecialchars($item['cl_scobjs_about'])); ?>
                                        </td>
                                        <td style="text-align: right;">
                                            <a href="scitems.php?edit=<?php echo $item['cl_scobjs_id']; ?>&page=<?php echo $page; ?>&search=<?php echo urlencode($search); ?>" class="btn-modern btn-mini">Editer</a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <?php if ($total_pages > 1): ?>
                    <div class="pagination">
                        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                            <?php if ($i == 1 || $i == $total_pages || ($i >= $page - 2 && $i <= $page + 2)): ?>
                                <a href="scitems.php?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>" class="page-link <?php echo $i == $page ? 'active' : ''; ?>">
                                    <?php echo $i; ?>
                                </a>
                            <?php elseif ($i == $page - 3 || $i == $page + 3): ?>
                                <span style="padding: 0.5rem;">...</span>
                            <?php endif; ?>
                        <?php endfor; ?>
                    </div>
                    <?php endif; ?>
                </section>
            </main>
        </div>
    </div>
</body>
</html>