<?php
include('inc/check_login.php');
require_once 'inc/db.php';

$is_admin = ($_SESSION['role'] === 'admin');

$message = '';
$message_type = '';
$edit_mode = false;
$edit_color = null;

// --- Nur Admins: Löschen ---
if ($is_admin && isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $stmt = mysqli_prepare($conn, "DELETE FROM colors WHERE id = ?");
    mysqli_stmt_bind_param($stmt, "i", $id);
    if (mysqli_stmt_execute($stmt)) {
        $message = "Farbe erfolgreich gelöscht!";
        $message_type = 'success';
    } else {
        $message = "Fehler beim Löschen der Farbe.";
        $message_type = 'danger';
    }
    mysqli_stmt_close($stmt);
    header("Location: colors.php");
    exit();
}

// --- Nur Admins: Bearbeiten ---
if ($is_admin && isset($_GET['action']) && $_GET['action'] == 'edit' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $stmt = mysqli_prepare($conn, "SELECT id, name, hex_code, is_special FROM colors WHERE id = ?");
    mysqli_stmt_bind_param($stmt, "i", $id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $edit_color = mysqli_fetch_assoc($result);
    mysqli_stmt_close($stmt);
    if ($edit_color) {
        $edit_mode = true;
    } else {
        $message = "Farbe nicht gefunden.";
        $message_type = 'warning';
    }
}

// --- Nur Admins: Speichern ---
if ($is_admin && $_SERVER["REQUEST_METHOD"] == "POST") {
    $name = trim($_POST['name'] ?? '');
    $hex_code = trim($_POST['hex_code'] ?? '');
    $is_special = !empty($_POST['is_special']) ? 1 : 0;
    $id = !empty($_POST['id']) ? (int)$_POST['id'] : null;

    if (empty($name) || empty($hex_code)) {
        $message = "Name und Farbcode sind erforderlich.";
        $message_type = 'danger';
    } else {
        if ($id) {
            $stmt = mysqli_prepare($conn, "UPDATE colors SET name = ?, hex_code = ?, is_special = ? WHERE id = ?");
            mysqli_stmt_bind_param($stmt, "ssii", $name, $hex_code, $is_special, $id);
        } else {
            $stmt = mysqli_prepare($conn, "INSERT INTO colors (name, hex_code, is_special) VALUES (?, ?, ?)");
            mysqli_stmt_bind_param($stmt, "ssi", $name, $hex_code, $is_special);
        }

        if (mysqli_stmt_execute($stmt)) {
            $message = $id ? "Farbe erfolgreich aktualisiert!" : "Neue Farbe erfolgreich hinzugefügt!";
            $message_type = 'success';
        } else {
            $message = "Fehler beim Speichern der Farbe.";
            $message_type = 'danger';
        }
        mysqli_stmt_close($stmt);
        header("Location: colors.php");
        exit();
    }
}

// --- Sortierung mit Richtung (asc/desc) ---
$sort = $_GET['sort'] ?? 'name';
$dir  = $_GET['dir']  ?? 'asc';
$sort = in_array($sort, ['name', 'usage']) ? $sort : 'name';
$dir  = in_array($dir,  ['asc', 'desc'])   ? $dir  : 'asc';

if ($sort === 'usage') {
    $order_by = "usage_count $dir, c.name ASC";
} else {
    $order_by = "c.name $dir";
}

// --- Farben mit Nutzungszähler laden ---
$colors = [];
$result = mysqli_query($conn, "
    SELECT 
        c.id, 
        c.name, 
        c.hex_code, 
        c.is_special,
        COUNT(m.id) AS usage_count
    FROM colors c
    LEFT JOIN meetings m ON c.id = m.color_id AND m.is_skipped = 0
    GROUP BY c.id, c.name, c.hex_code, c.is_special
    ORDER BY $order_by
");
while ($row = mysqli_fetch_assoc($result)) {
    $colors[] = $row;
}

require_once 'inc/header.php';
?>

<div class="container mt-5">

    <?php if ($message): ?>
        <div class="alert alert-<?= htmlspecialchars($message_type) ?> alert-dismissible fade show" role="alert">
            <?= htmlspecialchars($message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="mb-0">Farbverwaltung</h2>
    </div>

    <?php if ($is_admin): ?>
        <div class="collapse <?= $edit_mode ? 'show' : '' ?>" id="colorFormCollapse">
            <div class="card shadow mb-4">
                <div class="card-header bg-primary-subtle text-secondary">
                    <h4 class="mb-0"><?= $edit_mode ? 'Farbe bearbeiten' : 'Neue Farbe hinzufügen'; ?></h4>
                </div>
                <div class="card-body">
                    <form action="colors.php" method="post">
                        <?php if ($edit_mode): ?>
                            <input type="hidden" name="id" value="<?= htmlspecialchars($edit_color['id']); ?>">
                        <?php endif; ?>
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="name" class="form-label">Name der Farbe</label>
                                <input type="text" class="form-control" id="name" name="name"
                                    value="<?= htmlspecialchars($edit_color['name'] ?? ''); ?>" required>
                            </div>
                            <div class="col-md-6">
                                <label for="hex_code" class="form-label">Hex-Code</label>
                                <input type="color" class="form-control form-control-color" id="hex_code" name="hex_code"
                                    value="<?= htmlspecialchars($edit_color['hex_code'] ?? '#000000'); ?>">
                            </div>
                            <div class="col-12">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="is_special" name="is_special" <?= (!empty($edit_color['is_special']) ? 'checked' : ''); ?>>
                                    <label class="form-check-label" for="is_special">
                                        Sonderfarbe (wird nicht im Zufallsmodus verwendet)
                                    </label>
                                </div>
                            </div>
                            <div class="col-12 d-flex justify-content-start mt-2">
                                <button type="submit" class="btn btn-sm btn-outline-<?= $edit_mode ? 'success' : 'primary'; ?> me-2">
                                    <?= $edit_mode ? 'Speichern' : 'Hinzufügen'; ?>
                                </button>
                                <a href="colors.php" class="btn btn-sm btn-outline-secondary">Abbrechen</a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <div class="card shadow">
        <div class="card-header bg-primary-subtle text-secondary d-flex justify-content-between align-items-center">
            <h4 class="mb-0">Aktuelle Farben</h4>
            <?php if ($is_admin): ?>
                <a class="btn btn-sm d-flex align-items-center justify-content-center" data-bs-toggle="collapse" href="#colorFormCollapse" role="button" aria-expanded="false" aria-controls="colorFormCollapse">Add
                    <span class="material-symbols-outlined">add</span>
                </a>
            <?php endif; ?>
        </div>
        <div class="card-body">
            <?php if (empty($colors)): ?>
                <p class="text-muted text-center">Es sind noch keine Farben vorhanden.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>Farbe</th>
                                <th>
                                    <?php
                                    $name_dir = ($sort === 'name' && $dir === 'asc') ? 'desc' : 'asc';
                                    $name_arrow = '';
                                    if ($sort === 'name') {
                                        $name_arrow = $dir === 'asc' ? 'arrow_upward' : 'arrow_downward';
                                    }
                                    ?>
                                    <a href="?sort=name&dir=<?= $name_dir ?>" class="link-secondary text-decoration-none">
                                        Name <?php if ($name_arrow): ?><span class="material-symbols-outlined" style="font-size:1em;"><?= $name_arrow ?></span><?php endif; ?>
                                    </a>
                                </th>
                                <th>
                                    <?php
                                    $usage_dir = ($sort === 'usage' && $dir === 'asc') ? 'desc' : 'asc';
                                    $usage_arrow = '';
                                    if ($sort === 'usage') {
                                        $usage_arrow = $dir === 'asc' ? 'arrow_upward' : 'arrow_downward';
                                    }
                                    ?>
                                    <a href="?sort=usage&dir=<?= $usage_dir ?>" class="link-secondary text-decoration-none">
                                        Anzahl <?php if ($usage_arrow): ?><span class="material-symbols-outlined" style="font-size:1em;"><?= $usage_arrow ?></span><?php endif; ?>
                                    </a>
                                </th>
                                <?php if ($is_admin): ?>
                                    <th></th>
                                <?php endif; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($colors as $color): ?>
                                <tr>
                                    <td class="align-middle">
                                        <div style="background-color: <?= htmlspecialchars($color['hex_code']); ?>; width: 40px; height: 20px; border: 1px solid #ccc;"></div>
                                    </td>
                                    <td class="align-middle">
                                        <?= htmlspecialchars($color['name']); ?>
                                        <?php if ($color['is_special']): ?>
                                            <span class="badge bg-info ms-1" title="Sonderfarbe – nicht im Zufallsmodus">★</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="align-middle">
                                        <?= (int)$color['usage_count']; ?>
                                    </td>
                                    <?php if ($is_admin): ?>
                                        <td class="text-end align-middle">
                                            <div class="dropdown">
                                                <a href="#" class="text-secondary" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                                                    <span class="material-icons">more_vert</span>
                                                </a>
                                                <ul class="dropdown-menu dropdown-menu-end">
                                                    <li>
                                                        <a class="dropdown-item d-flex align-items-center" href="colors.php?action=edit&id=<?= htmlspecialchars($color['id']); ?>">
                                                            <span class="material-icons me-2">mode_edit_outline</span> Bearbeiten
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a class="dropdown-item d-flex align-items-center text-danger" href="colors.php?action=delete&id=<?= htmlspecialchars($color['id']); ?>" onclick="return confirm('Sind Sie sicher, dass Sie diese Farbe löschen möchten?');">
                                                            <span class="material-icons me-2">delete_outline</span> Löschen
                                                        </a>
                                                    </li>
                                                </ul>
                                            </div>
                                        </td>
                                    <?php endif; ?>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php include('inc/footer.php'); ?>