<?php

session_start();
require_once __DIR__ . '/../../includes/init.php';
require_once __DIR__ . '/../../auth/AuthController.php';
require_once __DIR__ . '/../../includes/core/MemberAuthService.php';

$auth = new AuthController();
if (!$auth->isLoggedIn()) {
    header('Location: ' . $adminLoginPath);
    exit;
}

$title = 'Empfaenger bearbeiten';
$db = Database::getInstance();
$memberModuleEnabled = isMemberModuleEnabled($config);
$memberService = new MemberAuthService($db, $config);
$error = '';

$id = $_GET['id'] ?? null;
if (!$id || !is_numeric($id)) {
    ErrorLogger::log('Ungueltige ID in empfaenger_edit.php: ' . (string) $id, 'WARN');
    header('Location: empfaenger.php?error=invalid_id');
    exit;
}

try {
    $stmt = $db->prepare('SELECT * FROM recipients WHERE id = ?');
    $stmt->execute([$id]);
    ErrorLogger::logSqlSuccess('Empfaenger geladen | table: recipients | context: ' . json_encode(['id' => (int) $id], JSON_UNESCAPED_UNICODE));
    $empfaenger = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$empfaenger) {
        header('Location: empfaenger.php?error=not_found');
        exit;
    }

    $lists = $db->query('SELECT id, name FROM lists ORDER BY name ASC')->fetchAll(PDO::FETCH_ASSOC) ?: [];
    ErrorLogger::logSqlSuccess('Listen geladen | table: lists');

    $tags = $db->query('SELECT id, name FROM tags ORDER BY name ASC')->fetchAll(PDO::FETCH_ASSOC) ?: [];
    ErrorLogger::logSqlSuccess('Tags geladen | table: tags');

    $stmtTags = $db->prepare('SELECT tag_id FROM recipient_tags WHERE recipient_id = ?');
    $stmtTags->execute([$id]);
    $assignedTags = array_column($stmtTags->fetchAll(PDO::FETCH_ASSOC) ?: [], 'tag_id');
    ErrorLogger::logSqlSuccess('Empfaenger-Tags geladen | table: recipient_tags | context: ' . json_encode(['recipient_id' => (int) $id], JSON_UNESCAPED_UNICODE));

    $stmtLists = $db->prepare('SELECT list_id FROM recipient_lists WHERE recipient_id = ?');
    $stmtLists->execute([$id]);
    $assignedLists = array_column($stmtLists->fetchAll(PDO::FETCH_ASSOC) ?: [], 'list_id');
    ErrorLogger::logSqlSuccess('Empfaenger-Listen geladen | table: recipient_lists | context: ' . json_encode(['recipient_id' => (int) $id], JSON_UNESCAPED_UNICODE));

    $customFields = $db->query('SELECT * FROM custom_field_definitions ORDER BY created_at ASC')->fetchAll(PDO::FETCH_ASSOC) ?: [];
    $stmtVals = $db->prepare('SELECT field_key, field_value FROM recipient_custom_fields WHERE recipient_id = ?');
    $stmtVals->execute([$id]);
    $customVals = array_column($stmtVals->fetchAll(PDO::FETCH_ASSOC) ?: [], 'field_value', 'field_key');
    ErrorLogger::logSqlSuccess('Empfaenger-Zusatzfelder geladen | table: recipient_custom_fields | context: ' . json_encode(['recipient_id' => (int) $id], JSON_UNESCAPED_UNICODE));
} catch (Throwable $e) {
    ErrorLogger::logSqlError('Empfaengerdaten konnten nicht geladen werden | recipient_id: ' . (int) $id . ' | error: ' . $e->getMessage());
    header('Location: empfaenger.php?error=load_error');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $anrede = (string) ($_POST['anrede'] ?? '');
    $vorname = trim((string) ($_POST['vorname'] ?? ''));
    $nachname = trim((string) ($_POST['nachname'] ?? ''));
    $email = trim((string) ($_POST['email'] ?? ''));
    $status = (string) ($_POST['status'] ?? 'active');
    $notizen = (string) ($_POST['notizen'] ?? '');
    $listToRemove = $_POST['list_to_remove'] ?? null;
    $listToAdd = $_POST['list_to_add'] ?? null;
    $tagToAdd = $_POST['tag_to_add'] ?? null;
    $tagToRemove = $_POST['tag_to_remove'] ?? null;
    $memberLoginEnabled = $memberModuleEnabled ? !empty($_POST['member_login_enabled']) : !empty($empfaenger['login_enabled']);
    $memberPassword = trim((string) ($_POST['member_password'] ?? ''));
    $memberSendPasswordMail = $memberModuleEnabled && !empty($_POST['member_send_password_mail']);

    try {
        $updateSql = 'UPDATE recipients SET anrede = ?, vorname = ?, nachname = ?, email = ?, status = ?, notizen = ? WHERE id = ?';
        $updateStmt = $db->prepare($updateSql);
        $updateStmt->execute([$anrede, $vorname, $nachname, $email, $status, $notizen, $id]);
        ErrorLogger::logSqlSuccess('Empfaenger aktualisiert | SQL: ' . $updateSql . ' | params: ' . json_encode([(int) $id, $email], JSON_UNESCAPED_UNICODE));

        $deleteCustomSql = 'DELETE FROM recipient_custom_fields WHERE recipient_id = ?';
        $deleteCustomStmt = $db->prepare($deleteCustomSql);
        $deleteCustomStmt->execute([$id]);
        ErrorLogger::logSqlSuccess('Empfaenger-Zusatzfelder geloescht | SQL: ' . $deleteCustomSql . ' | params: ' . json_encode([(int) $id], JSON_UNESCAPED_UNICODE));

        $insertCustomSql = 'INSERT INTO recipient_custom_fields (recipient_id, field_key, field_value) VALUES (?, ?, ?)';
        $insertCustomStmt = $db->prepare($insertCustomSql);
        foreach ($customFields as $field) {
            $key = (string) ($field['field_key'] ?? '');
            $value = trim((string) ($_POST['custom'][$key] ?? ''));
            if ($key === '' || $value === '') {
                continue;
            }
            $insertCustomStmt->execute([$id, $key, $value]);
        }
        ErrorLogger::logSqlSuccess('Empfaenger-Zusatzfelder gespeichert | SQL: ' . $insertCustomSql . ' | params: ' . json_encode([(int) $id], JSON_UNESCAPED_UNICODE));

        if (!empty($tagToRemove)) {
            $sql = 'DELETE FROM recipient_tags WHERE recipient_id = ? AND tag_id = ?';
            $stmt = $db->prepare($sql);
            $stmt->execute([$id, $tagToRemove]);
            ErrorLogger::logSqlSuccess('Empfaenger-Tag entfernt | SQL: ' . $sql . ' | params: ' . json_encode([(int) $id, (int) $tagToRemove], JSON_UNESCAPED_UNICODE));
        }

        if (!empty($tagToAdd)) {
            $checkSql = 'SELECT COUNT(*) FROM recipient_tags WHERE recipient_id = ? AND tag_id = ?';
            $checkStmt = $db->prepare($checkSql);
            $checkStmt->execute([$id, $tagToAdd]);
            ErrorLogger::logSqlSuccess('Empfaenger-Tag pruefen | SQL: ' . $checkSql . ' | params: ' . json_encode([(int) $id, (int) $tagToAdd], JSON_UNESCAPED_UNICODE));
            if ((int) $checkStmt->fetchColumn() === 0) {
                $insertSql = 'INSERT INTO recipient_tags (recipient_id, tag_id, assigned_at) VALUES (?, ?, NOW())';
                $insertStmt = $db->prepare($insertSql);
                $insertStmt->execute([$id, $tagToAdd]);
                ErrorLogger::logSqlSuccess('Empfaenger-Tag hinzugefuegt | SQL: ' . $insertSql . ' | params: ' . json_encode([(int) $id, (int) $tagToAdd], JSON_UNESCAPED_UNICODE));
            }
        }

        if (!empty($listToRemove)) {
            $sql = 'DELETE FROM recipient_lists WHERE recipient_id = ? AND list_id = ?';
            $stmt = $db->prepare($sql);
            $stmt->execute([$id, $listToRemove]);
            ErrorLogger::logSqlSuccess('Empfaenger-Liste entfernt | SQL: ' . $sql . ' | params: ' . json_encode([(int) $id, (int) $listToRemove], JSON_UNESCAPED_UNICODE));
        }

        if (!empty($listToAdd)) {
            $checkSql = 'SELECT COUNT(*) FROM recipient_lists WHERE recipient_id = ? AND list_id = ?';
            $checkStmt = $db->prepare($checkSql);
            $checkStmt->execute([$id, $listToAdd]);
            ErrorLogger::logSqlSuccess('Empfaenger-Liste pruefen | SQL: ' . $checkSql . ' | params: ' . json_encode([(int) $id, (int) $listToAdd], JSON_UNESCAPED_UNICODE));
            if ((int) $checkStmt->fetchColumn() === 0) {
                $pauseToken = bin2hex(random_bytes(32));
                $insertSql = 'INSERT INTO recipient_lists (recipient_id, list_id, subscribed_at, pause_token) VALUES (?, ?, NOW(), ?)';
                $insertStmt = $db->prepare($insertSql);
                $insertStmt->execute([$id, $listToAdd, $pauseToken]);
                ErrorLogger::logSqlSuccess('Empfaenger-Liste hinzugefuegt | SQL: ' . $insertSql . ' | params: ' . json_encode([(int) $id, (int) $listToAdd], JSON_UNESCAPED_UNICODE));
            }
        }

        $memberNotice = '';
        if ($memberModuleEnabled) {
            if (!$memberService->setRecipientAccess((int) $id, $memberLoginEnabled, $memberPassword !== '' ? $memberPassword : null)) {
                throw new RuntimeException('Mitgliederzugang konnte nicht gespeichert werden.');
            }

            if ($memberSendPasswordMail && $memberPassword !== '') {
                $memberMailSent = $memberService->sendAccessMail([
                    'email' => $email,
                    'vorname' => $vorname,
                    'nachname' => $nachname,
                ], $memberPassword);
                $memberNotice = $memberMailSent ? 'member_mail_sent' : 'member_mail_failed';
            }
        }

        $redirectParams = ['success' => 'updated'];
        if ($memberNotice !== '') {
            $redirectParams['member'] = $memberNotice;
        }
        header('Location: empfaenger.php?' . http_build_query($redirectParams));
        exit;
    } catch (Throwable $e) {
        ErrorLogger::logSqlError('Empfaenger speichern fehlgeschlagen | recipient_id: ' . (int) $id . ' | error: ' . $e->getMessage());
        $error = 'Fehler beim Speichern.';
    }
}

