<?php
require_once __DIR__ . '/header.php';
require_login();

$user    = current_user();
$isSuper = perms_is_super($user);
if (!perms_can_manage_forms($user)) { http_response_code(403); echo 'Forbidden'; exit; }
$formId  = v_int($_GET['id'] ?? 0, 1);

if ($formId <= 0) {
    echo '<div class="alert alert-danger">Form not found.</div>';
    require __DIR__ . '/footer.php';
    exit;
}

$stmt = $pdo->prepare('SELECT * FROM forms WHERE id = ? AND deleted_at IS NULL');
$stmt->execute([$formId]);
$form = $stmt->fetch();
if (!$form) {
    echo '<div class="alert alert-danger">Form not found.</div>';
    require __DIR__ . '/footer.php';
    exit;
}

// scoping: facility users can only edit own/global forms
if (!$isSuper && $form['facility_id'] !== null && (int)$form['facility_id'] !== (int)$user['facility_id']) {
    echo '<div class="alert alert-danger">You do not have permission to edit this form.</div>';
    require __DIR__ . '/footer.php';
    exit;
}

$msg = '';
$err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_require();

    if (isset($_POST['save_meta'])) {
        $name     = v_clean_string($_POST['name'] ?? '', 100);
        $desc     = v_clean_string($_POST['description'] ?? '', 2000);
        $duration = v_int($_POST['default_duration_minutes'] ?? 8, 0, 60, 8);
        if ($name === '') {
            $err = 'Form name is required.';
        } else {
            $pdo->prepare('UPDATE forms SET name=?, description=?, default_duration_minutes=? WHERE id=?')
                ->execute([$name, $desc, $duration, $formId]);
            audit_log($pdo, 'form_meta_update', ['form_id' => $formId, 'name' => $name, 'duration' => $duration]);
            $form['name']                     = $name;
            $form['description']              = $desc;
            $form['default_duration_minutes'] = $duration;
            $msg = 'Form details saved.';
        }
    }

    if (isset($_POST['save_items'])) {
        $labels   = $_POST['label']      ?? [];
        $maxes    = $_POST['max_score']  ?? [];
        $comments = $_POST['has_comment'] ?? [];

        try {
            $pdo->beginTransaction();
            $pdo->prepare('DELETE FROM form_items WHERE form_id = ?')->execute([$formId]);
            $ins = $pdo->prepare('INSERT INTO form_items (form_id, label, max_score, has_comment, sort_order) VALUES (?, ?, ?, ?, ?)');
            $order = 1;
            foreach ($labels as $idx => $label) {
                $text = trim((string)$label);
                if ($text === '') continue;
                $max = max(1, v_int($maxes[$idx] ?? 1, 1, 100, 1));
                $hasComment = isset($comments[$idx]) ? 1 : 0;
                $ins->execute([$formId, $text, $max, $hasComment, $order++]);
            }
            $pdo->commit();
            audit_log($pdo, 'form_items_update', ['form_id' => $formId]);
            $msg = 'Items saved.';
        } catch (Throwable $e) {
            $pdo->rollBack();
            $err = 'Could not save items.';
            error_log('form_items_update: ' . $e->getMessage());
        }
    }

    if (isset($_POST['save_bands'])) {
        $labels = $_POST['band_label'] ?? [];
        $mins   = $_POST['band_min']   ?? [];
        $maxs   = $_POST['band_max']   ?? [];

        try {
            $pdo->beginTransaction();
            $pdo->prepare('DELETE FROM grade_bands WHERE form_id = ?')->execute([$formId]);
            $ins = $pdo->prepare('INSERT INTO grade_bands (form_id, label, min_percent, max_percent, sort_order) VALUES (?, ?, ?, ?, ?)');
            $order = 1;
            foreach ($labels as $i => $label) {
                $text = trim((string)$label);
                if ($text === '') continue;
                $min = max(0.0, min(100.0, (float)($mins[$i] ?? 0)));
                $max = max(0.0, min(100.0, (float)($maxs[$i] ?? 100)));
                if ($max < $min) [$min, $max] = [$max, $min];
                $ins->execute([$formId, $text, $min, $max, $order++]);
            }
            $pdo->commit();
            audit_log($pdo, 'form_bands_update', ['form_id' => $formId]);
            $msg = 'Grade bands saved.';
        } catch (Throwable $e) {
            $pdo->rollBack();
            $err = 'Could not save grade bands.';
            error_log('form_bands_update: ' . $e->getMessage());
        }
    }
}

