<?php

namespace Modules\AdvancedTransfer\Entities\Services;

use App\BusinessLocation;
use App\User;
use Modules\AdvancedTransfer\Entities\NstPrepareStock;
use Modules\AdvancedTransfer\Entities\NstUserLocation;

class LocationsService
{

    /**
     * Gives Access locations for user
     * @param $businessId
     * @param $flag
     * @param null $userId
     * @param bool $inNstTableOnly
     * @param null $status
     * @param null $fromLocation
     * @return \Illuminate\Support\Collection
     */
    public function accessLocationsForUser($businessId, $flag, $userId = null, $inNstTableOnly = false, $status = null, $fromLocation = null): \Illuminate\Support\Collection
    {
        $query = BusinessLocation::where('business_locations.business_id', $businessId)->where('business_locations.is_active',1);

        if($inNstTableOnly){
            $query->join('nst_prepare_products','nst_prepare_products.'.$flag.'_location_id','=','business_locations.id');
            $query->whereNull('nst_prepare_products.deleted_at');
            if ($status && $status != 'index') {
                $query->where('nst_prepare_products.status', $status);
            }

            if($fromLocation && $fromLocation != 'all'){
                $query->where('nst_prepare_products.from_location_id', $fromLocation);
            }
        }

        $user = $userId ? User::findOrFail($userId) : auth()->user();
        $query->groupBy('business_locations.id', 'business_locations.name')->select('business_locations.*');

//      tpsTransfer.location_access_(index/add/prepare/receive)_(from/to)_(all/his/selected)_locations

        if(!$status){
            $status = 'index';
        }

        if ($user->can("tpsTransfer.location_access_{$status}_{$flag}_all_locations")) {
            return $query->get();
        }

        if ($user->can("tpsTransfer.location_access_{$status}_{$flag}_his_locations")) {
            $permitted_locations = auth()->user()->permitted_locations();
            if ($permitted_locations != 'all') {
                $query->whereIn('business_locations.id', $permitted_locations);
            }

            return $query->get();
        }
        
        if ($user->can("tpsTransfer.location_access_{$status}_{$flag}_selected_locations")) {
            $locationIds = NstUserLocation::where(['business_id' => $businessId, 'user_id' => $user->id, 'type' => $status."_".$flag])->get()->pluck('location_id');
            $query->whereIn('business_locations.id', $locationIds);
            return $query->get();
        }

        return collect();
    }

    /**
     * Return list of locations for dropdown list
     * @param $business_id
     * @param $flag
     * @param null $userId
     * @param bool $inNstTableOnly
     * @param null $status
     * @param null $fromLocation
     * @param null $preAppendAll
     * @param bool $return_null_if_not_authorized
     * @return array
     */
    public function accessLocationsForUserforDropdown($business_id, $flag, $userId = null, $inNstTableOnly = false, $status = null, $fromLocation = null, $preAppendAll = false, $return_null_if_not_authorized = false): array
    {
        $locations = $this->accessLocationsForUser($business_id, $flag, $userId, $inNstTableOnly, $status, $fromLocation)->pluck('name', 'id')->toArray();

        if($return_null_if_not_authorized && empty($locations)){
	        return $locations;
        }
        if($preAppendAll){
            $locations = ['all' => __('business.all_your_business_locations')] + $locations;
        }
        return $locations;
    }

    /**
     * Get Tps indicators data.
     * @param $flag
     * @param $status
     * @return int
     */
    public function getTpsIndicatorsData($flag, $status)
    {
        $businessId = request()->session()->get('user.business_id');
        $locations = $this->accessLocationsForUser($businessId, $flag, null, true, $status)->pluck('id')->toArray();

        return intval(NstPrepareStock::where('status', $status)->where('business_id', $businessId)->whereIn($flag.'_location_id', $locations)->count());
    }
}
