<?php

namespace App\Http\Controllers\Admin\Service;

use App\Models\Order;
use App\Models\Service;
use App\Models\ServiceCategory;
use App\Models\ServiceProvider;
use App\Models\ServiceCustomPrice;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Http\FormRequest;
use App\DataTables\Admin\Service\ServiceDataTable;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\Log;

class ServiceController extends Controller {
    public function list(ServiceDataTable $dataTable) {
        $components['breadcrumb'] = (object) [
			'first' => 'Daftar Layanan',
			'second' => 'Layanan'
		];
        $components['categories'] = Service::distinct()->latest('category_id')->get(['category_id']);
        $components['providers'] = Service::distinct()->latest('provider_id')->get(['provider_id']);
        $components['statuses'] = ['1' => 'Aktif', '0' => 'Nonaktif'];
        return $dataTable->render('admin.service.service.list', $components);
    }
    public function getForm(Service $target, Request $request) {
		if ($request->ajax() == false) abort('404');
        if ($target == true) $components['target'] = $target;
		$components['categories'] = ServiceCategory::where('status', '1')->oldest('name')->get();
		$components['providers'] = ServiceProvider::where('status', '1')->latest('id')->get();
        return view('admin.service.service.form', $components);
    }
    public function postForm(Service $target, PostRequest $request) {
		if ($request->ajax() == false) abort('404');
        if (Auth::guard('admin')->user()->level == 'Admin') {
			return response()->json([
				'status'  => false, 
				'type'    => 'alert',
                'message' => 'Aksi tidak diperbolehkan.'
			]);
        }
		$input_data = [
            'category_id'         => escape_input($request->category_id),
            'name'                => ($request->name),
            'min'                 => fixed_amount($request->min),
            'max'                 => fixed_amount($request->max),
            'price'               => fixed_amount($request->price),
            'profit'              => fixed_amount($request->profit),
            'provider_id'         => escape_input($request->provider_id),
            'provider_service_id' => escape_input($request->provider_service_id),
            'description'         => $request->description,
            'type'                => $request->type,
            'is_refill_support'   => is_null($request->is_refill_support) ? '0' : '1',
			'settings' => json_encode([
				'update_service'  => isset($request->update_service) ? '1' : '0',
				'name' 			  => isset($request['update_automate']['name']) ? '1' : '0',
				'min_max' 		  => isset($request['update_automate']['min_max']) ? '1' : '0',
				'price_profit' 	  => isset($request['update_automate']['price_profit']) ? '1' : '0',
				'profit' 		  => isset($request['update_automate']['profit']) ? '1' : '0',
				'description'     => isset($request['update_automate']['description']) ? '1' : '0',
				'custom_comments' => isset($request['update_automate']['custom_comments']) ? '1' : '0',
				'refill_support'  => isset($request['update_automate']['refill_support']) ? '1' : '0',
				'status'  		  => isset($request['update_automate']['status']) ? '1' : '0',
			])
		];
		if ($target->id <> null) {
			$check_data = Service::where([['name', $input_data['name']]])->first();
			if ($input_data['name'] <> $target['name'] AND $check_data) {
				$validator = Validator::make($request->all(), [
					'name' => 'required|unique:services,name|max:100',
				], [], ['name' => 'Nama']);
				if ($validator->fails()) {
					return response()->json([
						'status'  => false, 
						'type'    => 'validation',
						'message' => $validator->errors()->toArray()
					]);
				}
			}
			$check_provider = ServiceProvider::find($input_data['provider_id']);
			if (is_null($request->is_refill_support) == false AND $check_provider == true AND $check_provider->is_refill_support == '0') {
				return response()->json([
					'status'  => false, 
					'type'    => 'alert',
					'message' => 'Provider anda tidak mendukung Refill Support'
				]);
			}
			$update_data = $target->update($input_data);
			return response()->json([
				'status'  => true, 
				'message' => 'Layanan berhasil diperbarui.'
			]);
		} else {
			$check_provider = ServiceProvider::find($input_data['provider_id']);
			if (is_null($request->is_refill_support) == false AND $check_provider == true AND $check_provider->is_refill_support == '0') {
				return response()->json([
					'status'  => false, 
					'type'    => 'alert',
					'message' => 'Provider anda tidak mendukung Refill Support'
				]);
			}
			$insert_data = Service::create($input_data);
			return response()->json([
				'status'  => true, 
				'message' => 'Layanan berhasil ditambahkan.'
			]);
		}
	}
	public function status(Service $target, $status, Request $request) {
        if ($request->ajax() == false) abort('404');
        if (Auth::guard('admin')->user()->level == 'Admin') return (json_encode(['result' => false], JSON_PRETTY_PRINT));
        if (Arr::exists(['0', '1'], $status) == false) return (json_encode(['result' => false], JSON_PRETTY_PRINT));
        $update_data = $target->update(['status' => $status]);
        if ($update_data == true) {
            return (json_encode([
                'result'  => true,
                'message' => 'Status Layanan <b>'.$target->name.'</b> berhasil diperbarui.'
            ], JSON_PRETTY_PRINT));
        } else {
            return (json_encode(['result' => false], JSON_PRETTY_PRINT));
        }
	}
	public function delete(Service $target, Request $request) {
		if ($request->ajax() == false) abort('404');
        if (Auth::guard('admin')->user()->level == 'Admin') return (json_encode(['result' => false], JSON_PRETTY_PRINT));
		if ($target->delete()) {
            $custom_price = ServiceCustomPrice::where('service_id', $target->id)->delete();
			return json_encode(['result' => true], JSON_PRETTY_PRINT);
		}
	}
	public function detail(Service $target, Request $request) {
		if ($request->ajax() == false) abort('404');
        return view('admin.service.service.detail', compact('target'));
    }
}

