<?php

namespace App\Http\Controllers\Admin\Service;

use App\Models\User;
use App\Models\Service;
use Illuminate\Http\Request;
use App\Models\ServiceCategory;
use Illuminate\Validation\Rule;
use App\Models\ServiceCustomPrice;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use App\DataTables\Admin\Service\CustomPriceDataTable;

class CustomPriceController extends Controller {
    public function list(CustomPriceDataTable $dataTable) {
        $components['breadcrumb'] = (object) [
			'first' => 'Daftar Harga Khusus',
			'second' => 'Layanan'
		];
        $components['users'] = ServiceCustomPrice::distinct()->latest('user_id')->get(['user_id']);
        $components['services'] = ServiceCustomPrice::distinct()->latest('service_id')->get(['service_id']);
        return $dataTable->render('admin.service.custom_price.list', $components);
    }
    public function getForm(ServiceCustomPrice $target, Request $request) {
		if ($request->ajax() == false) abort('404');
        $config['category_id'] = '0';
        if ($target == true) $components['target'] = $target;
        if ($target->id <> null) $config['category_id'] = $target->service->category_id;
        $components['categories'] = Service::distinct()->latest('category_id')->get(['category_id']);
		$components['services'] = Service::where('category_id', $config['category_id'])->oldest('price')->get();
        $components['users'] = User::where('status', '1')->latest('id')->get();
        return view('admin.service.custom_price.form', $components);
    }
    public function postForm(ServiceCustomPrice $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 = [
            'user_id'    => null,
            'service_id' => escape_input($request->service_id),
            'price'      => fixed_amount($request->price),
            'profit'     => fixed_amount($request->profit),
		];
		if ($target->id <> null) {
            $input_data['user_id'] = $target->user_id;
			$check_data = ServiceCustomPrice::where([
                ['user_id', $input_data['user_id']],
                ['service_id', $input_data['service_id']]
            ])->first();
			if ($input_data['service_id'] <> $target['service_id'] AND $input_data['user_id'] == $target['user_id'] AND $check_data == true) {
                return response()->json([
                    'status'  => false, 
                    'type'    => 'alert',
                    'message' => 'Harga Khusus sudah terdaftar.'
                ]);
			}
			if ($input_data['service_id'] == $target['service_id'] AND $input_data['user_id'] <> $target['user_id'] AND $check_data == true) {
                return response()->json([
                    'status'  => false, 
                    'type'    => 'alert',
                    'message' => 'Harga Khusus sudah terdaftar.'
                ]);
			}
			$update_data = $target->update($input_data);
            return response()->json([
				'status'  => true, 
				'message' => 'Harga Khusus berhasil diperbarui.'
			]);
		} else {
            $input_data['user_id'] = $request->user_id;
            $check_data = ServiceCustomPrice::where([
                ['user_id', $input_data['user_id']], 
                ['service_id', $input_data['service_id']]
            ])->first();
            if ($check_data == true) {
                return response()->json([
                    'status'  => false, 
                    'type'    => 'alert',
                    'message' => 'Harga Khusus untuk '.$check_data->user->username.' sudah terdaftar.'
                ]);
            }
            $insert_data = ServiceCustomPrice::create($input_data);
            return response()->json([
				'status'  => true, 
				'message' => 'Harga Khusus berhasil ditambahkan.'
			]);
		}
	}
	public function delete(ServiceCustomPrice $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()) {
			return json_encode(['result' => true], JSON_PRETTY_PRINT);
		}
	}
}

class PostRequest extends FormRequest {
	protected function prepareForValidation() {
		$this->merge([
			'price'  => $this->price <> '' ? fixed_amount($this->price) : '',
			'profit' => $this->profit <> '' ? fixed_amount($this->profit) : '',
		]);
	}
    protected function getValidatorInstance() {
		$instance = parent::getValidatorInstance();
        if ($instance->fails() == true) {
			throw new HttpResponseException(response()->json([
				'status'  => false, 
				'type'    => 'validation',
				'message' => parent::getValidatorInstance()->errors()
			]));
		}
        return parent::getValidatorInstance();
    }
    public function rules() {
        return [
            'category_id' => 'required|numeric|exists:service_categories,id',
            'user_id'        => 'required',
            'user_id.*'      => 'required|numeric|exists:users,id',
            'service_id'  => 'required|numeric|exists:services,id',
            'price'       => 'required|numeric|integer|min:0',
            'profit'      => 'required|numeric|integer|min:0',
        ];
    }
    public function attributes() {
		return [
            'category_id' => 'Kategori',
            'user_id'        => 'Pengguna',
            'user_id.*'      => 'Pengguna',
            'service_id'  => 'Layanan',
            'price'       => 'Harga/K',
            'profit'      => 'Keuntungan/K',
		];
    }
}