<?php

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

auth_start_session();
auth_bootstrap();
auth_handle_page_access_post('scvaisseaux.php', 'Vaisseaux');
auth_require_page_access('scvaisseaux.php', 'Vaisseaux');

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

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

    // Add ship
    if ($action === 'add_ship') {
        $name = trim($_POST['name'] ?? '');
        $manufacture_id = (int)($_POST['manufacture_id'] ?? 0);
        if ($name !== '' && $manufacture_id > 0) {
            try {
                $stmt = $db->prepare("INSERT INTO tbl_scvaisseaux (cl_scvaisseaux_name, cl_scvaisseaux_manufacture_id) VALUES (:name, :manufacture_id)");
                $stmt->execute(['name' => $name, 'manufacture_id' => $manufacture_id]);
                auth_flash_set('success', 'Vaisseau ajouté avec succès.');
            } catch (PDOException $e) {
                auth_flash_set('error', 'Erreur lors de l\'ajout : ' . $e->getMessage());
            }
        } else {
            auth_flash_set('error', 'Veuillez remplir tous les champs obligatoires.');
        }
        header('Location: scvaisseaux.php');
        exit;
    }

    // Update ship
    if ($action === 'update_ship') {
        $id = (int)($_POST['ship_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $manufacture_id = (int)($_POST['manufacture_id'] ?? 0);
        if ($id > 0 && $name !== '' && $manufacture_id > 0) {
            try {
                $stmt = $db->prepare("UPDATE tbl_scvaisseaux SET cl_scvaisseaux_name = :name, cl_scvaisseaux_manufacture_id = :manufacture_id WHERE cl_scvaisseaux_id = :id");
                $stmt->execute(['name' => $name, 'manufacture_id' => $manufacture_id, 'id' => $id]);
                auth_flash_set('success', 'Vaisseau 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.');
        }
        header('Location: scvaisseaux.php');
        exit;
    }

    // Delete ship
    if ($action === 'delete_ship') {
        $id = (int)($_POST['ship_id'] ?? 0);
        if ($id > 0) {
            $stmt = $db->prepare("DELETE FROM tbl_scvaisseaux WHERE cl_scvaisseaux_id = :id");
            $stmt->execute(['id' => $id]);
            auth_flash_set('success', 'Vaisseau supprimé.');
        }
        header('Location: scvaisseaux.php');
        exit;
    }
}

// Fetch all manufactures for the dropdown
$stmt_mans = $db->query("SELECT * FROM tbl_scmanufactures ORDER BY cl_scmanufactures_name ASC");
$manufactures = $stmt_mans->fetchAll();

// Fetch all ships with manufacture names
$stmt_list = $db->query("SELECT v.*, m.cl_scmanufactures_name 
                        FROM tbl_scvaisseaux v 
                        JOIN tbl_scmanufactures m ON v.cl_scvaisseaux_manufacture_id = m.cl_scmanufactures_id 
                        ORDER BY m.cl_scmanufactures_name ASC, v.cl_scvaisseaux_name ASC");
$ships = $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>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;
        }

        .topbar-actions {
            display: flex;
            gap: 1rem;
            flex-wrap: wrap;
            align-items: center;
        }

        .session-user {
            opacity: 0.85;
        }

        .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); }
        select.form-control { background: #353b45; color: #fff; border-color: #565d68; color-scheme: dark; }
        select.form-control:focus { background: #3d444f; color: #fff; }
        select.form-control option { background: #353b45; color: #fff; }
        select.form-control option:checked { background: #4a5260; color: #fff; }

        .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;
        }
        .ship-filter-status {
            margin: 0 0 1rem;
            font-size: 0.9rem;
            color: #b8bdc7;
        }
        .ship-filter-status strong {
            color: #fff;
        }
        .ship-filter-empty {
            display: none;
            text-align: center;
            padding: 1rem;
            color: #8d94a0;
            font-size: 0.95rem;
        }
    </style>
</head>
<body>
    <?php echo auth_render_page_access_widget('scvaisseaux.php', 'Vaisseaux'); ?>
    <div class="admin-layout">
        <header class="admin-topbar">
            <div class="topbar-info">
                <h1>Gestion Vaisseaux</h1>
                <p>Niveau d\'accès : <strong>Administrateur</strong></p>
            </div>
            <div class="topbar-actions">
                <span class="session-user">Connecté : <strong><?php echo htmlspecialchars($current_session_user); ?></strong></span>
                <a href="index.php" class="btn-modern">Retour au site</a>
                <a href="logout.php" class="btn-modern danger">Déconnexion</a>
            </div>
        </header>

        <?php echo auth_render_app_nav('scvaisseaux.php'); ?>

        <?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 -->
            <div class="side-panel">
                <section class="glass-card">
                    <h2 id="formTitle">Nouveau Vaisseau</h2>
                    <?php if (empty($manufactures)): ?>
                        <p style="color: var(--danger); font-size: 0.9rem;">Veuillez d\'abord ajouter au moins une manufacture.</p>
                        <a href="scmanufactures.php" class="btn-modern" style="width: 100%;">Aller aux Manufactures</a>
                    <?php else: ?>
                    <form id="shipForm" method="post">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                        <input type="hidden" name="action" id="formAction" value="add_ship">
                        <input type="hidden" name="ship_id" id="shipId" value="">
                        
                        <div class="form-group">
                            <label>Manufacture</label>
                            <select name="manufacture_id" id="shipManufacture" class="form-control" required>
                                <option value="">- Sélectionner -</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>Nom du Vaisseau</label>
                            <input type="text" name="name" id="shipName" class="form-control" required placeholder="ex: Carrack">
                        </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 Vaisseaux</h2>
                    <p id="shipFilterStatus" class="ship-filter-status">Affichage : <strong>tous les vaisseaux</strong></p>
                    <div style="overflow-x: auto;">
                        <table class="modern-table">
                            <thead>
                                <tr>
                                    <th>Manufacture / Modèle</th>
                                    <th style="text-align: right;">Actions</th>
                                </tr>
                            </thead>
                            <tbody id="shipTableBody">
                                <?php if (empty($ships)): ?>
                                    <tr><td colspan="2" style="text-align: center; padding: 3rem; color: #666;">Aucun vaisseau enregistré.</td></tr>
                                <?php else: ?>
                                    <?php foreach ($ships as $s): ?>
                                    <tr class="ship-row" data-manufacture-id="<?php echo (int)$s['cl_scvaisseaux_manufacture_id']; ?>" data-manufacture-name="<?php echo htmlspecialchars($s['cl_scmanufactures_name'], ENT_QUOTES); ?>">
                                        <td>
                                            <span class="manufacturer-text"><?php echo htmlspecialchars($s['cl_scmanufactures_name']); ?></span>
                                            <strong style="color: var(--primary); text-transform: uppercase; font-size: 1.1rem;"><?php echo htmlspecialchars($s['cl_scvaisseaux_name']); ?></strong>
                                        </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='editShip(<?php echo json_encode([
                                                        "id" => $s["cl_scvaisseaux_id"],
                                                        "name" => $s["cl_scvaisseaux_name"],
                                                        "manufacture_id" => $s["cl_scvaisseaux_manufacture_id"]
                                                    ]); ?>)'>
                                                    Edit
                                                </button>
                                                <form method="post" onsubmit="return confirm('Supprimer ce vaisseau ?');">
                                                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                                    <input type="hidden" name="action" value="delete_ship">
                                                    <input type="hidden" name="ship_id" value="<?php echo $s['cl_scvaisseaux_id']; ?>">
                                                    <button type="submit" class="btn-modern btn-mini danger">X</button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                        <?php if (!empty($ships)): ?>
                            <p id="shipFilterEmpty" class="ship-filter-empty">Aucun vaisseau trouvé pour cette manufacture.</p>
                        <?php endif; ?>
                    </div>
                </section>
            </main>
        </div>
    </div>

    <script>
        function applyShipManufactureFilter() {
            const manufactureSelect = document.getElementById('shipManufacture');
            const status = document.getElementById('shipFilterStatus');
            const emptyMessage = document.getElementById('shipFilterEmpty');
            const rows = document.querySelectorAll('#shipTableBody .ship-row');

            if (!manufactureSelect || !status || !rows.length) {
                return;
            }

            const selectedManufactureId = manufactureSelect.value;
            const selectedOption = manufactureSelect.options[manufactureSelect.selectedIndex];
            const selectedManufactureName = selectedManufactureId && selectedOption
                ? selectedOption.text.trim()
                : '';

            let visibleCount = 0;

            rows.forEach((row) => {
                const matches = !selectedManufactureId || row.dataset.manufactureId === selectedManufactureId;
                row.style.display = matches ? '' : 'none';
                if (matches) {
                    visibleCount += 1;
                }
            });

            if (selectedManufactureId && selectedManufactureName) {
                const label = visibleCount > 1 ? 'vaisseaux' : 'vaisseau';
                status.innerHTML = `Affichage : <strong>${visibleCount} ${label} pour ${selectedManufactureName}</strong>`;
            } else {
                const label = rows.length > 1 ? 'vaisseaux' : 'vaisseau';
                status.innerHTML = `Affichage : <strong>tous les ${rows.length} ${label}</strong>`;
            }

            if (emptyMessage) {
                emptyMessage.style.display = visibleCount === 0 ? 'block' : 'none';
            }
        }

        function editShip(data) {
            document.getElementById('formAction').value = 'update_ship';
            document.getElementById('shipId').value = data.id;
            document.getElementById('shipName').value = data.name;
            document.getElementById('shipManufacture').value = data.manufacture_id;
            applyShipManufactureFilter();
            
            document.getElementById('submitBtn').innerText = 'Mettre à jour';
            document.getElementById('cancelBtn').style.display = 'block';
            document.getElementById('formTitle').innerText = 'Modifier Vaisseau';
            
            document.getElementById('shipForm').scrollIntoView({ behavior: 'smooth' });
        }

        function resetForm() {
            document.getElementById('formAction').value = 'add_ship';
            document.getElementById('shipId').value = '';
            document.getElementById('shipForm').reset();
            applyShipManufactureFilter();
            
            document.getElementById('submitBtn').innerText = 'Ajouter';
            document.getElementById('cancelBtn').style.display = 'none';
            document.getElementById('formTitle').innerText = 'Nouveau Vaisseau';
        }

        document.addEventListener('DOMContentLoaded', function () {
            const manufactureSelect = document.getElementById('shipManufacture');
            if (!manufactureSelect) {
                return;
            }

            manufactureSelect.addEventListener('change', applyShipManufactureFilter);
            applyShipManufactureFilter();
        });
    </script>
</body>
</html>
