@extends('merch_layouts.merch_master')
@section('page-title') 
    Merchant | Dealer Top Ups
@endsection
@section('page-css')
<link href="{!! url('public/vendor/tabulator-master/dist/css/tabulator_bootstrap3.min.css') !!}" type="text/css" rel="stylesheet">
@endsection
@section('page-content')
<div class="row">

<!-- <div class="col-md-12">
    <div class="hpanel hblue">
        <div class="panel-heading hbuilt">Top Ups received from Dealers</div>
        <div class="panel-body">
            <div class="" style="padding-bottom: 10px;">
              <button id="dealertopups-download-xlsx" class="btn btn-success btn-sm"><i class="fa fa-file-excel-o"></i> Download XLSX</button>
              <button id="dealertopups-download-pdf" class="btn btn-danger btn-sm"><i class="fa fa-file-pdf-o"></i> Download PDF</button>
            </div>
            <div class="pull-right">
                <form method="GET" action="{!! url('merchant/dealertransactions') !!}">
                  <div class="col-md-12 form-group pull-right top_search" style="background: cornflowerblue;">
                    <div class="input-group">
                      <input type="text" name="keyword" class="form-control" id="keywordField" placeholder="Keyword here.. ">
                      
                    </div>
                  </div>
                </form>
            </div>
            <div id="dealerTopsTable"></div>
        </div>
        <div class="panel-footer"></div>
    </div>
</div>
</div> -->
<div class="col-md-12">
    <div class="hpanel hblue">

        <div class="panel-heading hbuilt">
            Top Ups received from Dealers
        </div>

        <div class="panel-body">

            <!-- Action Buttons and Search -->
            <div class="row" style="margin-bottom:15px;">

                <!-- Download Buttons -->
                <div class="col-md-6">
                    <button id="dealertopups-download-xlsx" class="btn btn-success btn-sm">
                        <i class="fa fa-file-excel-o"></i> Download XLSX
                    </button>

                    <button id="dealertopups-download-pdf" class="btn btn-danger btn-sm">
                        <i class="fa fa-file-pdf-o"></i> Download PDF
                    </button>
                </div>

                <!-- Search Box -->
                <div class="col-md-6 text-right">
                    <form method="GET" action="{!! url('merchant/dealertransactions') !!}" class="form-inline">

                        <div class="input-group" style="width:300px; display:inline-flex;">
                            <input
                                type="text"
                                name="keyword"
                                id="keywordField"
                                class="form-control"
                                placeholder="Search by keyword..."
                                value="{{ request('keyword') }}">

                            <span class="input-group-btn">
                                <button class="btn btn-primary" type="submit">
                                    <i class="fa fa-search"></i>
                                </button>
                            </span>
                        </div>

                    </form>
                </div>

            </div>

            <!-- Dealer Topups Table -->
            <div id="dealerTopsTable"></div>

        </div>

        <div class="panel-footer"></div>

    </div>
</div>      
            



@endsection
@section('page-js')

<!-- <script src="{!! url('public/theme_assets/vendor/tabulator/js/tabulator.js') !!}"></script> -->
<script src="{!! url('public/vendor/tabulator-master/dist/js/tabulator.min.js') !!}"></script>
<script src="{!! url('public/theme_assets/vendor/tabulator/js/xlsx.full.min.js') !!}"></script>
<script src="{!! url('public/theme_assets/vendor/tabulator/js/jspdf.min.js') !!}"></script>
<script src="{!! url('public/theme_assets/vendor/tabulator/js/jspdf.plugin.autotable.js') !!}"></script>