class PostRequest extends FormRequest {
	protected function prepareForValidation() {
		$this->merge([
			'min'    => $this->min <> '' ? fixed_amount($this->min) : '',
			'max'    => $this->max <> '' ? fixed_amount($this->max) : '',
			'price'  => $this->price <> '' ? fixed_amount($this->price) : '',
			'profit' => $this->profit <> '' ? fixed_amount($this->profit) : '',
		]);
	}
    protected function getValidatorInstance() {
		$instance = parent::getValidatorInstance();
        if ($instance->fails() == true) {
			foreach (json_decode($instance->errors(), true) as $item) {
				$message = '<br />';
				$message .= $item[0].'';
				$message_array[] = $message;
			}
			throw new HttpResponseException(response()->json([
				'status'  => false, 
				'type'    => 'alert',
				'message' => 'Mohon periksa input. '.implode('', $message_array).''
			]));
		}
        return parent::getValidatorInstance();
    }
    public function rules() {
		if (request()->segment(4) == null) {
			return [
				'category_id'         => 'required|numeric|exists:service_categories,id',
				'provider_id'         => 'required|numeric|exists:service_providers,id',
				'provider_service_id' => 'required|max:30',
				'type'                => 'required|in:Default,Custom Comments,Comment Likes',
				'name'                => 'required|unique:services,name',
				'min'                 => 'required|numeric|integer|min:0',
				'max'                 => 'required|numeric|integer|min:0',
				'price'               => 'required|numeric|integer|min:0',
				'profit'              => 'required|numeric|integer|min:0',
				'description'         => 'required|string',
			];
		}
		return [
			'category_id'         => 'required|numeric|exists:service_categories,id',
			'provider_id'         => 'required|numeric|exists:service_providers,id',
            'provider_service_id' => 'required|max:30',
			'type'                => 'required|in:Default,Custom Comments,Comment Likes',
			'name'                => 'required',
			'min'                 => 'required|numeric|integer|min:0',
			'max'                 => 'required|numeric|integer|min:0',
			'price'               => 'required|numeric|integer|min:0',
			'profit'              => 'required|numeric|integer|min:0',
            'description'         => 'required|string',
		];
    }
    public function attributes() {
		return [
            'category_id'         => 'Kategori',
            'provider_id'         => 'Penyedia',
            'provider_service_id' => 'ID Layanan Penyedia',
            'type'                => 'Tipe',
            'name'                => 'Nama',
            'min'                 => 'Min.',
            'max'                 => 'Maks.',
            'price'               => 'Harga/K',
            'profit'              => 'Keuntungan/K',
            'description'         => 'Deskripsi',
		];
    }
}
