<?php

namespace App\DataTables\User;

use App\Models\OrderRefill;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
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, Request $request) {
        $query = OrderRefill::where('user_id', Auth::user()->id)->with('service', 'order')->select('order_refills.*');
        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_service <> null) {
                    $query->where(function($query) use ($request) {
                        $query
                        ->whereHas('service', function($query) use ($request) {
                            $query->where('name', 'like', '%'.escape_input($request->filter_service).'%');
                        });
                    });
                }
                if ($request->filter_status <> null) {
                    $query->where('order_refills.status', 'like', '%'.escape_input($request->filter_status).'%');
                }
                if ($request->search <> null) {
                    $query->where(function($query) use ($request) {
                        $query
                        ->whereHas('service', function($query) use ($request) {
                            $query->where('name', 'like', '%'.escape_input($request->search).'%');
                        })
                        ->orWhereHas('order', function($query) use ($request) {
                            $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('service_id', function ($query) {
                if ($query->service == true) {
                    return "<a href=\"javascript:;\" onclick=\"modal('detail', 'Layanan', '".url('page/service/detail/'.$query->service_id.'')."')\" class=\"text-dark\" data-toggle=\"tooltip\" title=\"Detail\">".$query->service->name."</a>";
                }
                return $query->service_name;
            })
            ->editColumn('order_id', function ($query) {
                if ($query->order == true) {
                    return "<a href=\"javascript:;\" onclick=\"modal('detail', 'Pesanan', '".url('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 "<input type=\"text\" class=\"form-control hidden\" value=\"".$query->order->target."\" id=\"data-$query->id\" readonly><a href=\"javascript:;\" class=\"text-default\" onclick=\"copy('data-$query->id')\">".$query->order->target."</a>";
                } else {
                    return '';
                }
            })
            ->addColumn('id_created_at', function ($query) {
                return "<a href=\"javascript:;\" onclick=\"modal('detail', 'Refill Pesanan', '".url('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>";
            })
            ->editColumn('id', function ($query) {
                return "<a href=\"javascript:;\" onclick=\"modal('detail', 'Refill Pesanan', '".url('order/refill/detail/'.$query->id.'')."')\" class=\"badge badge-info badge-sm\" data-toggle=\"tooltip\" title=\"Detail\">#$query->id</a>";
            })
            ->addColumn('status', function ($query) {
                return status($query->status);
            })
            ->setRowClass(function ($query) {
                return 'align-middle';
            })
            ->setRowId(function ($query) {
                return $query->id;
            })
            ->rawColumns(['id', 'order_id', 'target', 'service_id', 'status', 'refill', '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_service = $("#filter_service option:selected").val();
                            d.filter_status = $("#filter_status option:selected").val();
                            d.search = $("input[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', 'width' => '90'],
            ['data' => 'service_id', 'name' => 'service.name', 'title' => 'Layanan', 'class' => 'align-middle'],
            ['data' => 'target', 'title' => 'Target', 'class' => 'align-middle'],
            ['data' => 'status', 'name' => 'order_refills.status', 'title' => 'Status', 'class' => 'align-middle'],
        ];
    }

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