<?php

namespace App\DataTables\Admin;

use App\Models\Order;
use App\Models\OrderRefill;
use Illuminate\Support\Str;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
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 OrderDataTable extends DataTable {
    public function dataTable($query) {
        $query = Order::with('user', 'service', 'service_provider')->select('orders.*');
        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_created_at') AND request('filter_created_at') <> null) {
                    $query->where('orders.created_at', 'like', "%".escape_input(request('filter_created_at'))."%");
                }
                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_provider') AND request('filter_service_provider') <> null) {
                    $query->whereHas('service_provider', function($query){
                        $query->where('name', 'like', "%".escape_input(request('filter_service_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'))."%");
                        })
                        ->orWhere('orders.service_name', 'like', "%".escape_input(request('filter_service'))."%");
                    });
                }
                if (request()->has('filter_status') AND request('filter_status') <> null) {
                    $query->where('orders.status', '=', escape_input(request('filter_status')));
                }
                if (request()->has('filter_is_api') AND request('filter_is_api') <> null) {
                    $query->where('orders.is_api', 'like', "%".escape_input(request('filter_is_api'))."%");
                }
                if (request()->has('filter_target') AND request('filter_target') <> null) {
                    $query->where('orders.target', 'like', "%".escape_input(request('filter_target'))."%");
                }
                if (request()->has('filter_start_count') AND request('filter_start_count') <> null) {
                    $query->where('orders.start_count', 'like', "%".escape_input(request('filter_start_count'))."%");
                }
                if (request()->has('filter_remains') AND request('filter_remains') <> null) {
                    $query->where('orders.remains', 'like', "%".escape_input(request('filter_remains'))."%");
                }
                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('service_provider', function($query){
                            $query->where('name', 'like', "%".escape_input(request('search'))."%");
                        })
                        ->orWhere('orders.id', 'like', "%".escape_input(request('search'))."%")
                        ->orWhere('orders.service_name', 'like', "%".escape_input(request('search'))."%")
                        ->orWhere('orders.target', 'like', "%".escape_input(request('search'))."%")
                        ->orWhere('orders.quantity', 'like', "%".escape_input(request('search'))."%")
                        ->orWhere('orders.price', 'like', "%".escape_input(request('search'))."%")
                        ->orWhere('orders.provider_order_id', 'like', "%".escape_input(request('search'))."%")
                        ->orWhere('orders.start_count', 'like', "%".escape_input(request('search'))."%")
                        ->orWhere('orders.remains', 'like', "%".escape_input(request('search'))."%");
                    });
                }
            })
            ->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\">".$query->service->name."</a>";
                }
                return $query->service_name;
            })
            ->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('created_at', function ($query) {
                return Carbon::parse($query->created_at)->translatedFormat('d F Y - H:i');
            })
            ->editColumn('id', function ($query) {
                return "<a href=\"javascript:;\" onclick=\"modal('detail', 'Pesanan', '".url('admin/order/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', 'Pesanan', '".url('admin/order/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_provider', function ($query) {
                if($query->provider_order_id == 0) {
                    return "MANUAL";
                } else {
                    return $query->provider_order_id;
                }
            })
            ->editColumn('target', function ($query) {
                return "<div class=\"input-group\">
                    <input type=\"text\" class=\"form-control\" value=\"$query->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>";
            })
            ->editColumn('price', function ($query) {
                return 'Rp '.number_format($query->price,0,',','.');
            })
            ->editColumn('quantity', function ($query) {
                return number_format($query->quantity,0,',','.');
            })
            ->editColumn('start_count', function ($query) {
                return "
                    <input class=\"form-control\" type=\"text\" name=\"start_count\" value=\"{$query->start_count}\" id=\"start-count-$query->id\">
                ";
            })
            ->editColumn('remains', function ($query) {
                return "
                    <input class=\"form-control\" type=\"text\" name=\"remains\" value=\"{$query->remains}\" id=\"remains-$query->id\">
                ";
            })
            ->addColumn('action', function ($query) {
                return "
                <button class=\"btn btn-warning btn-sm btn-edit\" data-id=\"$query->id\" data-toggle=\"tooltip\" title=\"Simpan Perubahan\">
                    <i class=\"fa fa-save\"></i>
                </button>
                <a href=\"javascript:;\" onclick=\"deleteData(this, $query->id, '$query->id', '".url('admin/order/delete/'.$query->id.'')."')\" class=\"badge badge-danger badge-sm\" data-toggle=\"tooltip\" title=\"Hapus\"><i class=\"fa fa-trash\"></i></a>
                ";
            })
            ->addColumn('refill', function ($query) {
                if ($query->service_provider == true AND $query->service == true AND $query->service_provider->is_refill_support == '1' AND $query->service->is_refill_support == '1') {
                    $check_data = OrderRefill::where([
                        ['user_id', $query->user_id],
                        ['order_id', $query->id],
                        ['status', 'Pending']
                    ])->first();
                    if ($check_data == true) {
                        return '';
                    }
                    if ($query->status == 'Success') {
                        return "<a href=\"".url('admin/order/refill/create/'.$query->id.'')."\" class=\"badge badge-success badge-sm\" data-toggle=\"tooltip\" title=\"Refill\"><i class=\"mdi mdi-recycle\"></i> Refill</a>";
                    }
                }
                return '';
            })
            ->addColumn('status', function ($query) {
                $components['statuses'] = ['Pending', 'Processing', 'Success', 'Error', 'Partial'];
                $options = '';
                foreach ($components['statuses'] as $item) {
                    $selected = old('status') ? (old('status') == $item ? 'selected' : '') : ($query->status == $item ? 'selected' : '');
                    $options .= "<option value=\"{$item}\" {$selected}>{$item}</option>";
                }
            
                return "<select class='form-control status-dropdown' data-id='{$query->id}' id='status-{$query->id}'>{$options}</select>";
            })
            ->rawColumns(['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', 'service_id', 'target', 'action', 'status', 'refill', 'id_created_at', 'id_provider', 'start_count', 'remains','target']);
    }

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

    public function html() {
        return $this->builder()
                    ->setTableId('datatable')
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->parameters([
                        "responsive" => false,
                        "autoWidth" => false,
                        "pageLength" => 20,
                        "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_service_provider = $("#filter_service_provider option:selected").val();
                            d.filter_status = $("#filter_status option:selected").val();
                            d.filter_is_api = $("#filter_is_api option:selected").val();
                            d.search = $("textarea[name=search]").val();
                        }',
                    ])
                    ->orderBy(0);
    }

    protected function getColumns() {
        return [
            ['data' => 'id_created_at', 'name' => 'orders.id', 'title' => 'ID & Tanggal', 'class' => 'align-middle', 'width' => '100'],
            ['data' => 'id_provider', 'name' => 'orders.provider_order_id', 'title' => 'PID', 'class' => 'align-middle', 'width' => '100'],
            ['data' => 'user_id', 'name' => 'user.username', 'title' => 'Pengguna', 'class' => 'align-middle'],
            ['data' => 'service_id', 'name' => 'service.name', 'title' => 'Layanan', 'class' => 'align-middle'],
            ['data' => 'quantity', 'name' => 'orders.quantity', 'title' => 'Jumlah', 'class' => 'align-middle'],
            ['data' => 'price', 'name' => 'orders.price', 'title' => 'Harga', 'class' => 'align-middle'],
            ['data' => 'target', 'name' => 'service.target', 'title' => 'Target', 'class' => 'align-middle'],
            ['data' => 'start_count', 'name' => 'orders.start_count', 'title' => 'Start Count', 'class' => 'align-middle', 'width' => '100'],
            ['data' => 'remains', 'name' => 'orders.remains', 'title' => 'Remains', 'class' => 'align-middle', 'width' => '100'],
            ['data' => 'status', 'name' => 'orders.status', 'title' => 'Status', 'class' => 'text-center align-middle', 'width' => '100'],
            ['data' => 'refill', 'name' => 'refill', 'title' => 'Refill', 'class' => 'text-center align-middle', 'orderable' => false, 'searchable' => false],
            ['data' => 'action', 'title' => 'Aksi', 'class' => 'text-center align-middle', 'orderable' => false, 'searchable' => false],
        ];
    }

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