<?php
// ─────────────────────────────────────────────
// hq/rcic.php  —  RCIC-Berater verwalten
// ─────────────────────────────────────────────

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_hq_auth();

$db  = C2CDatabase::get();
$msg = '';

// ── Speichern ─────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'save') {
        $id = (int)($_POST['id'] ?? 0);
        $fields = ['name','title','firm','city','province','languages',
                   'specialties','phone','email','website','rcic_number','notes'];
        $data = [];
        foreach ($fields as $f) $data[$f] = trim($_POST[$f] ?? '');
        $data['active']     = (int)isset($_POST['active']);
        $data['sort_order'] = (int)($_POST['sort_order'] ?? 0);

        if ($id) {
            $sets = implode(',', array_map(fn($f) => "`$f`=:$f", array_keys($data)));
            $data['id'] = $id;
            $db->prepare("UPDATE rcic_consultants SET $sets WHERE id=:id")->execute($data);
            $msg = '✓ Berater aktualisiert';
        } else {
            $cols = implode(',', array_map(fn($f) => "`$f`", array_keys($data)));
            $vals = implode(',', array_map(fn($f) => ":$f", array_keys($data)));
            $db->prepare("INSERT INTO rcic_consultants ($cols) VALUES ($vals)")->execute($data);
            $msg = '✓ Berater hinzugefügt';
        }
    }

    if ($action === 'toggle') {
        $id = (int)($_POST['id'] ?? 0);
        $db->prepare("UPDATE rcic_consultants SET active = 1 - active WHERE id=?")->execute([$id]);
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $db->prepare("DELETE FROM rcic_consultants WHERE id=?")->execute([$id]);
        $msg = '✓ Berater gelöscht';
    }
}

// ── Liste laden ───────────────────────────────
$rcics   = $db->query("SELECT * FROM rcic_consultants ORDER BY sort_order, id")->fetchAll();
$editId  = (int)($_GET['edit'] ?? 0);
$editing = null;
if ($editId) {
    $stmt = $db->prepare("SELECT * FROM rcic_consultants WHERE id=?");
    $stmt->execute([$editId]);
    $editing = $stmt->fetch();
}
$newForm = isset($_GET['new']) || ($editId && !$editing);
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>RCIC-Berater — HQ</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&family=Special+Elite&display=swap" rel="stylesheet">
<style>
:root{--bg:#0F1410;--s:#1A2018;--s2:#222B20;--s3:#2A342A;--bdr:#344030;--bdr2:#405040;
  --r:#D0271D;--g:#3CA85A;--gold:#C8A96E;--w:#F5F2EC;--muted:#8A9280;--rad:10px;}
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:Inter,sans-serif;background:var(--bg);color:var(--w);font-size:14px;min-height:100vh;}
.topbar{height:54px;background:var(--s);border-bottom:1px solid var(--bdr);display:flex;
  align-items:center;padding:0 24px;gap:16px;position:sticky;top:0;z-index:100;}
.topbar-logo{font-family:'Special Elite',serif;font-size:17px;font-weight:700;}
.topbar-logo span{color:var(--r);}
.sep{width:1px;height:20px;background:var(--bdr);}
.topbar-title{font-size:14px;color:var(--muted);}
.page{max-width:1100px;margin:0 auto;padding:32px 24px;display:grid;
  grid-template-columns:1fr 420px;gap:28px;align-items:start;}
.card{background:var(--s);border:1px solid var(--bdr);border-radius:var(--rad);overflow:hidden;}
.card-head{padding:16px 20px;border-bottom:1px solid var(--bdr);
  display:flex;align-items:center;justify-content:space-between;}
.card-head h3{font-size:14px;font-weight:600;}
.card-body{padding:20px;}
.msg{background:var(--g);color:#fff;padding:10px 16px;border-radius:var(--rad);
  margin-bottom:20px;font-size:13px;font-weight:600;grid-column:1/-1;}

/* RCIC LIST */
.rcic-item{background:var(--s2);border:1px solid var(--bdr);border-radius:8px;
  padding:16px;margin-bottom:12px;display:flex;gap:14px;align-items:flex-start;}
.rcic-item.inactive{opacity:.5;}
.rcic-info{flex:1;}
.rcic-name{font-family:'Special Elite',serif;font-size:16px;margin-bottom:4px;}
.rcic-meta{font-size:12px;color:var(--muted);line-height:1.7;}
.rcic-actions{display:flex;flex-direction:column;gap:6px;flex-shrink:0;}
.btn{padding:7px 14px;border-radius:6px;border:none;cursor:pointer;font-size:12px;
  font-weight:600;font-family:Inter,sans-serif;transition:all .15s;text-decoration:none;display:inline-block;}
