<?php

namespace App\DataTables\Admin;

use App\Models\OrderRefill;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;

class OrderRefillDataTable extends DataTable {
    public function dataTable($query) {
        $query = OrderRefill::with('service', 'order')->select('order_refills.*');
        return datatables()
            ->eloquent($query)
            ->filter(function ($query) {
                if (request('filter_start_date') <> null AND request('filter_end_date') <> null) {
                    $start_date = month_format(request('filter_start_date'));
                    $end_date = month_format(request('filter_end_date'));
                    $query->whereRaw('DATE(created_at) BETWEEN "'.date('Y-m-d', strtotime($start_date)).'" AND "'.date('Y-m-d', strtotime($end_date)).'"');
                }
                if (request()->has('filter_user') AND request('filter_user') <> null) {
                    $query->whereHas('user', function($query){
                        $query->where('username', 'like', "%".escape_input(request('filter_user'))."%");
                    });
                }
                if (request()->has('filter_service') AND request('filter_service') <> null) {
                    $query->where(function($query) {
                        $query
                        ->whereHas('service', function($query) {
                            $query->where('name', 'like', "%".escape_input(request('filter_service'))."%");
                        });
                    });
                }
                if (request()->has('filter_status') AND request('filter_status') <> null) {
                    $query->where('order_refills.status', 'like', "%".escape_input(request('filter_status'))."%");
                }
                if (request()->has('search') AND request('search') <> null) {
                    $query->where(function($query) {
                        $query
                        ->whereHas('service', function($query) {
                            $query->where('name', 'like', "%".escape_input(request('search'))."%");
                        })
                        ->orWhereHas('user', function($query) {
                            $query->where('username', 'like', "%".escape_input(request('search'))."%");
                        })
                        ->orWhereHas('order', function($query) {
                            $query->where('target', 'like', "%".escape_input(request('search'))."%");
                        })
                        ->orWhere('order_refills.id', 'like', "%".escape_input(request('search'))."%")
                        ->orWhere('order_refills.order_id', 'like', "%".escape_input(request('search'))."%")
                        ->orWhere('order_refills.status', 'like', "%".escape_input(request('search'))."%");
                    });
                }
            })
            ->editColumn('user_id', function ($query) {
                if ($query->user == true) {
                    return "<a href=\"javascript:;\" onclick=\"modal('detail', 'Pengguna', '".url('admin/user/detail/'.$query->user_id.'')."')\" class=\"text-dark\" data-toggle=\"tooltip\" title=\"Detail\">".Str::limit($query->user->username, 10, '...')."</a>";
                }
                return null;
            })
            ->editColumn('service_id', function ($query) {
                if ($query->service == true) {
                    return "<a href=\"javascript:;\" onclick=\"modal('detail', 'Layanan', '".url('admin/service/detail/'.$query->service_id.'')."')\" class=\"text-dark\" data-toggle=\"tooltip\" title=\"Detail\">".Str::limit($query->service->name, 30, '...')."</a>";
                }
                return $query->service_name;
            })
            ->editColumn('order_id', function ($query) {
                if ($query->order == true) {
                    return "<a href=\"javascript:;\" onclick=\"modal('detail', 'Layanan', '".url('admin/order/detail/'.$query->order_id.'')."')\" class=\"text-dark\" data-toggle=\"tooltip\" title=\"Detail\">".Str::limit($query->order_id, 30, '...')."</a>";
                }
                return $query->order_id;
            })
            ->editColumn('created_at', function ($query) {
                return Carbon::parse($query->created_at)->translatedFormat('d F Y - H:i');
            })
            ->addColumn('target', function ($query) {
                if ($query->order == true) {
                    return "<div class=\"input-group\">
                        <input type=\"text\" class=\"form-control\" value=\"".$query->order->target."\" id=\"data-$query->id\" readonly>
                        <div class=\"input-group-append\">
                            <button class=\"btn btn-dark\" type=\"button\" onclick=\"copy('data-$query->id')\"><i class=\"fa fa-copy fa-fw\"></i> Salin</button>
                        </div>
                    </div>";
                } else {
                    return '';
                }
            })
            ->editColumn('id', function ($query) {
                return "<a href=\"javascript:;\" onclick=\"modal('detail', 'Refill Pesanan', '".url('admin/order/refill/detail/'.$query->id.'')."')\" class=\"badge badge-info badge-sm\" data-toggle=\"tooltip\" title=\"Detail\">#$query->id</a>";
            })
            ->addColumn('id_created_at', function ($query) {
                return "<a href=\"javascript:;\" onclick=\"modal('detail', 'Refill Pesanan', '".url('admin/order/refill/detail/'.$query->id.'')."')\" 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>";
            })
            ->addColumn('action', function ($query) {
                return "
                <a href=\"javascript:;\" onclick=\"modal('edit', 'Refill Pesanan', '".url('admin/order/refill/form/'.$query->id.'')."')\" class=\"badge badge-warning badge-sm\" data-toggle=\"tooltip\" title=\"Edit\"><i class=\"fa fa-edit fa-fw\"></i></a>
                <a href=\"javascript:;\" onclick=\"deleteData(this, $query->id, '$query->id', '".url('admin/order/refill/delete/'.$query->id.'')."')\" class=\"badge badge-danger badge-sm\" data-toggle=\"tooltip\" title=\"Hapus\"><i class=\"fa fa-trash\"></i></a>
                ";
            })
            ->addColumn('status', function ($query) {
                return status($query->status);
            })
            ->setRowClass(function ($query) {
                if ($query->status == 'Pending') {
                    return 'table-warning';
                } elseif ($query->status == 'Processing') {
                    return 'table-primary';
                } elseif ($query->status == 'Success') {
                    return 'table-success';
                } elseif ($query->status == 'Error') {
                    return 'table-danger';
                } elseif ($query->status == 'Partial') {
                    return 'table-danger';
                } else {
                    return 'table-secondary';
                }
            })
            ->setRowId(function ($query) {
                return $query->id;
            })
            ->rawColumns(['id', 'user_id', 'order_id', 'target', 'service_id', 'status', 'refill', 'action', 'id_created_at']);
    }

    public function query(OrderRefill $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_user = $("#filter_user option:selected").val();
                            d.filter_service = $("#filter_service option:selected").val();
                            d.filter_status = $("#filter_status option:selected").val();
                            d.search = $("textarea[name=search]").val();
                        }',
                    ])
                    ->orderBy(0);
    }

    protected function getColumns() {
        return [
            ['data' => 'id_created_at', 'name' => 'order_refills.id', 'title' => 'ID & Tanggal', 'class' => 'align-middle', 'width' => '100'],
            ['data' => 'order_id', 'name' => 'order_refills.order_id', 'title' => 'ID Pesanan', 'class' => 'align-middle'],
            ['data' => 'user_id', 'name' => 'user.username', 'title' => 'Pengguna', 'class' => 'align-middle'],
            ['data' => 'service_id', 'name' => 'service.name', 'title' => 'Layanan', 'class' => 'align-middle'],
            ['data' => 'status', 'name' => 'order_refills.status', 'title' => 'Status', 'class' => 'align-middle'],
            ['data' => 'action', 'title' => 'Aksi', 'class' => 'text-center align-middle', 'orderable' => false, 'searchable' => false],
        ];
    }

    protected function filename() {
        return 'Lead_' . date('YmdHis');
    }
}
