<?php
require_once __DIR__ . '/../config.php';
adminGuard();
requireCsrf();  // reject POSTs without a valid CSRF token
require_once __DIR__ . '/_layout.php';

$db      = db();
$adminId = (int)$_SESSION['admin_id'];
$msg     = '';
$error   = '';

// Load admin row
$row = $db->prepare('SELECT * FROM admins WHERE id=?');
$row->execute([$adminId]);
$admin = $row->fetch();

// ── Save profile ────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_profile'])) {
    $name    = trim($_POST['name'] ?? '');
    $email   = trim($_POST['email'] ?? '');
    $orgName = trim($_POST['org_name'] ?? '') ?: null;

    if (!$name || !$email) {
        $error = 'Name and email are required.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Invalid email address.';
    } else {
        $dup = $db->prepare('SELECT id FROM admins WHERE email=? AND id!=?');
        $dup->execute([$email, $adminId]);
        if ($dup->fetch()) {
            $error = 'That email is already used by another account.';
        } else {
            $db->prepare('UPDATE admins SET name=?, email=?, org_name=? WHERE id=?')
               ->execute([$name, $email, $orgName, $adminId]);
            $_SESSION['admin_name'] = $name;
            $msg = 'Profile updated.';
            // Refresh
            $row->execute([$adminId]);
            $admin = $row->fetch();
        }
    }
}

// ── Change password ─────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    $current = $_POST['current_password'] ?? '';
    $new1    = $_POST['new_password'] ?? '';
    $new2    = $_POST['new_password_confirm'] ?? '';

    if (!password_verify($current, $admin['password'])) {
        $error = 'Current password is incorrect.';
    } elseif (strlen($new1) < 8) {
        $error = 'New password must be at least 8 characters.';
    } elseif ($new1 !== $new2) {
        $error = 'New passwords do not match.';
    } else {
        $hash = password_hash($new1, PASSWORD_BCRYPT);
        $db->prepare('UPDATE admins SET password=? WHERE id=?')->execute([$hash, $adminId]);
        adminLog('admin.password_change', 'admin', $adminId);
        $msg = 'Password changed successfully.';
    }
}

// ── Save WhatsApp settings ──────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_whatsapp'])) {
    $provider = in_array($_POST['wa_provider'] ?? '', ['manual','cloud','twilio']) ? $_POST['wa_provider'] : 'manual';

    // Secrets: only overwrite when a new value is supplied (blank keeps existing).
    $sets   = ['wa_provider=?', 'wa_phone_id=?', 'twilio_sid=?', 'twilio_from=?', 'twilio_active=?'];
    $params = [
        $provider,
        trim($_POST['wa_phone_id'] ?? '') ?: null,
        trim($_POST['twilio_sid']  ?? '') ?: null,
        trim($_POST['twilio_from'] ?? '') ?: null,
        $provider === 'twilio' ? 1 : 0,
    ];
    if (trim($_POST['wa_token'] ?? '') !== '')     { $sets[] = 'wa_token=?';     $params[] = trim($_POST['wa_token']); }
    if (trim($_POST['twilio_token'] ?? '') !== '') { $sets[] = 'twilio_token=?'; $params[] = trim($_POST['twilio_token']); }
    $params[] = $adminId;
    $db->prepare('UPDATE admins SET ' . implode(',', $sets) . ' WHERE id=?')->execute($params);
    adminLog('settings.whatsapp', 'admin', $adminId, $provider);
    $msg = 'WhatsApp settings saved.';
    $row->execute([$adminId]);
    $admin = $row->fetch();
}

