<?php
/**
 * admin/campaigns/transaction_rules.php
 * ----------------------------------------------------------------------------
 * Kompletter Code inkl. Dropdown für vorhandene field_key‑Werte
 * ---------------------------------------------------------------------------
 */

declare(strict_types=1);

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

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

$db    = Database::getInstance();
$title = 'Transaktions‑Regeln verwalten';

/* -------------------------------- Regel speichern ------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $campaignId     = $_POST['campaign_id']      ?? null;
    $fieldKey       = trim($_POST['field_key']   ?? '');
    $fieldValue     = trim($_POST['field_value'] ?? '');
    $tagId          = $_POST['required_tag_id']  ?? null;
    $dateOffsetDays = (int)($_POST['date_offset_days'] ?? 0);
    $compareMode    = $_POST['date_compare_mode']      ?? 'equal';

    $allowedModes = ['equal','before','after'];
    if (!in_array($compareMode,$allowedModes,true)) $compareMode='equal';

    if (!$campaignId) {
        $_SESSION['error']='Bitte Kampagne auswählen.';
    } else {
        try {
            $sql="INSERT INTO transaction_rules
                    (campaign_id,field_key,field_value,required_tag_id,
                     date_offset_days,date_compare_mode)
                  VALUES (?,?,?,?,?,?)";
            $stmt=$db->prepare($sql);
            $stmt->execute([
                $campaignId,
                $fieldKey   ?: null,
                $fieldValue ?: null,
                $tagId      ?: null,
                $dateOffsetDays,
                $compareMode
            ]);
            ErrorLogger::logSqlSuccess('transaction_rules: insert | SQL: ' . $stmt->queryString . ' | affected: ' . (int)$stmt->rowCount());
            logSettingChange($auth->getUserId(),'create_transaction_rule','transaction_rules',json_encode($_POST,JSON_UNESCAPED_UNICODE));
            $_SESSION['success']='Regel gespeichert.';
            header('Location: transaction_rules.php'); exit;
        }catch(Throwable $e){
            ErrorLogger::logSqlError('transaction_rules: insert failed | error: ' . $e->getMessage());
            $_SESSION['error']='Fehler beim Speichern.';
        }
    }
}

/* ------------------------------ Regel löschen ---------------------------- */
if(isset($_GET['delete'])){
    $id=(int)$_GET['delete'];
    try{
        $del=$db->prepare("DELETE FROM transaction_rules WHERE id=?");
        $del->execute([$id]);
        ErrorLogger::logSqlSuccess('transaction_rules: delete | SQL: ' . $del->queryString . ' | affected: ' . (int)$del->rowCount());
        logSettingChange($auth->getUserId(),'delete_transaction_rule','transaction_rules',$id);
        $_SESSION['success']='Regel gelöscht.';
    }catch(Throwable $e){
        ErrorLogger::logSqlError('transaction_rules: delete failed | error: ' . $e->getMessage());
        $_SESSION['error']='Fehler beim Löschen.';
    }
    header('Location: transaction_rules.php'); exit;
}

