<?php

require_once __DIR__ . '/includes/settings_helpers.php';

settings_require_auth();
settings_ensure_tables($conn);

$org = settings_get_current_org($conn);
$orgId = (int) ($org['id'] ?? 0);
$mode = trim((string) ($_GET['action'] ?? 'list'));
$errors = [];
$flash = settings_flash_message();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['webhook_action'] ?? '') === 'create') {
    $name = trim((string) ($_POST['name'] ?? ''));
    $description = trim((string) ($_POST['description'] ?? ''));
    $scriptBody = trim((string) ($_POST['script_body'] ?? ''));

    if ($name === '') {
        $errors[] = 'Webhook name is required.';
    }
    if ($scriptBody === '') {
        $errors[] = 'Script body is required.';
    }

    if (!$errors && settings_add_webhook($conn, $orgId, $name, $description, $scriptBody)) {
        settings_set_flash('success', 'Incoming webhook created successfully.');
        header('Location: incoming_webhooks.php');
        exit();
    } elseif (!$errors) {
        $errors[] = 'Unable to save incoming webhook.';
    }
    $mode = 'new';
}

$webhooks = settings_get_webhooks($conn, $orgId);
$defaultScript = "//This is a sample function.\nresultMap = Map();\nresultMap.put(\"message\", \"Success\");\nresultMap.put(\"code\", 0);\nreturn resultMap;";
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Incoming Webhooks | Settings</title>
  <link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
  <link rel="stylesheet" href="assets/font-inter.css">
  <link rel="stylesheet" href="orgprofile.css">
  <style>
    .hero-empty{padding:70px 24px;text-align:center;color:#475569;}
    .hero-empty h2{margin:14px 0 10px;font-size:20px;color:#111827;}
    .hero-empty .save-btn{margin-top:16px;}
    .hook-form input,.hook-form textarea{width:100%;border:1px solid var(--border);border-radius:10px;padding:12px;font-size:14px;}
    .hook-form textarea{min-height:340px;font-family:Consolas, monospace;white-space:pre;resize:vertical;}
    .hook-grid{display:grid;gap:14px;}
    .hook-table{width:100%;border-collapse:collapse;}
    .hook-table th,.hook-table td{padding:14px 0;border-top:1px solid var(--border);text-align:left;}
    .ghost-btn{display:inline-flex;align-items:center;justify-content:center;padding:10px 16px;border-radius:10px;border:1px solid var(--border);background:#fff;color:#334155;text-decoration:none;font-weight:700;}
  </style>
</head>
<body class="orgprofile-page">
  <?php settings_render_header($_SESSION['org_name'] ?? 'demo', 'dashboard.php', 'fa-webhook'); ?>

  <main class="profile-layout">
    <?php settings_render_sidebar('incoming_webhooks'); ?>

    <section class="profile-main">
      <div class="profile-head">
        <h1><?php echo $mode === 'new' ? 'New Incoming Webhook' : 'Incoming Webhooks'; ?></h1>
        <div class="toolbar-actions">
          <?php if ($mode === 'new'): ?>
            <a class="ghost-btn" href="incoming_webhooks.php">Back</a>
          <?php else: ?>
            <a class="save-btn" href="incoming_webhooks.php?action=new">+ Add New</a>
          <?php endif; ?>
        </div>
      </div>

      <div class="profile-card">
        <?php if (!empty($flash['message'])): ?>
          <div class="alert-ok"><?php echo htmlspecialchars($flash['message']); ?></div>
        <?php endif; ?>

        <?php if ($mode === 'new'): ?>
          <?php if ($errors): ?>
            <div class="alert-err">
              <div class="alert-err-title">Please fix the following:</div>
              <ul>
                <?php foreach ($errors as $error): ?>
                  <li><?php echo htmlspecialchars($error); ?></li>
                <?php endforeach; ?>
              </ul>
            </div>
          <?php endif; ?>
          <form class="hook-form" method="POST">
            <input type="hidden" name="webhook_action" value="create">
            <div class="hook-grid">
              <div>
                <label>Name <span class="req">*</span></label>
                <input type="text" name="name" value="<?php echo htmlspecialchars((string) ($_POST['name'] ?? '')); ?>" required>
              </div>
              <div>
                <label>Description</label>
                <textarea name="description" style="min-height:88px;font-family:inherit;white-space:normal;"><?php echo htmlspecialchars((string) ($_POST['description'] ?? '')); ?></textarea>
              </div>
              <div>
                <label>Script <span class="req">*</span></label>
                <textarea name="script_body" required><?php echo htmlspecialchars((string) ($_POST['script_body'] ?? $defaultScript)); ?></textarea>
              </div>
            </div>
            <div class="action-row" style="display:flex;gap:12px;margin-top:18px;">
              <button class="save-btn" type="submit">Save</button>
              <a class="ghost-btn" href="incoming_webhooks.php">Cancel</a>
            </div>
          </form>
        <?php elseif ($webhooks): ?>
          <table class="hook-table">
            <thead>
              <tr>
                <th>Name</th>
                <th>Description</th>
                <th>Status</th>
                <th>Created</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($webhooks as $webhook): ?>
                <tr>
                  <td><?php echo htmlspecialchars($webhook['name']); ?></td>
                  <td><?php echo htmlspecialchars((string) $webhook['description']); ?></td>
                  <td><?php echo htmlspecialchars(strtoupper((string) $webhook['status'])); ?></td>
                  <td><?php echo htmlspecialchars((string) $webhook['created_at']); ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        <?php else: ?>
          <div class="hero-empty">
            <div style="font-size:88px;color:#c7d2fe;"><i class="fa-solid fa-code-branch"></i></div>
            <h2>You haven't created any Incoming Webhooks yet</h2>
            <p>Incoming Webhooks allow you to receive information from other applications, so you can automate your payroll workflows and save time.</p>
            <a class="save-btn" href="incoming_webhooks.php?action=new">+ Add Incoming Webhooks</a>
          </div>
        <?php endif; ?>
      </div>
    </section>
  </main>
</body>
</html>