$pageHelp = renderPageHelp([
    'sections' => [
        [
            'heading' => 'Was macht diese Seite?',
            'items' => [
                'Hier bearbeitest du die Daten eines vorhandenen Empf&auml;ngers.',
                'Du kannst Stammdaten, Listenbezug, Tags und Zusatzfelder anpassen.',
            ],
        ],
        [
            'heading' => 'Was muss ich eingeben oder ausw&auml;hlen?',
            'items' => [
                'Aendere nur die Angaben, die fachlich wirklich angepasst werden sollen.',
                'Kontrolliere besonders Status, Liste, E-Mail-Adresse und zugeordnete Tags.',
            ],
        ],
        [
            'heading' => 'Worauf sollte ich achten?',
            'items' => [
                'Status- oder Listen&auml;nderungen koennen Auswirkungen auf spaetere Versand- und Follow-up-Prozesse haben.',
                'Wenn der Mitgliederbereich aktiv ist, wird der Login hier direkt am Empf&auml;nger gesteuert.',
            ],
        ],
    ],
]);

$fieldTooltips = [
    '[name="anrede"]' => 'Optionale persoenliche Anrede fuer spaetere Personalisierung.',
    '[name="vorname"]' => 'Vorname des Empf&auml;ngers.',
    '[name="nachname"]' => 'Nachname des Empf&auml;ngers.',
    '[name="email"]' => 'E-Mail-Adresse des Empf&auml;ngers.',
    '[name="status"]' => 'Aktueller Status fuer Versand und Verarbeitung.',
    '[name="notizen"]' => 'Interne Notizen zu diesem Empf&auml;nger.',
    '[name="list_to_remove"]' => 'Entfernt den Empf&auml;nger aus einer aktuell zugeordneten Liste.',
    '[name="list_to_add"]' => 'Fuegt den Empf&auml;nger einer zusaetzlichen Liste hinzu.',
    '[name="tag_to_remove"]' => 'Entfernt einen bestehenden Tag von diesem Empf&auml;nger.',
    '[name="tag_to_add"]' => 'Fuegt einen zusaetzlichen Tag zu diesem Empf&auml;nger hinzu.',
    '[name^="custom["]' => 'Zusatzwert fuer ein benutzerdefiniertes Empf&auml;ngerfeld.',
];

