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

$user       = current_user();
$isSuper    = perms_is_super($user);
$facilityId = $user['facility_id'];

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_form'])) {
    csrf_require();
    $name = v_clean_string($_POST['name'] ?? '', 100);
    $desc = v_clean_string($_POST['description'] ?? '', 1000);
    $dur  = v_int($_POST['default_duration_minutes'] ?? 8, 0, 60, 8);
    $facId = $isSuper ? v_int($_POST['facility_id'] ?? 0, 0) : (int)$facilityId;

    if ($name === '') {
        $err = 'Form name is required.';
    } else {
        try {
            $pdo->beginTransaction();
            $pdo->prepare('INSERT INTO forms (facility_id, name, description, default_duration_minutes, created_by) VALUES (?, ?, ?, ?, ?)')
                ->execute([$facId ?: null, $name, $desc, $dur, $user['id']]);
            $formId = (int)$pdo->lastInsertId();
            $bands = [
                ['Poor',                 0.00,  49.99],
                ['Below expectation',    50.00, 64.99],
                ['Meets expectation',    65.00, 74.99],
                ['Above expectation',    75.00, 84.99],
                ['Exceeds expectation',  85.00, 100.00],
            ];
            $ins = $pdo->prepare('INSERT INTO grade_bands (form_id, label, min_percent, max_percent, sort_order) VALUES (?, ?, ?, ?, ?)');
            $order = 1;
            foreach ($bands as $b) $ins->execute([$formId, $b[0], $b[1], $b[2], $order++]);
            $pdo->commit();
            audit_log($pdo, 'form_create', ['id' => $formId, 'name' => $name]);
            header('Location: form_edit.php?id=' . $formId);
            exit;
        } catch (Throwable $e) {
            $pdo->rollBack();
            $err = 'Could not create form.';
            error_log('form_create: ' . $e->getMessage());
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_form'])) {
    csrf_require();
    $id = v_int($_POST['delete_form'], 1);
    $check = $pdo->prepare('SELECT facility_id FROM forms WHERE id = ?');
    $check->execute([$id]); $row = $check->fetch();
    if ($row && perms_owns_facility($user, $row['facility_id'])) {
        $pdo->prepare('UPDATE forms SET deleted_at = NOW() WHERE id = ?')->execute([$id]);
        audit_log($pdo, 'form_soft_delete', ['id' => $id]);
        $msg = 'Form moved to trash.';
    } else { $err = 'Permission denied.'; }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['restore_form'])) {
    csrf_require();
    $id = v_int($_POST['restore_form'], 1);
    $check = $pdo->prepare('SELECT facility_id FROM forms WHERE id = ?');
    $check->execute([$id]); $row = $check->fetch();
    if ($row && perms_owns_facility($user, $row['facility_id'])) {
        $pdo->prepare('UPDATE forms SET deleted_at = NULL WHERE id = ?')->execute([$id]);
        audit_log($pdo, 'form_restore', ['id' => $id]);
        $msg = 'Form restored.';
    }
}

$facilities = $isSuper ? $pdo->query('SELECT * FROM facilities WHERE deleted_at IS NULL ORDER BY name')->fetchAll() : [];

$showDeleted = isset($_GET['show_deleted']) && $_GET['show_deleted'] === '1';
$params = [];
$sql = 'SELECT f.*, fac.name AS facility_name, fac.code AS facility_code FROM forms f LEFT JOIN facilities fac ON f.facility_id = fac.id WHERE 1=1';
if (!$showDeleted) $sql .= ' AND f.deleted_at IS NULL';
if (!$isSuper && $facilityId) {
    $sql .= ' AND (f.facility_id IS NULL OR f.facility_id = ?)';
    $params[] = $facilityId;
}
$sql .= ' ORDER BY f.created_at DESC';
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$forms = $stmt->fetchAll();
?>
<h2>OSCE Forms (Checklists)</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>Create New Form</h3>
<form method="post">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="create_form" value="1">
    <div class="form-row">
        <?php if ($isSuper): ?>
            <div class="field"><label>Facility</label>
                <select name="facility_id">
                    <option value="">Global (all facilities)</option>
                    <?php foreach ($facilities as $f): ?>
                        <option value="<?php echo (int)$f['id']; ?>"><?php echo h($f['name']); ?><?php if ($f['code']) echo ' [' . h($f['code']) . ']'; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        <?php endif; ?>
        <div class="field"><label>Form Name *</label><input type="text" name="name" required></div>
        <div class="field"><label>Default Duration (min)</label><input type="number" name="default_duration_minutes" min="0" max="60" value="8"></div>
        <div class="field"><label>Description</label><input type="text" name="description"></div>
    </div>
    <button type="submit" class="btn btn-primary">Create &amp; Edit Items</button>
</form>

<h3 class="mt-3">Existing Forms</h3>
<p><a href="forms.php?show_deleted=<?php echo $showDeleted ? '0' : '1'; ?>" class="btn btn-sm"><?php echo $showDeleted ? '◀ Hide deleted' : '🗑 Show deleted'; ?></a></p>
<div class="table-wrap">
<table class="data">
    <thead><tr><th>ID</th><th>Name</th><th>Facility</th><th>Duration</th><th>Created</th><th>Status</th><th>Actions</th></tr></thead>
    <tbody>
    <?php foreach ($forms as $f): ?>
        <tr<?php if ($f['deleted_at']) echo ' style="opacity:.55"'; ?>>
            <td data-label="ID"><?php echo (int)$f['id']; ?></td>
            <td data-label="Name"><?php echo h($f['name']); ?></td>
            <td data-label="Facility"><?php echo $f['facility_name'] ? h($f['facility_name']) : '<em>Global</em>'; ?></td>
            <td data-label="Duration"><?php echo (int)($f['default_duration_minutes'] ?? 8); ?> min</td>
            <td data-label="Created"><?php echo h($f['created_at']); ?></td>
            <td data-label="Status"><?php echo $f['deleted_at'] ? '<span class="badge badge-timeout">deleted</span>' : '<span class="badge badge-submitted">active</span>'; ?></td>
            <td>
                <?php if (!$f['deleted_at']): ?>
                    <a href="form_edit.php?id=<?php echo (int)$f['id']; ?>" class="btn btn-sm">Edit</a>
                    <a href="grade.php?form_id=<?php echo (int)$f['id']; ?>" class="btn btn-sm btn-primary">Open Station</a>
                    <form method="post" style="display:inline" onsubmit="return confirm('Move this form to trash?');">
                        <?php echo csrf_field(); ?>
                        <button type="submit" name="delete_form" value="<?php echo (int)$f['id']; ?>" class="btn btn-sm btn-danger">Delete</button>
                    </form>
                <?php else: ?>
                    <form method="post" style="display:inline">
                        <?php echo csrf_field(); ?>
                        <button type="submit" name="restore_form" value="<?php echo (int)$f['id']; ?>" class="btn btn-sm">Restore</button>
                    </form>
                <?php endif; ?>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>

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