<?php
require_once __DIR__ . "/../config.php";
require_once __DIR__ . "/../includes/functions.php";

if (empty($_SESSION['admin_logged_in'])) {
    header("Location: login.php");
    exit();
}

$pageTitle = "Organisationen verwalten";
$message = "";
$messageType = "";
$organizations = getOrganizations(false);

if ($_SERVER['REQUEST_METHOD'] === "POST") {
    // Validate CSRF token
    if (!validateCsrfToken($_POST['csrf_token'] ?? "")) {
        $message = "Ungültiges Token. Bitte versuchen Sie es erneut.";
        $messageType = "error";
    } else {
        if (isset($_POST['add_organization'])) {
            $label = normalizeOrganizationLabel($_POST['label'] ?? "");
            $sortOrder = (int) ($_POST['sort_order'] ?? 0);
            $active = isset($_POST['active']);

            if (!isValidOrganizationLabel($label)) {
                $message =
                    "Bitte einen Organisationsnamen mit maximal 120 Zeichen eingeben.";
                $messageType = "error";
            } else {
                $orgId = generateOrganizationIdFromLabel(
                    $label,
                    $organizations,
                );
                $organizations[] = [
                    "id" => $orgId,
                    "label" => $label,
                    "sort_order" => $sortOrder,
                    "active" => $active,
                ];
                if (saveOrganizations($organizations)) {
                    logAccess("Admin added organization", [
                        "org_id" => $orgId,
                        "label" => $label,
                    ]);
                    $message = "Organisation wurde angelegt.";
                    $messageType = "success";
                } else {
                    $message = "Organisation konnte nicht gespeichert werden.";
                    $messageType = "error";
                }
            }
        }

        if (isset($_POST['update_organization'])) {
            $organizationId = normalizeOrganizationId(
                $_POST['organization_id'] ?? "",
            );
            $label = normalizeOrganizationLabel($_POST['label'] ?? "");
            $sortOrder = (int) ($_POST['sort_order'] ?? 0);
            $active = isset($_POST['active']);
            $updated = false;

            if (!isValidOrganizationLabel($label)) {
                $message =
                    "Bitte einen Organisationsnamen mit maximal 120 Zeichen eingeben.";
                $messageType = "error";
            } else {
                foreach ($organizations as &$organization) {
                    if ($organization["id"] !== $organizationId) {
                        continue;
                    }

                    $organization["label"] = $label;
                    $organization["sort_order"] = $sortOrder;
                    $organization["active"] = $active;
                    $updated = true;
                    break;
                }
                unset($organization);

                if ($updated) {
                    if (saveOrganizations($organizations)) {
                        logAccess("Admin updated organization", [
                            "org_id" => $organizationId,
                            "label" => $label,
                        ]);
                        $message = "Organisation wurde aktualisiert.";
                        $messageType = "success";
                    } else {
                        $message =
                            "Organisation konnte nicht gespeichert werden.";
                        $messageType = "error";
                    }
                } else {
                    $message = "Organisation nicht gefunden.";
                    $messageType = "error";
                }
            }
        }

        if (isset($_POST['delete_organization'])) {
            $organizationId = normalizeOrganizationId(
                $_POST['organization_id'] ?? "",
            );
            $orgLabel = "";
            $found = false;
            foreach ($organizations as $organization) {
                if ($organization["id"] === $organizationId) {
                    $orgLabel = $organization["label"];
                    break;
                }
            }
            $organizations = array_values(
                array_filter($organizations, function ($organization) use (
                    $organizationId,
                ) {
                    return $organization["id"] !== $organizationId;
                }),
            );
            if (saveOrganizations($organizations)) {
                logAccess("Admin deleted organization", [
                    "org_id" => $organizationId,
                    "label" => $orgLabel,
                ]);
                $message = "Organisation wurde gelöscht.";
                $messageType = "success";
            } else {
                $message = "Organisation konnte nicht gelöscht werden.";
                $messageType = "error";
            }
        }

        $organizations = getOrganizations(false);
    }
}

