{% extends "base.html" %} {% from "macros.jinja" import window_vars with context
%} {% block page %}
<div class="row q-col-gutter-md">
  <div class="col-12 col-md-8 col-lg-7 q-gutter-y-md">
    <q-card>
      <q-card-section>
        <q-btn unelevated color="deep-purple" @click="formDialog.show = true"
          >New captcha</q-btn
        >
      </q-card-section>
    </q-card>

    <q-card>
      <q-card-section>
        <div class="row items-center no-wrap q-mb-md">
          <div class="col">
            <h5 class="text-subtitle1 q-my-none">Captchas</h5>
          </div>
          <div class="col-auto">
            <q-btn flat color="grey" @click="exportCSV">Export to CSV</q-btn>
          </div>
        </div>
        <q-table
          dense
          flat
          :data="captchas"
          row-key="id"
          :columns="captchasTable.columns"
          :pagination.sync="captchasTable.pagination"
        >
          {% raw %}
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th auto-width></q-th>
              <q-th v-for="col in props.cols" :key="col.name" :props="props">
                {{ col.label }}
              </q-th>
              <q-th auto-width></q-th>
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td auto-width>
                <q-btn
                  unelevated
                  dense
                  size="xs"
                  icon="launch"
                  :color="($q.dark.isActive) ? 'grey-7' : 'grey-5'"
                  type="a"
                  :href="props.row.displayUrl"
                  target="_blank"
                ></q-btn>
                <q-btn
                  unelevated
                  dense
                  size="xs"
                  icon="visibility"
                  :color="($q.dark.isActive) ? 'grey-7' : 'grey-5'"
                  :href="buildCaptchaSnippet(props.row.id)"
                  @click="openQrCodeDialog(props.row.id)"
                ></q-btn>
              </q-td>
              <q-td v-for="col in props.cols" :key="col.name" :props="props">
                {{ col.value }}
              </q-td>
              <q-td auto-width>
                <q-btn
                  flat
                  dense
                  size="xs"
                  @click="deleteCaptcha(props.row.id)"
                  icon="cancel"
                  color="pink"
                ></q-btn>
              </q-td>
            </q-tr>
          </template>
          {% endraw %}
        </q-table>
      </q-card-section>
    </q-card>
  </div>

  <div class="col-12 col-md-4 col-lg-5 q-gutter-y-md">
    <q-card>
      <q-card-section>
        <h6 class="text-subtitle1 q-my-none">LNbits captcha extension</h6>
      </q-card-section>
      <q-card-section class="q-pa-none">
        <q-separator></q-separator>
        <q-list> {% include "captcha/_api_docs.html" %} </q-list>
      </q-card-section>
    </q-card>
  </div>

  <q-dialog v-model="formDialog.show" position="top">
    <q-card class="q-pa-lg q-pt-xl lnbits__dialog-card">
      <q-form @submit="createCaptcha" class="q-gutter-md">
        <q-select
          filled
          dense
          emit-value
          v-model="formDialog.data.wallet"
          :options="g.user.walletOptions"
          label="Wallet *"
        >
        </q-select>
        <!--         <q-input
          filled
          dense
          v-model.trim="formDialog.data.url"
          type="hidden"
          label="Redirect URL *"
          :value="https://dummy.com"
        ></q-input> -->
        <q-input
          filled
          dense
          v-model.trim="formDialog.data.memo"
          label="Title *"
          placeholder="LNbits captcha"
        ></q-input>
        <q-input
          filled
          dense
          autogrow
          v-model.trim="formDialog.data.description"
          label="Description"
        ></q-input>
        <q-input
          filled
          dense
          v-model.number="formDialog.data.amount"
          type="number"
          label="Amount (sat) *"
          hint="This is the minimum amount users can pay/donate."
        ></q-input>
        <q-list>
          <q-item tag="label" class="rounded-borders">
            <q-item-section avatar>
              <q-checkbox
                v-model="formDialog.data.remembers"
                color="deep-purple"
              ></q-checkbox>
            </q-item-section>
            <q-item-section>
              <q-item-label>Remember payments</q-item-label>
              <q-item-label caption
                >A succesful payment will be registered in the browser's
                storage, so the user doesn't need to pay again to prove they are
                human.</q-item-label
              >
            </q-item-section>
          </q-item>
        </q-list>
        <div class="row q-mt-lg">
          <q-btn
            unelevated
            color="deep-purple"
            :disable="formDialog.data.amount == null || formDialog.data.amount < 0 || formDialog.data.memo == null"
            type="submit"
            >Create captcha</q-btn
          >
          <q-btn v-close-popup flat color="grey" class="q-ml-auto"
            >Cancel</q-btn
          >
        </div>
      </q-form>
    </q-card>
  </q-dialog>

  <q-dialog v-model="qrCodeDialog.show" position="top">
    <q-card v-if="qrCodeDialog.data" class="q-pa-lg lnbits__dialog-card">
      {% raw %}
      <q-responsive :ratio="1" class="q-mx-xl q-mb-md">
        <!--      <qrcode
          :value="qrCodeDialog.data.lnurl"
          :options="{width: 800}"
          class="rounded-borders"
        ></qrcode> -->
        <code style="word-break: break-all">
          {{ qrCodeDialog.data.snippet }}
        </code>
        <p style="margin-top: 20px">
          Copy the snippet above and paste into your website/form. The checkbox
          can be in checked state only after user pays.
        </p>
      </q-responsive>
      <p style="word-break: break-all">
        <strong>ID:</strong> {{ qrCodeDialog.data.id }}<br />
        <strong>Amount:</strong> {{ qrCodeDialog.data.amount }}<br />
        <!--      <span v-if="qrCodeDialog.data.currency"
          ><strong>{{ qrCodeDialog.data.currency }} price:</strong> {{
          fiatRates[qrCodeDialog.data.currency] ?
          fiatRates[qrCodeDialog.data.currency] + ' sat' : 'Loading...' }}<br
        /></span>
        <strong>Accepts comments:</strong> {{ qrCodeDialog.data.comments }}<br />
        <strong>Dispatches webhook to:</strong> {{ qrCodeDialog.data.webhook
        }}<br />
        <strong>On success:</strong> {{ qrCodeDialog.data.success }}<br /> -->
      </p>
      {% endraw %}
      <div class="row q-mt-lg q-gutter-sm">
        <q-btn
          outline
          color="grey"
          @click="copyText(qrCodeDialog.data.snippet, 'Snippet copied to clipboard!')"
          class="q-ml-sm"
          >Copy Snippet</q-btn
        >
        <!-- <q-btn
          outline
          color="grey"
          @click="copyText(qrCodeDialog.data.pay_url, 'Link copied to clipboard!')"
          >Shareable link</q-btn
        >
        <q-btn
          outline
          color="grey"
          icon="print"
          type="a"
          :href="qrCodeDialog.data.print_url"
          target="_blank"
        ></q-btn> -->
        <q-btn v-close-popup flat color="grey" class="q-ml-auto">Close</q-btn>
      </div>
    </q-card>
  </q-dialog>
