<?php

namespace App\DataTables\Admin\Service;

use App\Models\ServiceLog;
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 LogDataTable extends DataTable {
    public function dataTable($query) {
        $query = ServiceLog::with('user', 'service', 'provider')->select('service_logs.*');
        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_provider') AND request('filter_provider') <> null) {
                    $query->whereHas('provider', function($query){
                        $query->where('name', 'like', "%".escape_input(request('filter_provider'))."%");
                    });
                }
                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('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('provider', function($query){
                            $query->where('name', 'like', "%".escape_input(request('search'))."%");
                        })
                        ->orWhere('service_logs.id', 'like', "%".escape_input(request('search'))."%")
                        ->orWhere('service_logs.logs', '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 null;
            })
            ->editColumn('provider_id', function ($query) {
                if ($query->provider == true) {
                    return "<a href=\"javascript:;\" onclick=\"modal('detail', 'Penyedia', '".url('admin/service/provider/detail/'.$query->provider_id.'')."')\" class=\"text-dark\" data-toggle=\"tooltip\" title=\"Detail\">".Str::limit($query->provider->name, 30, '...')."</a>";
                }
                return null;
            })
            ->editColumn('created_at', function ($query) {
                return Carbon::parse($query->created_at)->translatedFormat('d F Y - H:i');
            })
            ->setRowId(function ($query) {
                return $query->id;
            })
            ->rawColumns(['id', 'provider_id', 'service_id', 'user_id', 'action', 'status', 'refill']);
    }

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

    protected function getColumns() {
        return [
            ['data' => 'id', 'title' => 'ID', 'class' => 'align-middle'],
            ['data' => 'created_at', 'name' => 'orders.created_at', 'title' => 'Dibuat', 'class' => 'align-middle'],
            ['data' => 'user_id', 'name' => 'user.username', 'title' => 'Pengguna', 'class' => 'align-middle'],
            ['data' => 'provider_id', 'name' => 'provider.name', 'title' => 'Penyedia', 'class' => 'align-middle'],
            ['data' => 'service.id', 'name' => 'service.id', 'title' => 'ID Layanan', 'class' => 'align-middle'],
            ['data' => 'service_id', 'name' => 'service.name', 'title' => 'Layanan', 'class' => 'align-middle'],
            ['data' => 'logs', 'title' => 'Deskripsi', 'class' => 'align-middle', 'width' => '180'],
        ];
    }

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