$editingOrganization = isset($_GET['edit'])
    ? getOrganizationById($_GET['edit'])
    : null;

$bodyClass = "admin-page";
include __DIR__ . "/../includes/header.php";
?>

<div class="admin-header">
    <h2>Organisationen verwalten</h2>
    <div>
        <a href="index.php" class="btn btn-secondary">Zurück zum Dashboard</a>
    </div>
</div>

<?php if ($message !== ""): ?>
    <div class="alert alert-<?php echo escape($messageType); ?>">
        <?php echo escape($message); ?>
    </div>
<?php endif; ?>

<div class="panel panel-lg">
    <h3><?php echo $editingOrganization
        ? "Organisation bearbeiten"
        : "Neue Organisation"; ?></h3>
    <form method="POST">
        <?php echo csrfField(); ?>
        <?php if ($editingOrganization): ?>
            <input type="hidden" name="organization_id" value="<?php echo escape(
                $editingOrganization["id"],
            ); ?>">
        <?php endif; ?>

        <div class="form-group">
            <label for="label">Name *</label>
            <input type="text" id="label" name="label" required maxlength="120" value="<?php echo escape(
                $editingOrganization["label"] ?? "",
            ); ?>">
        </div>

        <div class="form-group">
            <label for="sort_order">Sortierung</label>
            <input type="number" id="sort_order" name="sort_order" value="<?php echo escape(
                (string) ($editingOrganization["sort_order"] ?? 0),
            ); ?>">
        </div>

        <div class="form-group">
            <label>
                <input type="checkbox" name="active" value="1" <?php echo !isset(
                    $editingOrganization["active"],
                ) || !empty($editingOrganization["active"])
                    ? "checked"
                    : ""; ?>>
                Organisation ist auswählbar
            </label>
        </div>

        <button type="submit" name="<?php echo $editingOrganization
            ? "update_organization"
            : "add_organization"; ?>" class="btn">
            <?php echo $editingOrganization
                ? "Speichern"
                : "Organisation anlegen"; ?>
        </button>
        <?php if ($editingOrganization): ?>
            <a href="organizations.php" class="btn btn-secondary">Abbrechen</a>
        <?php endif; ?>
    </form>
</div>

<div class="panel">
    <h3>Organisationen</h3>
    <div class="table-responsive">
        <table class="responsive-table">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>ID</th>
                    <th>Sortierung</th>
                    <th>Status</th>
                    <th>Aktionen</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($organizations as $organization): ?>
                    <tr>
                        <td data-label="Name"><?php echo escape(
                            $organization["label"],
                        ); ?></td>
                        <td data-label="ID"><code><?php echo escape(
                            $organization["id"],
                        ); ?></code></td>
                        <td data-label="Sortierung"><?php echo (int) $organization[
                            "sort_order"
                        ]; ?></td>
                        <td data-label="Status">
                            <span class="status <?php echo !empty(
                                $organization["active"]
                            )
                                ? "status-open"
                                : "status-cancelled"; ?>">
                                <?php echo !empty($organization["active"])
                                    ? "Aktiv"
                                    : "Inaktiv"; ?>
                            </span>
                        </td>
                        <td data-label="Aktionen">
                            <a href="organizations.php?edit=<?php echo urlencode(
                                $organization["id"],
                            ); ?>" class="btn btn-small">Bearbeiten</a>
                             <form method="POST" class="inline-form" onsubmit="return confirm('Organisation wirklich löschen?');">
                                <?php echo csrfField(); ?>
                                <input type="hidden" name="organization_id" value="<?php echo escape(
                                    $organization["id"],
                                ); ?>">
                                <button type="submit" name="delete_organization" class="btn btn-secondary btn-small">Löschen</button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include __DIR__ . "/../includes/footer.php"; ?>
