{% extends "base.html" %}
{% block content %}
<div x-data="dealsCrud()">
<header class="page-header"><h1>Deals</h1><p class="subtitle page-tip">Pipeline deals with full CRUD — click row to edit.</p></header>
<button class="btn btn-primary" @click="openNew()">Add deal</button>
<table class="data-table"><thead><tr><th>Title</th><th>Client</th><th>Value</th><th>Stage</th><th></th></tr></thead>
<tbody>{% for d in deals %}
<tr class="clickable-row" @click="editRow({{ d.id }}, '{{ d.title|e }}', {{ d.value or 0 }}, '{{ d.stage|e }}')">
<td>{{ d.title }}</td><td>{{ d.client_name or '—' }}</td><td>€{{ d.value }}</td><td>{{ d.stage }}</td>
<td><button class="btn btn-sm btn-reject" @click.stop="remove({{ d.id }})">Delete</button></td></tr>{% endfor %}</tbody></table>
<div class="modal" :class="{ open: show }" @click.self="show=false"><div class="modal-card">
<h3>Deal</h3><input class="form-input" x-model="form.title" /><input type="number" class="form-input" x-model="form.value" /><input class="form-input" x-model="form.stage" />
<div class="btn-group"><button class="btn btn-primary" @click="save()">Save</button></div></div></div>
</div>
{% endblock %}
{% block scripts %}
<script>
function dealsCrud() {
  return {
    show: false, id: null, form: { title: '', value: 0, stage: 'lead', client_id: null },
    openNew() { this.id = null; this.form = { title: '', value: 0, stage: 'lead', client_id: null }; this.show = true; },
    editRow(id, title, value, stage) { this.id = id; this.form = { title, value, stage, client_id: null }; this.show = true; },
    async save() {
      const body = { ...this.form, value: parseFloat(this.form.value) };
      if (this.id) await Cockpit.api('/deals/' + this.id, { method: 'PUT', body: JSON.stringify(body) });
      else await Cockpit.api('/deals', { method: 'POST', body: JSON.stringify(body) });
      location.reload();
    },
    async remove(id) { if (!Cockpit.confirmDelete()) return; await Cockpit.api('/deals/' + id, { method: 'DELETE' }); location.reload(); }
  };
}
</script>
{% endblock %}
