<?php

namespace App\DataTables\Admin\Service;

use App\Models\Service;
use App\Models\Order;
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;
function string_date($tanggal, $kostum = false) {
    
        date_default_timezone_set('Asia/Jakarta');
        
        if ($kostum === false) {
            $inputSeconds = time() - strtotime($tanggal);
        } else {
            $inputSeconds = strtotime($kostum) - strtotime($tanggal);
        }
        
        $secondsInAMinute = 60;
        $secondsInAnHour = 60 * $secondsInAMinute;
        $secondsInADay = 24 * $secondsInAnHour;
    
        // Extract days
        $days = floor($inputSeconds / $secondsInADay);
    
        // Extract hours
        $hourSeconds = $inputSeconds % $secondsInADay;
        $hours = floor($hourSeconds / $secondsInAnHour);
    
        // Extract minutes
        $minuteSeconds = $hourSeconds % $secondsInAnHour;
        $minutes = floor($minuteSeconds / $secondsInAMinute);
    
        // Extract the remaining seconds
        $remainingSeconds = $minuteSeconds % $secondsInAMinute;
        $seconds = ceil($remainingSeconds);
    
        // Format and return
        $timeParts = [];
        $sections = [
            'Hari' => (int)$days,
            'Jam' => (int)$hours,
            'Menit' => (int)$minutes,
            'Detik' => (int)$seconds,
        ];
    
        foreach ($sections as $name => $value){
            if ($value > 0){
                $timeParts[] = $value. ' '.$name.($value == 1 ? '' : '');
            }
        }
    
        return implode(' ', $timeParts);
    }

