<template>
  <div class="row">
    <div class="col-12">
      <div
        class="page-title-box d-flex align-items-center justify-content-between"
      >
        <h4 class="mb-0">
          <img src="/img/expenses.png" alt="" class="avatar-sm me-2" />
          Expenses Panel
        </h4>

        <div class="page-title-right">
          <ol class="breadcrumb m-0">
            <li class="breadcrumb-item">
              <a href="javascript: void(0);">Expenses</a>
            </li>
            <li><i class="uil uil-arrow-right"></i></li>
            <li class="breadcrumb-item active">Expenses List</li>
          </ol>
        </div>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-lg-12">
      <div class="card">
        <div class="card-body">
          <div class="row">
            <div
              class="w-100 justify-content-between d-flex align-items-center my-3"
            >
              <div class="left-toobar d-flex flex-nowrap">
                <div
                  class="date-range d-flex align-items-center"
                  style="width: 200px"
                >
                  <div class="d-flex align-items-center input-wrapper">
                    <input
                      type="date"
                      v-model="dataFilter.from"
                      class="form-control"
                      @click="displayPicker"
                    />
                    <span class="input-separator">-</span>
                    <input
                      type="date"
                      v-model="dataFilter.to"
                      class="form-control"
                      @click="displayPicker"
                    />
                  </div>
                  <div class="icon ms-auto">
                    <i class="uil uil-calendar-alt fs-5"></i>
                  </div>
                </div>
                <div class="ms-2">
                  <ZohoSearch
                    placeholder="Select Product"
                    url="stock/expensesCategory/search"
                    label="name"
                    :load-defaults="true"
                    style="z-index: 999"
                    v-model="dataFilter.expense"
                  ></ZohoSearch>
                </div>
                <button
                  class="btn btn-primary ms-2"
                  type="button"
                  @click="handleDataFilter"
                >
                  {{ $trans("Apply") }}
                </button>
                <button
                  class="btn btn-outline-primary ms-2"
                  @click="resetFilters"
                  type="button"
                >
                  {{ $trans("Reset") }}
                </button>
              </div>
              <div class="right-toobar d-flex align-items-center flex-nowrap">
                <a
                  href="#"
                  class="btn btn-primary"
                  data-bs-toggle="modal"
                  data-bs-target="#Expenses-modal"
                  ><i class="uil uil-plus me-1"></i> Add New</a
                >
                <button
                  class="btn-dark btn btn-icon ms-1"
                  type="button"
                  :disabled="!rows.length"
                  @click="handlePrint('#expense-table', [], 'Expense report')"
                >
                  <svg
                    height="18px"
                    viewBox="0 0 16 16"
                    xmlns="http://www.w3.org/2000/svg"
                    fill="currentColor"
                  >
                    <path
                      d="M11 2H5a1 1 0 0 0-1 1v2H3V3a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2h-1V3a1 1 0 0 0-1-1zm3 4H2a1 1 0 0 0-1 1v3a1 1 0 0 0 1 1h1v1H2a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2h-1v-1h1a1 1 0 0 0 1-1V7a1 1 0 0 0-1-1z"
                    ></path>
                    <path
                      fill-rule="evenodd"
                      d="M11 9H5a1 1 0 0 0-1 1v3a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1zM5 8a2 2 0 0 0-2 2v3a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2v-3a2 2 0 0 0-2-2H5z"
                    ></path>
                    <path d="M3 7.5a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0z"></path>
                  </svg>
                </button>
                <button
                  class="btn-success btn btn-icon ms-1"
                  type="button"
                  :disabled="!rows.length"
                  @click="handleExcelExport('expense-table', 'Expense Report')"
                >
                  <svg
                    height="18px"
                    viewBox="0 0 16 16"
                    xmlns="http://www.w3.org/2000/svg"
                    fill="currentColor"
                  >
                    <path
                      fill-rule="evenodd"
                      d="M2 2a2 2 0 0 1 2-2h5.293A1 1 0 0 1 10 .293L13.707 4a1 1 0 0 1 .293.707V14a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V2zm7.5 1.5v-2l3 3h-2a1 1 0 0 1-1-1zM5.884 6.68a.5.5 0 1 0-.768.64L7.349 10l-2.233 2.68a.5.5 0 0 0 .768.64L8 10.781l2.116 2.54a.5.5 0 0 0 .768-.641L8.651 10l2.233-2.68a.5.5 0 0 0-.768-.64L8 9.219l-2.116-2.54z"
                    ></path>
                  </svg>
                </button>
              </div>
            </div>
          </div>
          <div class="table-responsive">
            <table
              class="table align-middle table-nowrap table-check"
              id="expense-table"
            >
              <thead>
                <tr>
                  <th scope="col" style="width: 50px">
                    <div class="form-check font-size-16">
                      <input
                        type="checkbox"
                        class="form-check-input"
                        id="checkAll"
                      />
                      <label class="form-check-label" for="checkAll"></label>
                    </div>
                  </th>
                  <th scope="col">Name</th>
                  <th scope="col">Amount</th>
                  <th scope="col">Description</th>
                  <th scope="col">Payment Mode</th>
                  <th scope="col">Created by</th>
                  <th scope="col">Created at</th>
                  <th class="action" style="width: 80px; min-width: 80px">
                    Action
                  </th>
                </tr>
              </thead>
              <div
                class="d-flex justify-content-center loader-container"
                v-if="isFetchingExpenses && !rows.length"
              >
                <div class="lds-ellipsis">
                  <div></div>
                  <div></div>
                  <div></div>
                  <div></div>
                </div>
              </div>
              <tbody v-else>
                <tr v-for="(expense, i) in rows" :key="i">
                  <th scope="row">
                    <div class="form-check font-size-16">
                      <input
                        type="checkbox"
                        class="form-check-input"
                        id="contacusercheck1"
                      />
                      <label
                        class="form-check-label"
                        for="contacusercheck1"
                      ></label>
                    </div>
                  </th>
                  <td>
                    <a
                      href="javascript: void(0);"
                      class="text-primary fw-bold"
                      >{{ expense.category.name.toUpperCase() }}</a
                    >
                  </td>
                  <td>FB <b class="fw-bold">{{ $helper.formatNumber(expense.amount) }}</b></td>
                  <td>{{ expense.description }}</td>
                  <td class="fw-bold">{{ expense.payment_method.name }}</td>
                  <td>{{ expense.creator.name }}</td>
                  <td>{{ $helper.formatDate(expense.created_at) }}</td>
                  <td>
                    <div class="dropdown">
                      <button
                        class="btn btn-light btn-sm dropdown-toggle"
                        type="button"
                        data-bs-toggle="dropdown"
                        aria-expanded="false"
                      >
                        <i class="uil uil-ellipsis-h"></i>
                      </button>
                      <ul class="dropdown-menu dropdown-menu-end">
                        <li>
                          <a
                            class="dropdown-item"
                            @click.prevent="handleEdit(expense)"
                            href="javascript:void(0)"
                          >
                            <i class="uil uil-edit fs-5 me-3"></i>
                            {{ $trans("Edit") }}</a
                          >
                        </li>
                        <li>
                          <a
                            class="dropdown-item"
                            @click.prevent="handleDestroy(expense, i)"
                            href="javascript:void(0)"
                          >
                            <i class="uil uil-trash fs-5 me-3"></i>
                            {{ $trans("Delete") }}</a
                          >
                        </li>
                      </ul>
                    </div>
                  </td>
                </tr>
                <tr>
                  <td></td>
                  <td colspan="1">Total:</td>
                  <td class="fw-bolder">
                    FB {{ $helper.formatNumber(grandTotal) }}
                  </td>
                  <td colspan="3"></td>
                </tr>
              </tbody>
            </table>
          </div>
          <paginations
            :to="recordsTo"
            :from="recordsFrom"
            :current_page="currentPage"
            :row_count_page="rowCountPage"
            @page-update="handlePagination"
            :total_records="totalRows"
            :page_range="pageRange"
          ></paginations>
        </div>
      </div>

      <div
        class="modal fade"
        tabindex="-1"
        id="Expenses-modal"
        aria-labelledby="mySmallModalLabel"
        aria-hidden="true"
        style="display: none"
      >
        <div class="modal-dialog modal-dialog-centered">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">
                {{
                  newExpense.id
                    ? $trans("Edit Expense")
                    : $trans("Create a new Expense")
                }}
              </h5>
              <button
                type="button"
                class="btn-close"
                data-bs-dismiss="modal"
                aria-label="Close"
              ></button>
            </div>
            <div class="modal-body">
              <div class="mb-3 row">
                <label class="col-md-4 col-form-label">{{
                  $trans("Expense Category")
                }}</label>
                <div class="col-md-8">
                  <select
                    class="form-control form-select"
                    v-model="newExpense.category_id"
                  >
                    <option :value="undefined" hidden disabled>
                      {{ $trans("Select Expenses") }}
                    </option>
                    <option
                      :value="expense.id"
                      v-for="expense in expenses"
                      :key="expense.id"
                    >
                      {{ expense.name }}
                    </option>
                  </select>
                </div>
              </div>
              <div class="mb-3 row">
                <label class="col-md-4 col-form-label">{{
                  $trans("Amount")
                }}</label>
                <div class="col-md-8">
                  <input
                    class="form-control"
                    type="number"
                    placeholder="Amount"
                    v-model="newExpense.amount"
                  />
                </div>
              </div>
              <div class="mb-3 row">
                <label class="col-md-4 col-form-label">{{
                  $trans("Payment Mode")
                }}</label>
                <div class="col-md-8">
                  <select
                    class="form-control form-select"
                    v-model="newExpense.payment_method"
                  >
                    <option :value="undefined" hidden disabled>
                      {{ $trans("Select Category") }}
                    </option>
                    <option
                      :value="row.id"
                      v-for="row in paymentModes"
                      :key="row.id"
                    >
                      {{ row.name }}
                    </option>
                  </select>
                </div>
              </div>
              <div class="mb-3 row">
                <label class="col-md-4 col-form-label">{{
                  $trans("Description")
                }}</label>
                <div class="col-md-8">
                  <textarea
                    class="form-control"
                    type="text"
                    placeholder="Description"
                    v-model="newExpense.description"
                  ></textarea>
                </div>
              </div>
              <div class="row">
                <div class="col-md-4"></div>
                <div class="col-md-8">
                  <loading-button
                    task="CREATING_NEW_EXPENSE"
                    class="btn btn-primary"
                    type="button w-100"
                    @clicked="handleSave"
                    :disabled="
                      !newExpense.category_id ||
                      !newExpense.amount ||
                      !newExpense.payment_method
                    "
                  >
                    <template #caption>{{ $trans("Save and Close") }}</template>
                  </loading-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import LoadingButton from "@/components/LoadingButton.vue";
