{% extends 'core_ui/base.html' %}
{% block title %}Edit Plant – Nature In Pots{% endblock %}

{% block content %}
<div class="container mt-4">
  <h2>Edit Plant</h2>

  <form method="POST" enctype="multipart/form-data">
    {{ form.hidden_tag() }}

    <div class="mb-3">
      {{ form.plant_type.label(class="form-label") }}
      {{ form.plant_type(class="form-select") }}
    </div>
    <div class="mb-3">
      {{ form.common_name.label(class="form-label") }}
      {{ form.common_name(class="form-select") }}
    </div>
    <div class="mb-3">
      {{ form.scientific_name.label(class="form-label") }}
      {{ form.scientific_name(class="form-select") }}
    </div>
    <div class="mb-3">
      {{ form.mother_uuid.label(class="form-label") }}
      {{ form.mother_uuid(class="form-select") }}
    </div>
    <div class="mb-3">
      {{ form.custom_slug.label(class="form-label") }}
      {{ form.custom_slug(class="form-control") }}
    </div>
    <div class="mb-3">
      {{ form.vendor_name.label(class="form-label") }}
      {{ form.vendor_name(class="form-control") }}
    </div>
    <div class="mb-3">
      {{ form.price.label(class="form-label") }}
      {{ form.price(class="form-control") }}
    </div>
    <div class="mb-3">
      {{ form.notes.label(class="form-label") }}
      {{ form.notes(class="form-control", rows=4) }}
    </div>
    <div class="form-check mb-3">
      {{ form.data_verified(class="form-check-input") }}
      {{ form.data_verified.label(class="form-check-label") }}
    </div>
    <div class="form-check mb-3">
      {{ form.is_active(class="form-check-input") }}
      {{ form.is_active.label(class="form-check-label") }}
    </div>

    <button type="submit" class="btn btn-primary">Save Changes</button>
  </form>

  <hr>

  <h4>Upload Image</h4>
  <form
    method="POST"
    action="{{ url_for('media.add_media', plant_uuid=plant.uuid) }}"
    enctype="multipart/form-data"
    class="mb-4"
  >
    {{ form.csrf_token }}
    <div class="input-group">
      <input type="file" name="file" class="form-control" required>
      <button class="btn btn-secondary" type="submit">Upload</button>
    </div>
  </form>

  <h4>Existing Images</h4>
  <form method="POST" id="delete-images-form"
        action="{{ url_for('media.bulk_delete_media', plant_uuid=plant.uuid) }}"
        onsubmit="return confirm('Are you sure you want to delete selected images?');">
    {{ form.csrf_token }}
    <div class="row">
      {% for media in plant.media %}
        <div class="col-md-3 mb-4">
          <div class="card h-100">
            <img
              id="image-{{ media.id }}"
              src="{{ generate_image_url(media) }}"
              class="card-img-top img-fluid"
              alt="Plant Image"
              style="object-fit:cover; height:150px;"
            >
            <div class="card-body text-center">

              <div class="form-check mb-2">
                <input
                  class="form-check-input featured-radio"
                  type="radio"
                  name="featured_media"
                  value="{{ media.id }}"
                  {% if plant.featured_media_id == media.id %} checked {% endif %}
                  data-url="{{ url_for('media.set_featured_image',
                                       context='plant',
                                       context_id=plant.id,
                                       media_id=media.id) }}"
                >
                <label class="form-check-label">Featured</label>
              </div>

              <div class="d-grid gap-1">
                <button
                  type="button"
                  class="btn btn-outline-secondary btn-sm rotate-btn"
                  data-url="{{ url_for('media.rotate_media', media_id=media.id) }}"
                  data-id="{{ media.id }}"
                >Rotate</button>

                <div class="form-check mt-2">
                  <input class="form-check-input delete-checkbox"
                         type="checkbox"
                         name="delete_ids"
                         value="{{ media.id }}">
                  <label class="form-check-label">Delete</label>
                </div>
              </div>

            </div>
          </div>
        </div>
      {% else %}
        <p class="text-muted">No images uploaded yet.</p>
      {% endfor %}
    </div>

    <button type="submit" class="btn btn-danger mt-2">Delete Selected Images</button>
  </form>
</div>
{% endblock %}

{% block scripts %}
<script>
  const csrfToken = "{{ form.csrf_token._value() }}";

  // Rotate
  document.querySelectorAll('.rotate-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const url = btn.dataset.url;
      const id  = btn.dataset.id;
      fetch(url, {
        method: 'POST',
        headers: { 'X-CSRFToken': csrfToken }
      })
      .then(r => {
        if (!r.ok) throw Error();
        const img = document.getElementById(`image-${id}`);
        img.src = img.src.split('?')[0] + `?v=${Date.now()}`;
      })
      .catch(() => alert('Failed to rotate image.'));
    });
  });

  // Feature
  document.querySelectorAll('.featured-radio').forEach(radio => {
    radio.addEventListener('change', () => {
      const url = radio.dataset.url;
      fetch(url, {
        method: 'POST',
        headers: { 'X-CSRFToken': csrfToken }
      })
      .then(r => {
        if (!r.ok) throw Error();
        // uncheck all, then check this one
        document.querySelectorAll('.featured-radio').forEach(r => r.checked = false);
        radio.checked = true;
      })
      .catch(() => alert('Could not set featured image.'));
    });
  });
</script>
{% endblock %}