class ServiceDataTable extends DataTable {
    public function dataTable($query) {
        $query = Service::with('category', 'provider')->select('services.*');
        return datatables()
            ->eloquent($query)
            ->filter(function ($query) {
                if (request()->has('filter_category') AND request('filter_category') <> null) {
                    $query->whereHas('category', function($query){
                        $query->where('name', 'like', "%".escape_input(request('filter_category'))."%");
                    });
                }
                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_type') AND request('filter_type') <> null) {
                    $query->where('services.type', 'like', "%".escape_input(request('filter_type'))."%");
                }
                if (request()->has('filter_status') AND request('filter_status') <> null) {
                    $query->where('services.status', 'like', "%".escape_input(request('filter_status'))."%");
                }
                if (request()->has('refill_support') AND request('refill_support') <> null) {
                    $query->where('services.is_refill_support', 'like', "%".escape_input(request('refill_support'))."%");
                }
                if (request()->has('search') AND request('search') <> null) {
                    $query->where(function($query) {
                        $query
                        ->whereHas('category', function($query) {
                            $query->where('name', 'like', "%".escape_input(request('search'))."%");
                        })
                        ->orWhereHas('provider', function($query) {
                            $query->where('name', 'like', "%".escape_input(request('search'))."%");
                        })
                        ->orWhere('services.id', 'like', "%".escape_input(request('search'))."%")
                        ->orWhere('services.name', 'like', "%".escape_input(request('search'))."%")
                        ->orWhere('services.price', 'like', "%".escape_input(request('search'))."%")
                        ->orWhere('services.min', 'like', "%".escape_input(request('search'))."%")
                        ->orWhere('services.provider_service_id', 'like', "%".escape_input(request('search'))."%")
                        ->orWhere('services.max', 'like', "%".escape_input(request('search'))."%");
                    });
                }
            })
            ->editColumn('id', function ($query) {
                return "<a href=\"javascript:;\" onclick=\"modal('detail', 'Layanan', '".url('admin/service/detail/'.$query->id.'')."')\" class=\"badge badge-info badge-sm\" data-toggle=\"tooltip\" title=\"Detail\">#$query->id</a>";
            })
            ->editColumn('name', function ($query) {
                return "<a href=\"javascript:;\" onclick=\"info('$query->name')\" class=\"text-dark\" data-toggle=\"tooltip\" title=\"Detail\">$query->name</a>";
            })
            ->editColumn('price', function ($query) {
                return 'Rp '.number_format($query->price,0,',','.');
            })
            ->editColumn('min', function ($query) {
                return number_format($query->min,0,',','.');
            })
            ->editColumn('max', function ($query) {
                return number_format($query->max,0,',','.');
            })
            ->editColumn('category_id', function ($query) {
                if ($query->category == true) {
                    return "<a href=\"javascript:;\" onclick=\"info('".$query->category->name."')\" class=\"text-dark\" data-toggle=\"tooltip\" title=\"Detail\">".$query->category->name."</a>";
                }
                return null;
            })
            ->editColumn('provider_id', function ($query) {
                if ($query->provider == true) {
                    return $query->provider->name;
                }
                return null;
            })
            ->editColumn('avarage', function ($query) {
                $check_data = Service::find($query->id);
                $orders = Order::whereIn('status', ['Success'])
                               ->where('service_name', $query->name)
                               ->orderBy('id', 'desc')
                               ->get();
            
                if ($orders->count() > 0) {

                    foreach ($orders as $order) {
                        $selisih = string_date($order->created_at, $order->updated_at);
                        if (empty($selisih)) {
                           $selisih = 'data tidak cukup';
                        }
                    }
                } else {
                    $selisih = 'data tidak cukup';
                }
                return $selisih;
            })
            ->addColumn('action', function ($query) {
                return "
                <a href=\"javascript:;\" onclick=\"modal('edit', 'Layanan', '".url('admin/service/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->name', '".url('admin/service/delete/'.$query->id.'')."', '<br /><small>jika Anda menghapus <b>$query->name</b>, maka <b>Harga Khusus</b> dari <b>$query->name</b> juga akan ikut terhapus.')\" class=\"badge badge-danger badge-sm\" data-toggle=\"tooltip\" title=\"Hapus\"><i class=\"fa fa-trash\"></i></a>
                ";
            })
            ->addColumn('status', function ($query) {
                if ($query->status == '1') {
                    $labels = "<div class=\"custom-control custom-switch\">
                    <input type=\"checkbox\" class=\"custom-control-input\" id=\"switch-status-$query->id\" value=\"0\" onclick=\"switchStatus(this, $query->id, '".url('admin/service/status/'.$query->id.'/0')."')\" checked>
                    <label class=\"custom-control-label\" for=\"switch-status-$query->id\">Aktif</label></div>";
                } elseif ($query->status == '0') {
                    $labels = "<div class=\"custom-control custom-switch\">
                    <input type=\"checkbox\" class=\"custom-control-input\" id=\"switch-status-$query->id\" value=\"1\" onclick=\"switchStatus(this, $query->id, '".url('admin/service/status/'.$query->id.'/1')."')\">
                    <label class=\"custom-control-label\" for=\"switch-status-$query->id\">Nonaktif</label></div>";
                } else {
                    $labels = '<span class="badge badge-info badge-sm">ERROR</span>';
                }
                return $labels;
            })
            ->setRowId(function ($query) {
                return $query->id;
            })
            ->rawColumns(['id', 'category_id', 'name', 'action', 'status']);
    }

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

    protected function getColumns() {
        return [
            ['data' => 'id', 'title' => 'ID', 'class' => 'align-middle'],
            ['data' => 'category_id', 'name' => 'category.name', 'title' => 'Kategori', 'class' => 'align-middle'],
            ['data' => 'name', 'title' => 'Nama', 'class' => 'align-middle'],
            ['data' => 'price', 'title' => 'Harga/K', 'class' => 'align-middle'],
            ['data' => 'min', 'title' => 'Min.', 'class' => 'align-middle'],
            ['data' => 'max', 'title' => 'Maks.', 'class' => 'align-middle'],
            ['data' => 'provider_id', 'title' => 'API', 'class' => 'align-middle'],
            ['data' => 'provider_service_id', 'title' => 'PID', 'class' => 'align-middle'],
            ['data' => 'avarage', 'title' => 'Average Time', 'class' => 'align-middle'],
            ['data' => 'status', 'title' => 'Status', 'class' => 'align-middle', 'class' => 'text-center', 'orderable' => false, 'searchable' => false],
            ['data' => 'action', 'title' => 'Aksi', 'class' => 'align-middle', 'class' => 'text-center', 'orderable' => false, 'searchable' => false],
        ];
    }

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