// ── Save SMTP settings ──────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_smtp'])) {
    $smtpPass = trim($_POST['smtp_pass'] ?? '');
    $passCol  = $smtpPass !== '' ? ', smtp_pass=?' : '';
    $params   = [
        trim($_POST['smtp_host']   ?? '') ?: null,
        (int)($_POST['smtp_port']  ?? 587),
        trim($_POST['smtp_user']   ?? '') ?: null,
        trim($_POST['smtp_from']   ?? '') ?: null,
        trim($_POST['smtp_name']   ?? '') ?: null,
        in_array($_POST['smtp_secure'] ?? '', ['tls','ssl','none']) ? $_POST['smtp_secure'] : 'tls',
    ];
    if ($smtpPass !== '') $params[] = $smtpPass;
    $params[] = $adminId;
    $db->prepare("UPDATE admins SET smtp_host=?,smtp_port=?,smtp_user=?,smtp_from=?,smtp_name=?,smtp_secure=?{$passCol} WHERE id=?")
       ->execute($params);
    $msg = 'SMTP settings saved.';
    $row->execute([$adminId]);
    $admin = $row->fetch();
}

// ── Test SMTP ───────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['test_smtp'])) {
    $testTo = trim($_POST['test_to'] ?? $admin['email']);
    $html   = buildEmailHtml('Test User', 'RSVP System',
                             'Your SMTP configuration is working correctly.');
    $ok = sendMail($admin, $testTo, 'RSVP System — SMTP Test ✓', $html);
    if ($ok) $msg   = "Test email sent to {$testTo}.";
    else     $error = 'Test failed. Check SMTP settings below.';
}

layout_start('Account Settings', '');
?>

<?php if ($msg): ?><div class="alert alert-success"><?= htmlspecialchars($msg) ?></div><?php endif; ?>
<?php if ($error): ?><div class="alert alert-danger"><?= htmlspecialchars($error) ?></div><?php endif; ?>

<div class="page-header">
  <div>
    <div class="page-header-sub">Admin</div>
    <h1>Account Settings</h1>
  </div>
</div>

<!-- ── Profile ─────────────────────────────────────────────── -->
<div class="card mb-4" style="max-width:640px">
  <div class="label-ui mb-3">Profile</div>
  <form method="POST">
    <div class="grid-2">
      <div class="form-group">
        <label class="form-label">Full Name *</label>
        <input class="form-control" type="text" name="name"
               value="<?= htmlspecialchars($admin['name']) ?>" required>
      </div>
      <div class="form-group">
        <label class="form-label">Email Address *</label>
        <input class="form-control" type="email" name="email"
               value="<?= htmlspecialchars($admin['email']) ?>" required>
      </div>
    </div>
    <div class="form-group">
      <label class="form-label">Organisation / Brand Name</label>
      <input class="form-control" type="text" name="org_name"
             value="<?= htmlspecialchars($admin['org_name'] ?? '') ?>"
             placeholder="Used as the sender name in emails">
    </div>
    <button class="btn btn-gold" name="save_profile" type="submit">Save Profile</button>
  </form>
</div>

<!-- ── Change Password ─────────────────────────────────────── -->
<div class="card mb-4" style="max-width:640px">
  <div class="label-ui mb-3">Change Password</div>
  <form method="POST">
    <div class="form-group">
      <label class="form-label">Current Password</label>
      <input class="form-control" type="password" name="current_password"
             autocomplete="current-password" required>
    </div>
    <div class="grid-2">
      <div class="form-group">
        <label class="form-label">New Password</label>
        <input class="form-control" type="password" name="new_password"
               autocomplete="new-password" placeholder="Min 6 characters" required>
      </div>
      <div class="form-group">
        <label class="form-label">Confirm New Password</label>
        <input class="form-control" type="password" name="new_password_confirm"
               autocomplete="new-password" required>
      </div>
    </div>
    <button class="btn btn-outline" name="change_password" type="submit">Change Password</button>
  </form>
</div>

<!-- ── Sending & integrations (advanced) ───────────────────── -->
<details class="card mb-4" style="max-width:640px;padding:0">
  <summary style="cursor:pointer;padding:20px 28px;font-family:var(--font-ui);font-size:.8rem;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--gold);list-style:none">
    Sending &amp; integrations
    <span class="text-muted" style="font-weight:400;text-transform:none;letter-spacing:0;font-family:var(--font-body);font-size:.82rem"> — email &amp; WhatsApp delivery (advanced)</span>
  </summary>
  <div style="padding:0 28px 8px">