.btn-sm{padding:5px 12px;font-size:11px;}
.btn-edit{background:var(--s3);color:var(--w);border:1px solid var(--bdr2);}
.btn-edit:hover{border-color:var(--gold);color:var(--gold);}
.btn-red{background:var(--r);color:#fff;}
.btn-red:hover{background:#b01f16;}
.btn-green{background:var(--g);color:#fff;}
.btn-muted{background:var(--s3);color:var(--muted);border:1px solid var(--bdr);}

/* FORM */
.field{margin-bottom:18px;}
.field label{display:block;font-size:12px;font-weight:600;color:var(--w);
  margin-bottom:6px;letter-spacing:.3px;}
.field label .sub{font-weight:400;color:var(--muted);}
input[type=text],input[type=email],input[type=tel],input[type=number],
select,textarea{
  width:100%;background:var(--s2);border:1.5px solid var(--bdr);
  border-radius:6px;color:var(--w);font-family:Inter,sans-serif;
  font-size:13px;padding:10px 13px;outline:none;transition:border-color .15s;
}
input:focus,select:focus,textarea:focus{border-color:var(--r);}
textarea{min-height:80px;resize:vertical;}
.check-row{display:flex;align-items:center;gap:10px;font-size:13px;}
.check-row input{width:16px;height:16px;accent-color:var(--r);}
.form-actions{display:flex;gap:10px;margin-top:24px;padding-top:20px;
  border-top:1px solid var(--bdr);}
.btn-save{background:var(--r);color:#fff;padding:10px 24px;border-radius:6px;
  border:none;cursor:pointer;font-size:13px;font-weight:700;font-family:Inter,sans-serif;}
.btn-save:hover{background:#b01f16;}
.btn-cancel{background:var(--s3);color:var(--muted);padding:10px 20px;border-radius:6px;
  border:1px solid var(--bdr);cursor:pointer;font-size:13px;font-family:Inter,sans-serif;
  text-decoration:none;display:inline-flex;align-items:center;}
.sortnum{width:60px;display:inline-block;}
</style>
</head>
<body>

<div class="topbar">
  <div class="topbar-logo">🍁 <span>C2C</span> HQ</div>
  <div class="sep"></div>
  <span class="topbar-title">RCIC-Berater verwalten</span>
  <div style="margin-left:auto;display:flex;gap:10px;">
    <a href="?new=1" class="btn btn-green">+ Neuer Berater</a>
    <a href="index.php" class="btn btn-muted">← HQ</a>
  </div>
</div>

<div class="page">

  <?php if ($msg): ?>
    <div class="msg"><?= htmlspecialchars($msg) ?></div>
  <?php endif; ?>

  <!-- LISTE -->
  <div>
    <div class="card">
      <div class="card-head">
        <h3>👥 Empfohlene RCIC-Berater (<?= count($rcics) ?>)</h3>
      </div>
      <div class="card-body">
        <?php if (empty($rcics)): ?>
          <p style="color:var(--muted);font-size:13px;">Noch keine Berater erfasst.</p>
        <?php endif; ?>
        <?php foreach ($rcics as $r): ?>
          <div class="rcic-item <?= $r['active'] ? '' : 'inactive' ?>">
            <div style="font-size:24px;flex-shrink:0;">👤</div>
            <div class="rcic-info">
              <div class="rcic-name"><?= htmlspecialchars($r['name']) ?></div>
              <div class="rcic-meta">
                <?= htmlspecialchars($r['title'] ?? '') ?><br>
                <?php if ($r['firm']): ?><?= htmlspecialchars($r['firm']) ?> · <?php endif; ?>
                <?= htmlspecialchars($r['city'] ?? '') ?>, <?= htmlspecialchars($r['province'] ?? '') ?><br>
                🗣 <?= htmlspecialchars($r['languages'] ?? '—') ?><br>
                <?php if ($r['rcic_number']): ?>
                  <span style="color:var(--gold);">RCIC <?= htmlspecialchars($r['rcic_number']) ?></span><br>
                <?php endif; ?>
                <?php if ($r['email']): ?>
                  <a href="mailto:<?= htmlspecialchars($r['email']) ?>"
                     style="color:var(--r);text-decoration:none;">
                    <?= htmlspecialchars($r['email']) ?></a>
                <?php endif; ?>
              </div>
            </div>
            <div class="rcic-actions">
              <a href="?edit=<?= $r['id'] ?>" class="btn btn-sm btn-edit">✏️ Bearbeiten</a>
              <form method="POST" style="display:inline">
                <input type="hidden" name="action" value="toggle">
                <input type="hidden" name="id" value="<?= $r['id'] ?>">
                <button type="submit" class="btn btn-sm <?= $r['active'] ? 'btn-muted' : 'btn-green' ?>">
                  <?= $r['active'] ? '⏸ Deaktivieren' : '▶ Aktivieren' ?>
                </button>
              </form>
              <form method="POST" onsubmit="return confirm('Berater löschen?')" style="display:inline">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?= $r['id'] ?>">
                <button type="submit" class="btn btn-sm btn-red">🗑 Löschen</button>
              </form>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>

  <!-- FORMULAR -->
  <div>
    <div class="card">
      <div class="card-head">
        <h3><?= $editing ? '✏️ Berater bearbeiten' : '+ Neuer Berater' ?></h3>
      </div>
      <div class="card-body">
        <?php if (!$editing && !$newForm): ?>
          <p style="color:var(--muted);font-size:13px;">
            Klicken Sie auf "+ Neuer Berater" oder wählen Sie einen Berater zum Bearbeiten.
          </p>
        <?php else: ?>
          <form method="POST">
            <input type="hidden" name="action" value="save">
            <input type="hidden" name="id" value="<?= $editing['id'] ?? 0 ?>">

            <div class="field">
              <label>Name <span class="sub">*</span></label>
              <input type="text" name="name" required
                value="<?= htmlspecialchars($editing['name'] ?? '') ?>"
                placeholder="Vor- und Nachname oder Firmenname">
            </div>
            <div class="field">
              <label>Titel <span class="sub">z.B. RCIC</span></label>
              <input type="text" name="title"
                value="<?= htmlspecialchars($editing['title'] ?? 'Regulated Canadian Immigration Consultant (RCIC)') ?>">
            </div>
            <div class="field">
              <label>Firma / Kanzlei</label>
              <input type="text" name="firm"
                value="<?= htmlspecialchars($editing['firm'] ?? '') ?>">
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
              <div class="field">
                <label>Stadt</label>
                <input type="text" name="city"
                  value="<?= htmlspecialchars($editing['city'] ?? '') ?>" placeholder="Toronto">
              </div>
              <div class="field">
                <label>Provinz</label>
                <select name="province">
                  <?php foreach (['Ontario','British Columbia','Alberta','Quebec','Nova Scotia',
                    'Manitoba','Saskatchewan','New Brunswick','PEI','Newfoundland'] as $p): ?>
                    <option <?= ($editing['province'] ?? '') === $p ? 'selected' : '' ?>><?= $p ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
            </div>
            <div class="field">
              <label>Sprachen</label>
              <input type="text" name="languages"
                value="<?= htmlspecialchars($editing['languages'] ?? 'Deutsch, Englisch') ?>">
            </div>
            <div class="field">
              <label>Spezialisierungen</label>
              <textarea name="specialties"><?= htmlspecialchars($editing['specialties'] ?? '') ?></textarea>
            </div>
            <div class="field">
              <label>E-Mail</label>
              <input type="email" name="email"
                value="<?= htmlspecialchars($editing['email'] ?? '') ?>">
            </div>
            <div class="field">
              <label>Website</label>
              <input type="text" name="website"
                value="<?= htmlspecialchars($editing['website'] ?? '') ?>"
                placeholder="https://...">
            </div>
            <div class="field">
              <label>RCIC-Nummer <span class="sub">aus ICCRC-Register</span></label>
              <input type="text" name="rcic_number"
                value="<?= htmlspecialchars($editing['rcic_number'] ?? '') ?>"
                placeholder="z.B. R123456">
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
              <div class="field">
                <label>Reihenfolge <span class="sub">1 = zuerst</span></label>
                <input type="number" name="sort_order" min="0" max="99"
                  value="<?= (int)($editing['sort_order'] ?? 0) ?>">
              </div>
              <div class="field" style="padding-top:24px;">
                <label class="check-row">
                  <input type="checkbox" name="active" value="1"
                    <?= ($editing['active'] ?? 1) ? 'checked' : '' ?>>
                  Aktiv (in E-Mail anzeigen)
                </label>
              </div>
            </div>
            <div class="field">
              <label>Interne Notizen</label>
              <textarea name="notes"><?= htmlspecialchars($editing['notes'] ?? '') ?></textarea>
            </div>

            <div class="form-actions">
              <button type="submit" class="btn-save">
                <?= $editing ? '✓ Speichern' : '+ Hinzufügen' ?>
              </button>
              <a href="rcic.php" class="btn-cancel">Abbrechen</a>
            </div>
          </form>
        <?php endif; ?>
      </div>
    </div>
  </div>

</div>
</body>
</html>