import { tableMixin } from "@/helpers/tables.mixin";
import ZohoSearch from "@/components/ZohoSearch.vue";
import { permissionsHandler } from "@/helpers/permissions-handler";
export default {
  name: "Expenses",
  mixins: [permissionsHandler, tableMixin],
  components: { LoadingButton, ZohoSearch },
  data: () => ({
    dataUrl: "stock/expenses",
    selectedExpense: null,
    percentageCount: 0,
    selectedRow: null,
    newExpense: {},
    paymentModes: [],
    expenses: [],
    modal: null,
    task: "GETTING_EXPENSES_LIST",
  }),
  computed: {
    isFetchingExpenses() {
      this.$store.commit("SET_AJAX_TASK", this.task);
      return (
        this.$store.state.isLoading &&
        this.$store.state.loadingTask == this.task
      );
    },
    grandTotal() {
      return this.rows.reduce((a, b) => a + b.amount, 0);
    },
  },
  mounted() {
    this.$http.get("stock/pos/payments-modes").then((response) => {
      this.paymentModes = response.data.rows;
    });

    this.$http.get("stock/expensesCategory").then((response) => {
      this.expenses = response.data.rows;
    });

    this.modal = new bootstrap.Modal(
      document.getElementById("Expenses-modal"),
      {}
    );
  },
  methods: {
    handleDestroy(expense, i) {
      this.$confirm({
        title: "Deleting",
        content: `Are you sure you want to delete ${expense.category.name} from list of Expenses?`,
        actionText: "Yes, Continue",
        closeText: "Discard",
        classes: "btn btn-danger",
        action: () => {
          this.$http
            .get(`stock/expenses/destroy/${expense.id}`)
            .then((response) => {
              if (response.data.status) {
                this.rows.splice(i, 1);
                this.$notify({
                  type: "success",
                  message: "Expense deleted successfully",
                });
              }
            });
        },
      });
    },
    selectRow(row) {
      this.selectedRow = row;
    },
    handleEdit(expense) {
      this.newExpense = { ...expense };
      this.selectRow(expense);
      this.modal.show();
    },
    handleSave() {
      this.$http
        .post(
          "stock/expenses/store",
          this.$helper.generateFormData(this.newExpense)
        )
        .then((response) => {
          if (response.data.status) {
            if (!this.newExpense.id) {
              this.rows.unshift(response.data.row);
            } else {
              let index = this.rows.indexOf(
                (row) => row.id == this.newExpense.id
              );

              this.rows[index] = response.data.row;
            }
            this.modal.hide();
            this.newExpense = {};
            this.$emit("saved", response.data.row);
            this.resetFilters();
            this.$notify({
              type: "success",
              message: "New Expense saved successfully",
            });
          }
        })
        .catch((error) => {
          if (error.response.status == 400 || error.response.status == 422) {
            this.errors = error.response.data.errors;
            this.$notify({
              type: "error",
              message: "Form contains validation errors",
            });
          }
        });
    },
  },
};
</script>