<!-- ── WhatsApp Settings ───────────────────────────────────── -->
<div class="card mb-4" style="max-width:640px;border:none;padding-left:0;padding-right:0">
  <div class="label-ui mb-1">WhatsApp Delivery</div>
  <p class="text-muted text-sm" style="margin-bottom:20px">
    <strong>Manual</strong> opens WhatsApp with a pre-filled message (you tap send).
    <strong>Cloud API</strong> sends invites automatically via Meta's WhatsApp Cloud API.
  </p>
  <form method="POST">
    <div class="form-group">
      <label class="form-label">Send Mode</label>
      <select class="form-control" name="wa_provider" style="width:260px" id="wa-provider" onchange="waToggle()">
        <?php foreach (['manual'=>'Manual (wa.me links)','cloud'=>'Meta Cloud API (automatic)','twilio'=>'Twilio (automatic)'] as $v=>$lbl): ?>
          <option value="<?= $v ?>" <?= ($admin['wa_provider'] ?? 'manual') === $v ? 'selected' : '' ?>><?= $lbl ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <!-- Meta Cloud API fields -->
    <div id="wa-cloud" class="grid-2">
      <div class="form-group">
        <label class="form-label">Cloud API Phone Number ID</label>
        <input class="form-control" type="text" name="wa_phone_id"
               value="<?= htmlspecialchars($admin['wa_phone_id'] ?? '') ?>" placeholder="e.g. 123456789012345">
      </div>
      <div class="form-group">
        <label class="form-label">Cloud API Access Token</label>
        <input class="form-control" type="password" name="wa_token"
               autocomplete="new-password" placeholder="<?= !empty($admin['wa_token']) ? '•••••• (leave blank to keep)' : 'Permanent access token' ?>">
      </div>
      <div class="form-hint" style="grid-column:1/-1">From Meta ▸ WhatsApp ▸ API Setup (use a permanent/system-user token).</div>
    </div>

    <!-- Twilio fields -->
    <div id="wa-twilio">
      <div class="grid-2">
        <div class="form-group">
          <label class="form-label">Twilio Account SID</label>
          <input class="form-control" type="text" name="twilio_sid"
                 value="<?= htmlspecialchars($admin['twilio_sid'] ?? '') ?>" placeholder="ACxxxxxxxx">
        </div>
        <div class="form-group">
          <label class="form-label">Twilio Auth Token</label>
          <input class="form-control" type="password" name="twilio_token"
                 autocomplete="new-password" placeholder="<?= !empty($admin['twilio_token']) ? '•••••• (leave blank to keep)' : 'Auth token' ?>">
        </div>
      </div>
      <div class="form-group">
        <label class="form-label">Twilio WhatsApp Sender Number</label>
        <input class="form-control" type="text" name="twilio_from" style="width:220px"
               value="<?= htmlspecialchars($admin['twilio_from'] ?? '') ?>" placeholder="+14155238886">
      </div>
      <div class="form-hint">From the Twilio console. Use the WhatsApp-enabled sender number (with country code).</div>
    </div>

    <button class="btn btn-gold" name="save_whatsapp" type="submit" style="margin-top:14px">Save WhatsApp Settings</button>
  </form>
  <script>
    function waToggle() {
      var p = document.getElementById('wa-provider').value;
      document.getElementById('wa-cloud').style.display  = (p === 'cloud')  ? '' : 'none';
      document.getElementById('wa-twilio').style.display = (p === 'twilio') ? '' : 'none';
    }
    waToggle();
  </script>
</div>