<script>
    // Status formatter
    function statusDesign(cell) {
        const value = cell.getValue() || "";

        if (value.includes("Success")) {
            return "<span style='color:#3FB449;font-weight:bold'>" + value + "</span>";
        }

        if (value.includes("Failed")) {
            return "<span style='color:#dc3545;font-weight:bold'>" + value + "</span>";
        }

        return "<span style='color:#E4A11B'>" + value + "</span>";
    }

    // Initialize Tabulator
    var table = new Tabulator("#dealerTopsTable", {

        ajaxURL: "dealertransactions/all",

        ajaxConfig: "GET",

        layout: "fitColumns",

        index: "id",

        pagination: true,
        paginationMode: "remote",
        paginationSize: 15,

        selectableRows: false,

        printAsHtml: true,

        ajaxLoader: true,
        ajaxLoaderLoading: $("#logo_spinner").html(),

        columns: [
            {
                title: "Dealer",
                field: "name",
                sorter: "string",
            },
            {
                title: "Dealer Phone",
                field: "phone",
                sorter: "string",
            },
            {
                title: "Amount",
                field: "amount",
                sorter: "number",
                hozAlign: "right",
            },
            {
                title: "Status",
                field: "status",
                sorter: "string",
                formatter: statusDesign,
            },
            {
                title: "Date",
                field: "created_at",
                sorter: "string",
            },
            // {
            //   title: "Action",
            //   formatter: function (cell) {
            //     const data = cell.getRow().getData();
            //     const transaction_id = data.transaction_id;
            //     return `<button class="btn btn-sm btn-danger" type="button" onclick="refundDealerTopUp('${transaction_id}')" >Refund</button>`;
            //   },
            //   hozAlign: "center",
            //   headerSort: false,
            // }
            {
              title: "Action",
              formatter: function (cell) {
                const data = cell.getRow().getData();
                if (!data.status || !data.status.includes("Success")) return "No Action needed";
                const transaction_id = data.transaction_id;
                return `<button class="btn btn-sm btn-danger" type="button" onclick="refundDealerTopUp(${transaction_id})">Refund</button>`;
              },
              hozAlign: "center",
              headerSort: false,
            }


        ],

        rowClick: function (e, row) {
            const data = row.getData();
            console.log("Selected ID:", data.id);

            // Example:
            // window.location = "/dealertransactions/" + data.id;
        },

        ajaxError: function (xhr, textStatus, errorThrown) {
            console.error("Tabulator AJAX Error:", errorThrown);
        }

    });

    // Excel Download
    const excelBtn = document.getElementById("dealertopups-download-xlsx");

    if (excelBtn) {
        excelBtn.addEventListener("click", function () {
            table.download("xlsx", "dealertopups-list.xlsx", {
                sheetName: "Sheet 1"
            });
        });
    }

    // PDF Download
    const pdfBtn = document.getElementById("dealertopups-download-pdf");

    if (pdfBtn) {
        pdfBtn.addEventListener("click", function () {
            table.download("pdf", "dealertopups-list.pdf", {
                orientation: "portrait",
                title: "Click Mobile - Dealer Top Ups"
            });
        });
    }

    // Search with debounce
    let searchTimer;

    $("#keywordField").on("keyup", function () {

        clearTimeout(searchTimer);

        searchTimer = setTimeout(function () {

            table.setData("dealertransactions/all", {
                keyword: $("#keywordField").val()
            });

        }, 300);

    });

    function refundDealerTopUpOld(transaction_id) {
      if (!confirm("Are you sure you want to refund this transaction?")) return;

      $.ajax({
        url: "/pushrefunds",
        method: "POST",
        data: { transaction_id: transaction_id },
        headers: {
          "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
        },
        success: function (res) {
          alert(res?.message || "Refund requested successfully.");
          table.setData("dealertransactions/all", {
            keyword: $("#keywordField").val()
          });
        },
        error: function (xhr) {
          console.error(xhr.responseText);
          alert("Refund failed: " + (xhr.responseJSON?.message || "Unknown error"));
        }
      });
    }
    function refundDealerTopUp(transaction_id) {
      $.confirm({
        title: 'Refund top up',
        content: '' +
          '<form id="refundForm">' +
          '  <div class="form-group">' +
          '    <label>Reason</label>' +
          '    <input type="text" class="form-control" name="reason" placeholder="Enter refund reason" required />' +
          '  </div>' +
          '</form>',
        type: 'red',
        columnClass: 'medium',
        buttons: {
          cancel: function () {},
          confirm: {
            text: 'Confirm Refund',
            btnClass: 'btn-danger',
            action: function () {
              const reason = this.$content.find('input[name="reason"]').val();

              return $.ajax({
                url: "/merchant/pushrefunds",
                method: "POST",
                data: { transaction_id: transaction_id, reason: reason },
                headers: {
                  "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
                }
              }).done(function (res) {
                $.alert(res?.message || "Refund requested successfully.");
                table.setData("dealertransactions/all", {
                  keyword: $("#keywordField").val()
                });
              }).fail(function (xhr) {
                    console.log('status:', xhr.status);
                    console.log(xhr.responseText);
                    let msg = 'Request failed.';
                    try {
                        const res = JSON.parse(xhr.responseText);
                        if (res && typeof res.message === 'string') msg = res.message;
                    } 
                    catch (e) {}

                    $.alert(msg);
              });
            }
          }
        }
      });
    }



</script>
@endsection