if ($memberModuleEnabled) {
    $fieldTooltips['[name="member_login_enabled"]'] = 'Aktiviert den Login fuer diesen Empf&auml;nger im Mitgliederbereich.';
    $fieldTooltips['[name="member_password"]'] = 'Neues Passwort fuer den Mitgliederzugang. Leer lassen, um das bestehende Passwort zu behalten.';
    $fieldTooltips['[name="member_send_password_mail"]'] = 'Versendet das neu gesetzte Passwort direkt an die gespeicherte E-Mail-Adresse.';
}

ob_start();
?>
<div class="page-header h2">Empf&auml;nger &raquo; Bearbeiten</div>

<?= $pageHelp ?>

<?php if ($error !== ''): ?>
  <div class="alert alert-danger auto-dismiss"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
<?php endif; ?>

<form method="post" class="row g-3">
  <div class="col-md-2">
    <label class="form-label">Anrede</label>
    <select name="anrede" class="form-select">
      <option value="">-</option>
      <option value="Herr" <?= (($empfaenger['anrede'] ?? '') === 'Herr') ? 'selected' : '' ?>>Herr</option>
      <option value="Frau" <?= (($empfaenger['anrede'] ?? '') === 'Frau') ? 'selected' : '' ?>>Frau</option>
      <option value="Divers" <?= (($empfaenger['anrede'] ?? '') === 'Divers') ? 'selected' : '' ?>>Divers</option>
    </select>
  </div>

  <div class="col-md-5">
    <label class="form-label">Vorname</label>
    <input type="text" name="vorname" class="form-control" value="<?= htmlspecialchars((string) ($empfaenger['vorname'] ?? ''), ENT_QUOTES, 'UTF-8') ?>">
  </div>

  <div class="col-md-5">
    <label class="form-label">Nachname</label>
    <input type="text" name="nachname" class="form-control" value="<?= htmlspecialchars((string) ($empfaenger['nachname'] ?? ''), ENT_QUOTES, 'UTF-8') ?>">
  </div>

  <div class="col-md-6">
    <label class="form-label">E-Mail</label>
    <input type="email" name="email" class="form-control" value="<?= htmlspecialchars((string) ($empfaenger['email'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" required>
  </div>

  <div class="col-md-3">
    <label class="form-label">Status</label>
    <select name="status" class="form-select">
      <option value="active" <?= (($empfaenger['status'] ?? '') === 'active') ? 'selected' : '' ?>>Aktiv</option>
      <option value="unsubscribed" <?= (($empfaenger['status'] ?? '') === 'unsubscribed') ? 'selected' : '' ?>>Abgemeldet</option>
      <option value="bounced" <?= (($empfaenger['status'] ?? '') === 'bounced') ? 'selected' : '' ?>>Unzustellbar</option>
      <option value="pause" <?= (($empfaenger['status'] ?? '') === 'pause') ? 'selected' : '' ?>>Versandpause</option>
    </select>
  </div>

  <div class="col-md-3">
    <label class="form-label">Mitglieder-Login</label>
    <input type="text" class="form-control" value="<?= !empty($empfaenger['login_enabled']) ? 'Aktiv' : 'Inaktiv' ?>" readonly>
  </div>

  <div class="col-md-6">
    <label class="form-label">Aktuelle Listen</label>
    <ul class="form-control" style="height:auto; background:#f9f9f9; padding:10px">
      <?php foreach ($lists as $list): ?>
        <?php if (in_array($list['id'], $assignedLists, true)): ?>
          <li><?= htmlspecialchars((string) $list['name'], ENT_QUOTES, 'UTF-8') ?> (ID <?= (int) $list['id'] ?>)</li>
        <?php endif; ?>
      <?php endforeach; ?>
    </ul>
  </div>

  <div class="col-md-6">
    <label class="form-label">Aus Liste entfernen</label>
    <select name="list_to_remove" class="form-select">
      <option value="">Keine</option>
      <?php foreach ($lists as $list): ?>
        <?php if (in_array($list['id'], $assignedLists, true)): ?>
          <option value="<?= (int) $list['id'] ?>"><?= htmlspecialchars((string) $list['name'], ENT_QUOTES, 'UTF-8') ?></option>
        <?php endif; ?>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="col-md-6">
    <label class="form-label">Liste hinzufuegen</label>
    <select name="list_to_add" class="form-select">
      <option value="">Keine</option>
      <?php foreach ($lists as $list): ?>
        <?php if (!in_array($list['id'], $assignedLists, true)): ?>
          <option value="<?= (int) $list['id'] ?>"><?= htmlspecialchars((string) $list['name'], ENT_QUOTES, 'UTF-8') ?></option>
        <?php endif; ?>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="col-md-6">
    <label class="form-label">Aktive Tags</label>
    <ul class="form-control" style="height:auto; background:#f9f9f9; padding:10px">
      <?php foreach ($tags as $tag): ?>
        <?php if (in_array($tag['id'], $assignedTags, true)): ?>
          <li><?= htmlspecialchars((string) $tag['name'], ENT_QUOTES, 'UTF-8') ?> (ID <?= (int) $tag['id'] ?>)</li>
        <?php endif; ?>
      <?php endforeach; ?>
    </ul>
  </div>

  <div class="col-md-6">
    <label class="form-label">Tag entfernen</label>
    <select name="tag_to_remove" class="form-select">
      <option value="">Kein Tag entfernen</option>
      <?php foreach ($tags as $tag): ?>
        <?php if (in_array($tag['id'], $assignedTags, true)): ?>
          <option value="<?= (int) $tag['id'] ?>"><?= htmlspecialchars((string) $tag['name'], ENT_QUOTES, 'UTF-8') ?></option>
        <?php endif; ?>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="col-md-6">
    <label class="form-label">Tag hinzufuegen</label>
    <select name="tag_to_add" class="form-select">
      <option value="">Kein Tag hinzufuegen</option>
      <?php foreach ($tags as $tag): ?>
        <?php if (!in_array($tag['id'], $assignedTags, true)): ?>
          <option value="<?= (int) $tag['id'] ?>"><?= htmlspecialchars((string) $tag['name'], ENT_QUOTES, 'UTF-8') ?></option>
        <?php endif; ?>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="col-md-12">
    <label class="form-label">Notizen</label>
    <textarea name="notizen" class="form-control" rows="3"><?= htmlspecialchars((string) ($empfaenger['notizen'] ?? ''), ENT_QUOTES, 'UTF-8') ?></textarea>
  </div>

  <h5 class="mt-4">Zusaetzliche Felder</h5>
  <?php foreach ($customFields as $field): ?>
    <div class="col-md-6">
      <label class="form-label"><?= htmlspecialchars((string) ($field['label'] ?? ''), ENT_QUOTES, 'UTF-8') ?></label>
      <input type="text" name="custom[<?= htmlspecialchars((string) ($field['field_key'] ?? ''), ENT_QUOTES, 'UTF-8') ?>]" class="form-control" value="<?= htmlspecialchars((string) ($customVals[(string) ($field['field_key'] ?? '')] ?? ''), ENT_QUOTES, 'UTF-8') ?>">
    </div>
  <?php endforeach; ?>

  <?php if ($memberModuleEnabled): ?>
    <h5 class="mt-4">Mitgliederbereich</h5>
    <div class="col-md-4">
      <div class="form-check mt-4 pt-2">
        <input class="form-check-input" type="checkbox" name="member_login_enabled" id="member_login_enabled" value="1" <?= !empty($empfaenger['login_enabled']) ? 'checked' : '' ?>>
        <label class="form-check-label" for="member_login_enabled">Login fuer diesen Empf&auml;nger aktivieren</label>
      </div>
    </div>
    <div class="col-md-4">
      <label class="form-label" for="member_password">Neues Passwort</label>
      <input type="text" name="member_password" id="member_password" class="form-control" autocomplete="off">
      <small class="text-muted">Leer lassen, wenn das bestehende Passwort unveraendert bleiben soll.</small>
    </div>
    <div class="col-md-4">
      <div class="form-check mt-4 pt-2">
        <input class="form-check-input" type="checkbox" name="member_send_password_mail" id="member_send_password_mail" value="1">
        <label class="form-check-label" for="member_send_password_mail">Neues Passwort per E-Mail versenden</label>
      </div>
      <div class="mt-2 small text-muted">Login-URL: <a href="<?= htmlspecialchars(memberBasePath($config) . '/login.php', ENT_QUOTES, 'UTF-8') ?>" target="_blank" rel="noopener">Mitgliederbereich oeffnen</a></div>
    </div>
  <?php endif; ?>

  <div class="col-12">
    <button type="submit" class="btn btn-primary">Speichern</button>
    <a href="empfaenger.php" class="btn btn-secondary">Abbrechen</a>
  </div>
</form>
<?php
$pageContent = ob_get_clean();
include __DIR__ . '/../template.php';