<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\Helper;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use App\Shipping;
use App\Http\Resources\Admin\ShippingResource;
use Validator;

/**
 * Class ShippingController
 *
 * @package App\Http\Controllers
 */
class ShippingController extends Controller
{
	const ITEM_PER_PAGE = 100;
	
	public function index(Request $request)
	{
		$searchParams = $request->all();
		$list = Shipping::notDeleted();
		$limit = Arr::get($searchParams, 'limit', static::ITEM_PER_PAGE);
		$keyword = Arr::get($searchParams, 'keyword', '');
		$status = Arr::get($searchParams, 'status', '');
		
		if (!empty($keyword)) {
			$list->where('price', 'LIKE', '%' . $keyword . '%');
		}
		if ($status != '') {
			$list->where('is_activated', $status);
		}
		$list->orderBy('id');
		
		return ShippingResource::collection($list->paginate($limit));
	}
	
	public function all(Request $request)
	{
		$searchParams = $request->all();
		$limit = Arr::get($searchParams, 'limit', static::ITEM_PER_PAGE);
		$list = Shipping::select('id', 'name', 'slug')->notDeleted()->orderBy('id');
		
		return ShippingResource::collection($list->paginate($limit));
	}
	
	public function available(Request $request)
	{
		
		$ignoreId = Arr::get($request->all(), 'ignoreId', '');
		$list = Shipping::select('id', 'name')->isPublished();
		
		if ($ignoreId != null && $ignoreId != "") {
			$list->where('id', '!=', $ignoreId);
		}
		
		$list->orderBy('id');
		
		return ShippingResource::collection($list->get());
	}
	
	public function show($id = 0)
	{
		$shipping = Shipping::notDeleted()->where('id', $id)->first();
		if (!isset($shipping)) return response()->json(['errors' => 'Shipping cost is not valid'], 403);
		
		return new ShippingResource($shipping);
	}
	
	public function store(Request $request)
	{
		$validator = Validator::make($request->all(), ['area_id' => ['required'], 'price' => ['required']]);
		if ($validator->fails()) return response()->json(['errors' => $validator->errors()], 403);
		$params = $request->all();
		
		$areaId = null;
		if (isset($params['area_id']) && is_array($params['area_id']) && isset($params['area_id'][array_key_last($params['area_id'])])) {
			$areaId = $params['area_id'][array_key_last($params['area_id'])];
		}
		
		$checkArea = Shipping::where('area_id', $areaId)->first();
		if ($checkArea) return response()->json(['errors' => 'Area is already exist.'], 403);
		
		$shipping = Shipping::create([
			'area_id'      => $areaId,
			'price'        => $params['price'],
			'free_from'    => $params['free_from'],
			'description'  => $params['description'],
			'is_activated' => ($params['is_activated'] === true) ? 1 : 0,
			'created_at'   => date('Y-m-d H:i:s'),
			'updated_at'   => date('Y-m-d H:i:s')
		]);
		
		return new ShippingResource($shipping);
	}
	
	public function update(Request $request, $id = 0)
	{
		$validator = Validator::make($request->all(), ['area_id' => ['required'], 'price' => ['required']]);
		if ($validator->fails()) return response()->json(['errors' => $validator->errors()], 403);
		$shipping = Shipping::notDeleted()->where('id', $id)->first();
		if (!isset($shipping)) return response()->json(['errors' => 'Shipping cost is not valid'], 403);
		$params = $request->all();
		
		$areaId = $shipping->area_id;
		if (isset($params['area_id']) && is_array($params['area_id']) && isset($params['area_id'][array_key_last($params['area_id'])])) {
			$areaId = $params['area_id'][array_key_last($params['area_id'])];
		}
		
		$checkArea = Shipping::where('id', '!=', $id)->where('area_id', $areaId)->first();
		if ($checkArea) return response()->json(['errors' => 'Area is already exist.'], 403);
		
		$shipping->update([
			'area_id'      => $areaId,
			'price'        => $params['price'],
			'free_from'    => $params['free_from'],
			'description'  => $params['description'],
			'is_activated' => ($params['is_activated'] === true) ? 1 : 0,
			'updated_at'   => date('Y-m-d H:i:s')
		]);
		
		return response()->json(null, 204);
	}
	
	public function destroy($id = 0)
	{
		$shipping = Shipping::notDeleted()->where('id', $id)->first();
		if (!isset($shipping)) response()->json(['error' => 'Ehhh! Can not delete this shipping cost'], 403);
		
		try {
			$shipping->update(['is_deleted' => true]);
		} catch (\Exception $ex) {
			response()->json(['error' => $ex->getMessage()], 403);
		}
		
		return response()->json(null, 204);
	}
	
	public function destroyMultiple(Request $request)
	{
		$validator = Validator::make($request->all(), ['ids' => 'required']);
		if ($validator->fails()) return response()->json(['errors' => $validator->errors()], 403);
		$listIds = $request->get('ids', []);
		$shipping = Shipping::notDeleted()->whereIn('id', $listIds)->get();
		if ($shipping->count() <= 0) response()->json(['error' => 'Shipping cost is not valid.'], 403);
		try {
			Shipping::notDeleted()->whereIn('id', $listIds)->update(['is_deleted' => true]);
		} catch (\Exception $ex) {
			response()->json(['error' => $ex->getMessage()], 403);
		}
		
		return response()->json(null, 204);
	}
	
	public function activateMultiple(Request $request)
	{
		$validator = Validator::make($request->all(), ['ids' => 'required']);
		if ($validator->fails()) return response()->json(['errors' => $validator->errors()], 403);
		$listIds = $request->get('ids', []);
		$shipping = Shipping::notDeleted()->whereIn('id', $listIds)->get();
		if ($shipping->count() <= 0) response()->json(['error' => 'Shipping cost is not valid.'], 403);
		try {
			Shipping::notDeleted()->whereIn('id', $listIds)->update(['is_activated' => true]);
		} catch (\Exception $ex) {
			response()->json(['error' => $ex->getMessage()], 403);
		}
		
		return response()->json(null, 204);
	}
	
	public function deactivateMultiple(Request $request)
	{
		$validator = Validator::make($request->all(), ['ids' => 'required']);
		if ($validator->fails()) return response()->json(['errors' => $validator->errors()], 403);
		$listIds = $request->get('ids', []);
		$shipping = Shipping::notDeleted()->whereIn('id', $listIds)->get();
		if ($shipping->count() <= 0) response()->json(['error' => 'Shipping cost is not valid.'], 403);
		try {
			Shipping::notDeleted()->whereIn('id', $listIds)->update(['is_activated' => false]);
		} catch (\Exception $ex) {
			response()->json(['error' => $ex->getMessage()], 403);
		}
		
		return response()->json(null, 204);
	}
}