$items = $pdo->prepare('SELECT * FROM form_items WHERE form_id = ? ORDER BY sort_order');
$items->execute([$formId]);
$items = $items->fetchAll();

$bands = $pdo->prepare('SELECT * FROM grade_bands WHERE form_id = ? ORDER BY sort_order');
$bands->execute([$formId]);
$bands = $bands->fetchAll();
?>
<h2>Edit Form: <?php echo h($form['name']); ?></h2>

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

<h3>Station Details</h3>
<form method="post" class="mb-2">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="save_meta" value="1">
    <div class="form-row">
        <div class="field"><label>Form / Station Name</label><input type="text" name="name" value="<?php echo h($form['name']); ?>" required></div>
        <div class="field">
            <label>Default Station Duration (minutes)</label>
            <input type="number" name="default_duration_minutes"
                   min="0" max="60"
                   value="<?php echo (int)($form['default_duration_minutes'] ?? 8); ?>">
            <small class="muted">This is auto-loaded when an examiner opens this station. Set 0 for "no timer".</small>
        </div>
    </div>
    <div class="field mb-2"><label>Description</label><textarea name="description" rows="2"><?php echo h($form['description'] ?? ''); ?></textarea></div>
    <button type="submit" class="btn btn-primary">Save Details</button>
</form>

<h3>Checklist Items</h3>
<form method="post">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="save_items" value="1">
    <div class="table-wrap">
    <table class="data">
        <thead><tr><th>#</th><th>Item Label</th><th>Max Score</th><th>Comment Box?</th></tr></thead>
        <tbody>
        <?php
        $rows = max(count($items) + 3, 8);
        for ($i = 0; $i < $rows; $i++):
            $item = $items[$i] ?? null;
        ?>
            <tr>
                <td data-label="#"><?php echo $i + 1; ?></td>
                <td data-label="Item">
                    <textarea name="label[]" rows="2"><?php echo $item ? h($item['label']) : ''; ?></textarea>
                </td>
                <td data-label="Max">
                    <input type="number" name="max_score[]" min="1" max="100" value="<?php echo $item ? (int)$item['max_score'] : 1; ?>" style="max-width:90px;">
                </td>
                <td data-label="Comment">
                    <input type="checkbox" name="has_comment[<?php echo $i; ?>]" <?php if ($item && $item['has_comment']) echo 'checked'; ?>>
                </td>
            </tr>
        <?php endfor; ?>
        </tbody>
    </table>
    </div>
    <button type="submit" class="btn btn-primary mt-2">Save Items</button>
</form>

<h3 class="mt-3">Grade Bands (Final Grade)</h3>
<form method="post">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="save_bands" value="1">
    <div class="table-wrap">
    <table class="data">
        <thead><tr><th>#</th><th>Label</th><th>Min %</th><th>Max %</th></tr></thead>
        <tbody>
        <?php
        $rows = max(count($bands) + 2, 5);
        for ($i = 0; $i < $rows; $i++):
            $b = $bands[$i] ?? null;
        ?>
            <tr>
                <td data-label="#"><?php echo $i + 1; ?></td>
                <td data-label="Label"><input type="text" name="band_label[]" value="<?php echo $b ? h($b['label']) : ''; ?>"></td>
                <td data-label="Min %"><input type="number" step="0.01" name="band_min[]" value="<?php echo $b ? h($b['min_percent']) : ''; ?>"></td>
                <td data-label="Max %"><input type="number" step="0.01" name="band_max[]" value="<?php echo $b ? h($b['max_percent']) : ''; ?>"></td>
            </tr>
        <?php endfor; ?>
        </tbody>
    </table>
    </div>
    <button type="submit" class="btn btn-primary mt-2">Save Grade Bands</button>
</form>

<?php require __DIR__ . '/footer.php'; ?>
