<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
auth_require_admin();

$step_id = (int)($_GET['id'] ?? 0);
$action  = $_GET['action'] ?? 'edit';
$is_add  = ($action === 'add');

$step   = null;
$errors = [];

if (!$is_add) {
    $step = db_row('SELECT * FROM journey_steps WHERE id=:id', ['id'=>$step_id]);
    if (!$step) { http_response_code(404); echo 'Step not found.'; exit; }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $tier        = trim($_POST['tier']        ?? '');
    $name        = trim($_POST['name']        ?? '');
    $description = trim($_POST['description'] ?? '');
    $sort_order  = (int)($_POST['sort_order'] ?? 0);

    if (!in_array($tier, ['Bronze','Silver','Gold','Platinum','Diamond'], true)) {
        $errors[] = 'Pick a valid tier.';
    }
    if (!$name) $errors[] = 'Step name is required.';

    if (empty($errors)) {
        $data = [
            'tier' => $tier,
            'name' => $name,
            'description' => $description ?: null,
            'sort_order' => $sort_order,
            'active' => 1,
        ];
        if ($is_add) {
            db_insert('journey_steps', $data);
        } else {
            db_update('journey_steps', $step_id, $data);
        }
        header('Location: journey-templates.php?msg=saved'); exit;
    }
    $step = array_merge($step ?? [], [
        'tier'=>$tier,'name'=>$name,'description'=>$description,'sort_order'=>$sort_order,
    ]);
}

if ($is_add && $_SERVER['REQUEST_METHOD'] === 'GET') {
    $tier_pref = $_GET['tier'] ?? '';
    $next_order = 1;
    if ($tier_pref) {
        $next_order = (int)db_value(
            'SELECT COALESCE(MAX(sort_order),0)+1 FROM journey_steps WHERE tier=:t',
            ['t'=>$tier_pref]
        );
    }
    $step = ['tier'=>$tier_pref,'name'=>'','description'=>'','sort_order'=>$next_order];
}

$page_title = $is_add ? 'New step' : 'Edit — ' . ($step['name'] ?? '');
require __DIR__ . '/_guard.php';
?>

<style>
.b-card{background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:1.5rem;max-width:620px;}
</style>

<section class="section">
<div class="container">

<p class="muted" style="margin:0;"><a href="journey-templates.php">← Journey templates</a></p>
<h1 style="margin:.25rem 0 1.25rem;"><?= $is_add ? 'Add a step' : 'Edit step' ?></h1>

<?php if (!empty($errors)): ?>
    <div class="alert alert-error" style="max-width:620px;margin-bottom:1rem;">
        <?= implode('<br>', array_map('htmlspecialchars', $errors)) ?>
    </div>
<?php endif; ?>

<form method="post" action="journey-template-edit.php?<?= $is_add?'action=add':'id='.$step_id ?>"
      class="b-card">
    <?= csrf_field() ?>

    <label>Tier *</label>
    <select name="tier" required>
        <option value="">— choose —</option>
        <?php foreach (['Bronze','Silver','Gold','Platinum','Diamond'] as $t): ?>
            <option value="<?= $t ?>" <?= ($step['tier'] ?? '')===$t?'selected':'' ?>><?= $t ?></option>
        <?php endforeach; ?>
    </select>

    <label>Step name *</label>
    <input type="text" name="name" required maxlength="150"
           value="<?= htmlspecialchars($step['name'] ?? '') ?>"
           placeholder="e.g. Interview Owner">

    <label>Description <small>(optional, shown under the step name)</small></label>
    <textarea name="description" rows="3" maxlength="500"
              placeholder="Short description of what this step involves."><?= htmlspecialchars($step['description'] ?? '') ?></textarea>

    <label>Sort order</label>
    <input type="number" name="sort_order" value="<?= (int)($step['sort_order'] ?? 0) ?>">
    <p class="muted" style="font-size:.78rem;margin-top:-.5rem;">
        Lower numbers run earlier. Or drag-drop on the templates page.
    </p>

    <div style="display:flex;gap:.75rem;margin-top:1rem;">
        <button type="submit" class="btn"><?= $is_add ? 'Create step' : 'Save changes' ?></button>
        <a href="journey-templates.php" class="btn btn-outline">Cancel</a>
    </div>
</form>

</div>
</section>

<?php require __DIR__ . '/_footer.php'; ?>