<!-- ── SMTP Settings ───────────────────────────────────────── -->
<div class="card mb-4" style="max-width:640px">
  <div class="label-ui mb-1">Email / SMTP Settings</div>
  <p class="text-muted text-sm" style="margin-bottom:20px">
    Used for sending ticket emails and invite notifications.
    Leave blank to use PHP's built-in <code>mail()</code> function.
  </p>
  <form method="POST">
    <div class="grid-2">
      <div class="form-group">
        <label class="form-label">SMTP Host</label>
        <input class="form-control" type="text" name="smtp_host"
               value="<?= htmlspecialchars($admin['smtp_host'] ?? '') ?>"
               placeholder="smtp.gmail.com">
      </div>
      <div class="form-group">
        <label class="form-label">SMTP Port</label>
        <input class="form-control" type="number" name="smtp_port"
               value="<?= (int)($admin['smtp_port'] ?? 587) ?>"
               placeholder="587">
      </div>
    </div>
    <div class="grid-2">
      <div class="form-group">
        <label class="form-label">SMTP Username</label>
        <input class="form-control" type="text" name="smtp_user"
               value="<?= htmlspecialchars($admin['smtp_user'] ?? '') ?>"
               autocomplete="off" placeholder="your@email.com">
      </div>
      <div class="form-group">
        <label class="form-label">SMTP Password</label>
        <input class="form-control" type="password" name="smtp_pass"
               autocomplete="new-password" placeholder="Leave blank to keep current">
      </div>
    </div>
    <div class="grid-2">
      <div class="form-group">
        <label class="form-label">From Email</label>
        <input class="form-control" type="email" name="smtp_from"
               value="<?= htmlspecialchars($admin['smtp_from'] ?? '') ?>"
               placeholder="noreply@yourdomain.com">
      </div>
      <div class="form-group">
        <label class="form-label">From Name</label>
        <input class="form-control" type="text" name="smtp_name"
               value="<?= htmlspecialchars($admin['smtp_name'] ?? '') ?>"
               placeholder="RSVP System">
      </div>
    </div>
    <div class="form-group">
      <label class="form-label">Encryption</label>
      <select class="form-control" name="smtp_secure" style="width:160px">
        <?php foreach (['tls','ssl','none'] as $s): ?>
          <option value="<?= $s ?>" <?= ($admin['smtp_secure'] ?? 'tls') === $s ? 'selected' : '' ?>><?= strtoupper($s) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <button class="btn btn-gold" name="save_smtp" type="submit">Save SMTP</button>
  </form>

  <!-- Test SMTP -->
  <div style="margin-top:24px;padding-top:20px;border-top:1px solid var(--border)">
    <div class="label-ui mb-2">Send Test Email</div>
    <form method="POST" style="display:flex;gap:8px;align-items:flex-end">
      <div class="form-group" style="flex:1;margin-bottom:0">
        <label class="form-label">Recipient</label>
        <input class="form-control" type="email" name="test_to"
               value="<?= htmlspecialchars($admin['email']) ?>" required>
      </div>
      <button class="btn btn-outline" name="test_smtp" type="submit">Send Test</button>
    </form>
  </div>
</div>

  </div>
</details>
<!-- ── Account Info ────────────────────────────────────────── -->
<div class="card card-sm" style="max-width:640px">
  <div class="label-ui mb-2">Account Info</div>
  <table style="font-size:.85rem;width:100%">
    <tr>
      <td class="text-muted" style="padding:5px 0;width:140px">Role</td>
      <td>
        <?php if (isSuperAdmin()): ?>
          <span class="badge badge-gold">Super Admin</span>
        <?php else: ?>
          <span class="badge badge-muted">Admin</span>
        <?php endif; ?>
      </td>
    </tr>
    <?php if (!isSuperAdmin()): ?>
    <tr>
      <td class="text-muted" style="padding:5px 0">Event Limit</td>
      <td><?= $admin['max_events'] !== null ? (int)$admin['max_events'] : '<span class="text-muted">Unlimited</span>' ?></td>
    </tr>
    <tr>
      <td class="text-muted" style="padding:5px 0">Guest Limit/Event</td>
      <td><?= $admin['max_guests'] !== null ? (int)$admin['max_guests'] : '<span class="text-muted">Unlimited</span>' ?></td>
    </tr>
    <?php endif; ?>
    <tr>
      <td class="text-muted" style="padding:5px 0">Member Since</td>
      <td><?= date('F j, Y', strtotime($admin['created_at'])) ?></td>
    </tr>
  </table>
</div>

<?php layout_end(); ?>