/* ------------------------------ Daten laden ------------------------------ */
$campaigns=$db->query("SELECT id,name FROM campaigns WHERE type='transaction' ORDER BY name")->fetchAll();
$tags     =$db->query("SELECT id,name FROM tags ORDER BY name")->fetchAll();
$fields   =$db->query("SELECT DISTINCT field_key FROM recipient_custom_fields ORDER BY field_key")->fetchAll(PDO::FETCH_COLUMN);
$rules=$db->query("SELECT r.*,c.name AS campaign_name,t.name AS tag_name
                     FROM transaction_rules r
                     LEFT JOIN campaigns c ON c.id=r.campaign_id
                     LEFT JOIN tags t ON t.id=r.required_tag_id
	                    ORDER BY r.created_at DESC")->fetchAll();

$fieldTooltips = [
    '[name="campaign_id"]' => 'Transaktionskampagne, die bei erfüllter Regel ausgelöst werden soll.',
    '[name="field_key"]' => 'Optionales Empfängerfeld, das für die Regelprüfung herangezogen wird.',
    '[name="field_value"]' => 'Wert, den das ausgewählte Feld für diese Regel erreichen muss.',
    '[name="required_tag_id"]' => 'Optionaler Tag, der zusätzlich vorhanden sein muss.',
    '[name="date_compare_mode"]' => 'Vergleichsart für datumsbezogene Regeln.',
    '[name="date_offset_days"]' => 'Tageversatz relativ zum Vergleichsdatum.',
];

ob_start();?>
<div class="page-header">Transaktions‑Regeln</div>
<?php foreach(['success','error'] as $t){if(!empty($_SESSION[$t])){?>
  <div class="alert alert-<?= $t==='success'?'success':'danger' ?> alert-dismissible fade show" role="alert">
    <i class="bi bi-<?= $t==='success'?'check-circle':'exclamation-triangle' ?> me-2"></i>
    <?=htmlspecialchars($_SESSION[$t])?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  </div><?php unset($_SESSION[$t]);}}?>

<form method="post" class="mb-4">
  <div class="row g-3 align-items-end">
    <div class="col-md-4">
      <label class="form-label">Kampagne *</label>
      <select name="campaign_id" class="form-select" required>
        <option value="">-- wählen --</option>
        <?php foreach($campaigns as $c):?>
          <option value="<?=$c['id']?>"><?=htmlspecialchars($c['name'])?></option>
        <?php endforeach;?>
      </select>
    </div>

    <div class="col-md-3">
      <label class="form-label">Feldname (optional)</label>
      <select name="field_key" class="form-select">
        <option value="">-- keiner --</option>
        <?php foreach($fields as $f):?>
          <option value="<?=htmlspecialchars($f)?>"><?=htmlspecialchars($f)?></option>
        <?php endforeach;?>
      </select>
    </div>

    <div class="col-md-3">
      <label class="form-label">Feldwert (optional)</label>
      <input type="text" name="field_value" class="form-control" placeholder="z. B. bezahlt">
    </div>

    <div class="col-md-2">
      <label class="form-label">Tag (optional)</label>
      <select name="required_tag_id" class="form-select">
        <option value="">-- keiner --</option>
        <?php foreach($tags as $tag):?>
          <option value="<?=$tag['id']?>"><?=htmlspecialchars($tag['name'])?></option>
        <?php endforeach;?>
      </select>
    </div>
  </div>

  <div class="row g-3 mt-1 align-items-end">
    <div class="col-md-2">
      <label class="form-label">Datums­vergleich</label>
      <select name="date_compare_mode" class="form-select">
        <option value="equal">= (exakt)</option>
        <option value="before">&lt; (vorher)</option>
        <option value="after">&gt; (nachher)</option>
      </select>
    </div>
    <div class="col-md-2">
      <label class="form-label">Versatz ± Tage</label>
      <input type="number" name="date_offset_days" class="form-control" value="0" step="1">
      <small class="text-muted">0 = am Tag, -1 = 1 Tag vorher …</small>
    </div>
  </div>
  <button type="submit" class="btn btn-primary mt-3"><i class="bi bi-floppy me-1"></i> Regel speichern</button>
</form>

<table class="table table-bordered table-striped align-middle">
  <thead class="table-light"><tr><th>ID</th><th>Kampagne</th><th>Feldname</th><th>Feldwert</th><th>Tag</th><th>Vergleich</th><th>± Tage</th><th class="text-center">Aktion</th></tr></thead>
  <tbody>
    <?php foreach($rules as $r):?>
      <tr>
        <td><?=$r['id']?></td>
        <td><?=htmlspecialchars($r['campaign_name'])?></td>
        <td><?=htmlspecialchars($r['field_key']?:'–')?></td>
        <td><?=htmlspecialchars($r['field_value']?:'–')?></td>
        <td><?=htmlspecialchars($r['tag_name']?:'–')?></td>
        <td><?=htmlspecialchars($r['date_compare_mode']?:'–')?></td>
        <td class="text-end"><?=$r['date_offset_days']?></td>
        <td class="text-center">
          <a href="?delete=<?=$r['id']?>" class="btn btn-sm btn-danger" onclick="return confirm('Regel wirklich löschen?')"><i class="bi bi-trash"></i></a>
        </td>
      </tr>
    <?php endforeach;?>
  </tbody>
</table>
<script>setTimeout(()=>document.querySelectorAll('.alert').forEach(a=>bootstrap.Alert.getOrCreateInstance(a).close()),5000);</script>
<?php
$pageContent=ob_get_clean();
include __DIR__.'/../template.php';