</div>
{% endblock %} {% block scripts %} {{ window_vars(user) }}
<script>
  var mapCaptcha = function (obj) {
    obj.date = Quasar.utils.date.formatDate(
      new Date(obj.time * 1000),
      'YYYY-MM-DD HH:mm'
    )
    obj.fsat = new Intl.NumberFormat(LOCALE).format(obj.amount)
    obj.displayUrl = ['/captcha/', obj.id].join('')
    return obj
  }

  new Vue({
    el: '#vue',
    mixins: [windowMixin],
    data: function () {
      return {
        captchas: [],
        captchasTable: {
          columns: [
            {name: 'id', align: 'left', label: 'ID', field: 'id'},
            {name: 'memo', align: 'left', label: 'Memo', field: 'memo'},
            {
              name: 'amount',
              align: 'right',
              label: 'Amount (sat)',
              field: 'fsat',
              sortable: true,
              sort: function (a, b, rowA, rowB) {
                return rowA.amount - rowB.amount
              }
            },
            {
              name: 'remembers',
              align: 'left',
              label: 'Remember',
              field: 'remembers'
            },
            {
              name: 'date',
              align: 'left',
              label: 'Date',
              field: 'date',
              sortable: true
            }
          ],
          pagination: {
            rowsPerPage: 10
          }
        },
        formDialog: {
          show: false,
          data: {
            remembers: false
          }
        },
        qrCodeDialog: {
          show: false,
          data: null
        }
      }
    },
    methods: {
      getCaptchas: function () {
        var self = this

        LNbits.api
          .request(
            'GET',
            '/captcha/api/v1/captchas?all_wallets',
            this.g.user.wallets[0].inkey
          )
          .then(function (response) {
            self.captchas = response.data.map(function (obj) {
              return mapCaptcha(obj)
            })
          })
      },
      createCaptcha: function () {
        var data = {
          // url: this.formDialog.data.url,
          url: 'http://dummy.com',
          memo: this.formDialog.data.memo,
          amount: this.formDialog.data.amount,
          description: this.formDialog.data.description,
          remembers: this.formDialog.data.remembers
        }
        var self = this

        LNbits.api
          .request(
            'POST',
            '/captcha/api/v1/captchas',
            _.findWhere(this.g.user.wallets, {id: this.formDialog.data.wallet})
              .inkey,
            data
          )
          .then(function (response) {
            self.captchas.push(mapCaptcha(response.data))
            self.formDialog.show = false
            self.formDialog.data = {
              remembers: false
            }
          })
          .catch(function (error) {
            LNbits.utils.notifyApiError(error)
          })
      },
      deleteCaptcha: function (captchaId) {
        var self = this
        var captcha = _.findWhere(this.captchas, {id: captchaId})

        LNbits.utils
          .confirmDialog('Are you sure you want to delete this captcha link?')
          .onOk(function () {
            LNbits.api
              .request(
                'DELETE',
                '/captcha/api/v1/captchas/' + captchaId,
                _.findWhere(self.g.user.wallets, {id: captcha.wallet}).inkey
              )
              .then(function (response) {
                self.captchas = _.reject(self.captchas, function (obj) {
                  return obj.id == captchaId
                })
              })
              .catch(function (error) {
                LNbits.utils.notifyApiError(error)
              })
          })
      },
      buildCaptchaSnippet: function (captchaId) {
        var locationPath = [
          window.location.protocol,
          '//',
          window.location.host,
          window.location.pathname
        ].join('')

        var captchasnippet =
          '<!-- Captcha Checkbox Start -->\n' +
          '<input type="checkbox" id="captchacheckbox">\n' +
          '<label for="captchacheckbox">I\'m not a robot</label><br/>\n' +
          '<input type="text" id="captchapayhash" style="display: none;"/>\n' +
          '<script type="text/javascript" src="' +
          locationPath +
          'static/js/captcha.js" id="captchascript" data-captchaid="' +
          captchaId +
          '">\n' +
          '<\/script>\n' +
          '<!-- Captcha Checkbox End -->'
        return captchasnippet
      },
      openQrCodeDialog(captchaId) {
        // var link = _.findWhere(this.payLinks, {id: linkId})
        var captcha = _.findWhere(this.captchas, {id: captchaId})
        // if (link.currency) this.updateFiatRate(link.currency)

        this.qrCodeDialog.data = {
          id: captcha.id,
          amount: captcha.amount,
          // (link.min === link.max ? link.min : `${link.min} - ${link.max}`) +
          // ' ' +
          // (link.currency || 'sat'),
          snippet: this.buildCaptchaSnippet(captcha.id)
          // currency: link.currency,
          // comments: link.comment_chars
          //   ? `${link.comment_chars} characters`
          //   : 'no',
          // webhook: link.webhook_url || 'nowhere',
          // success:
          //   link.success_text || link.success_url
          //     ? 'Display message "' +
          //       link.success_text +
          //       '"' +
          //       (link.success_url ? ' and URL "' + link.success_url + '"' : '')
          //     : 'do nothing',
          // lnurl: link.lnurl,
          // pay_url: link.pay_url,
          // print_url: link.print_url
        }
        this.qrCodeDialog.show = true
      },
      exportCSV: function () {
        LNbits.utils.exportCSV(this.captchasTable.columns, this.captchas)
      }
    },
    created: function () {
      if (this.g.user.wallets.length) {
        this.getCaptchas()
      }
    }
  })
</script>
{% endblock %}
