<?php

namespace App\DataTables\User\Account;

use App\Models\Ticket;
use App\Models\UserBalanceLog;
use App\Models\RegisterLog;
use Illuminate\Support\Str;
use App\Models\UserLoginLog;
use Illuminate\Support\Carbon;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use App\Models\Admin\Log\Register;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;

class BalanceLogDataTable extends DataTable {
    public function dataTable($query, Request $request) {
        $query = UserBalanceLog::where('user_id', Auth::user()->id);
        return datatables()
            ->eloquent($query)
            ->filter(function ($query) use ($request) {
                if ($request->filter_start_date <> null AND $request->filter_end_date <> null) {
                    $request->filter_start_date = month_format($request->filter_start_date);
                    $request->filter_end_date = month_format($request->filter_end_date);
                    $query->whereRaw('DATE(created_at) BETWEEN "'.date('Y-m-d', strtotime($request->filter_start_date)).'" AND "'.date('Y-m-d', strtotime($request->filter_end_date)).'"');
                }
                if ($request->filter_type <> null) {
                    $query->where('type', 'like', '%'.escape_input($request->filter_type).'%');
                }
                if ($request->filter_action <> null) {
                    $query->where('action', 'like', '%'.escape_input($request->filter_action).'%');
                }
                if ($request->search <> null) {
                    $query->where(function($query) use ($request) {
                        $query
                        ->where('id', 'like', '%'.escape_input($request->search).'%')
                        ->orWhere('type', 'like', '%'.escape_input($request->search).'%')
                        ->orWhere('action', 'like', '%'.escape_input($request->search).'%')
                        ->orWhere('amount', 'like', '%'.escape_input($request->search).'%')
                        ->orWhere('first_balance', 'like', '%'.escape_input($request->search).'%')
                        ->orWhere('last_balance', 'like', '%'.escape_input($request->search).'%')
                        ->orWhere('description', 'like', '%'.escape_input($request->search).'%');
                    });
                }
            })
            ->editColumn('description', function ($query) {
                return "<a href=\"javascript:;\" onclick=\"info('$query->description')\" class=\"text-default\" data-toggle=\"tooltip\" title=\"Detail\">".Str::limit($query->description, 50, '...')."</a>";
            })
            ->addColumn('id_created_at', function ($query) {
                return "<a href=\"javascript:;\" class=\"badge bg-info badge-sm text-white\" data-toggle=\"tooltip\" title=\"Detail\">#$query->id</a><br /><small class=\"text-muted\">".Carbon::parse($query->created_at)->translatedFormat('d M Y - H:i')."</small>";
            })
            ->editColumn('amount', function ($query) {
                return 'Rp '.number_format($query->amount,0,',','.');
            })
            ->editColumn('first_balance', function ($query) {
                return 'Rp '.number_format($query->first_balance,0,',','.');
            })
            ->editColumn('last_balance', function ($query) {
                return 'Rp '.number_format($query->last_balance,0,',','.');
            })
            ->editColumn('type', function ($query) {
                if ($query->type == 'Plus') return '<span class="badge bg-success text-white"><i class="fa fa-plus"></i> Plus</span>';
                if ($query->type == 'Minus') return '<span class="badge bg-danger text-white"><i class="fa fa-minus"></i> Minus</span>';
            })
            ->setRowClass(function ($query) {
                return 'align-middle';
            })
            ->setRowId(function ($query) {
                return $query->id;
            })
            ->rawColumns(['description', 'type', 'id_created_at']);
    }

    public function query(UserBalanceLog $model) {
        return $model->newQuery();
    }

    public function html() {
        return $this->builder()
                    ->setTableId('data-table')
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->parameters([
                        "responsive" => true,
                        "autoWidth" => false,
                        "pageLength" => 10,
                        "lengthMenu" => [5, 10, 30, 50, 100],
                        "pagingType" => "full_numbers", 
                        "language" => [
                            "processing" => 'Sedang memproses...',
                            "lengthMenu" => "_MENU_",
                            "zeroRecords" => "Tidak ditemukan data yang sesuai",
                            "info" => "Menampilkan _START_ sampai _END_ dari _TOTAL_ entri",
                            "infoEmpty" => "Menampilkan 0 sampai 0 dari 0 entri",
                            "infoFiltered" => "(disaring dari _MAX_ entri keseluruhan)",
                            "infoPostFix" => "",
                            "search" => "Cari:",
                            "paginate" => [
                                "first" => "Pertama",
                                "previous" => "<i class='mdi mdi-chevron-left'>",
                                "next" => "<i class='mdi mdi-chevron-right'>",
                                "last" =>    "Terakhir"
                            ],
                        ]
                    ])
                    ->dom('<bottom><"float-left"><"float-right">r<"row"<"col-sm-4"i><"col-sm-4"><"col-sm-4"p>>')
                    ->ajax([
                        'url' => url()->current(),
                        'data' => 'function(d) { 
                            d.filter_start_date = $("input[name=filter_start_date]").val();
                            d.filter_end_date = $("input[name=filter_end_date]").val();
                            d.filter_type = $("#filter_type option:selected").val();
                            d.filter_action = $("#filter_action option:selected").val();
                            d.search = $("input[name=search]").val();
                        }',
                    ])
                    ->orderBy(0);
    }
    
    protected function getColumns() {
        return [
            ['data' => 'id_created_at', 'name' => 'id', 'title' => 'ID & Tanggal', 'class' => 'align-middle', 'width' => '100'],
            ['data' => 'type', 'title' => 'Tipe', 'class' => 'align-middle'],
            ['data' => 'action', 'title' => 'Aksi', 'class' => 'align-middle'],
            ['data' => 'amount', 'title' => 'Jumlah', 'class' => 'align-middle'],
            ['data' => 'first_balance', 'title' => 'Saldo Awal', 'class' => 'align-middle'],
            ['data' => 'last_balance', 'title' => 'Saldo Akhir', 'class' => 'align-middle'],
            ['data' => 'description', 'title' => 'Deskripsi', 'class' => 'align-middle'],
        ];
    }
    
    protected function filename() {
        return 'Lead_' . date('YmdHis');
    }
}
