<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Indexer\ShopIndex;
use App\RuleCustom;
use App\Laravue\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use App\Shop;
use App\Http\Resources\Admin\ShopResource;
use App\Http\Resources\Admin\ShopResourceSelect;
use App\Http\Resources\Admin\ShopIndexResource;
use Illuminate\Support\Facades\URL;
use Validator;
use DB;

/**
 * Class ShopIndexController
 *
 * @package App\Http\Controllers
 */
class ShopIndexController extends Controller
{
    const ITEM_PER_PAGE = 20;
    private $_imagePath;
    private $_csvPath;
    private $_limitedItems;

    public function __construct()
    {
        $this->_imagePath = public_path('uploads/image/shop/');
        $this->_csvPath = storage_path('app/public/uploads/temp/csv/');

        $this->_limitedItems = ['hasLimited' => false, 'data' => []];
        $user = auth('api')->user();
        if ($user != null && !$user->hasRole('admin') && !$user->hasRole('manager') && !$user->hasPermissionTo('manage-shop') && $user->hasPermissionTo('manage-shop-custom')) {
            $this->_limitedItems['hasLimited'] = true;
            $permissions = $user->getAllPermissions();
            $pId = 0;
            $rId = 0;
            foreach ($permissions as $permission) {
                if ($permission->name == "manage-shop-custom") {
                    $pId = $permission->id;
                    $rId = $permission->pivot->role_id;
                    break;
                }
            }

            if ($pId > 0 && $rId > 0) {
                $rules = RuleCustom::where('role_id', $rId)->where('permission_id', $pId)->get();
                if ($rules->count() > 0) {
                    $shopLimited = Shop::select('id')->where('is_deleted', false);
                    foreach ($rules as $rule) {
                        $conditionVal = trim($rule->condition_value);
                        if ($rule->condition_name == 'id' || $rule->condition_name == 'name') {
                            if ($rule->condition_compare == 'is') {
                                $shopLimited->where($rule->condition_name, $conditionVal);
                            } elseif ($rule->condition_compare == 'start_with') {
                                $shopLimited->where($rule->condition_name, 'like', "$conditionVal%");
                            } elseif ($rule->condition_compare == 'end_with') {
                                $shopLimited->where($rule->condition_name, 'like', "%$conditionVal");
                            } elseif ($rule->condition_compare == 'contain') {
                                $shopLimited->where($rule->condition_name, 'like', "%$conditionVal%");
                            } elseif ($rule->condition_compare == 'in_list') {
                                $orgParam = str_replace(" ", "", $conditionVal);
                                $listParams = explode(",", $orgParam);
                                $pList = [];
                                foreach ($listParams as $l) {
                                    if (trim($l) != null && trim($l) != "") $pList[] = $l;
                                }
                                $shopLimited->whereIn($rule->condition_name, $pList);
                            }
                        } elseif ($rule->condition_name == 'user_id') {
                            $conditionVal = str_replace(" ", "", $conditionVal);
                            if ($conditionVal == "" || $conditionVal == "own" || $conditionVal == "owner") {
                                $shopLimited->where("user_id", $user->id);
                            } else if ($conditionVal == "store") {
                                $cUser = User::select('created_by')->where('id', $user->id)->first();
                                $storeManger = User::role('storemanage')->select('id')->where('id', $cUser->created_by)->first();
                                $shopLimited->where("user_id", $storeManger->id);
                            } else if ($conditionVal == "owner,store" || $conditionVal == "store,owner" || $conditionVal == "owner,store," || $conditionVal == "store,owner,") {
                                $listUserIds = [$user->id];
                                $cUser = User::select('created_by')->where('id', $user->id)->first();
                                $storeManger = User::role('storemanage')->select('id')->where('id', $cUser->created_by)->first();
                                $listUserIds[] = $storeManger->id;
                                $shopLimited->whereIn("user_id", $listUserIds);
                            } else {
                                if (strpos($conditionVal, "@") !== false) {
                                    $author = User::select('id')->where('email', $conditionVal)->first();
                                } else {
                                    $author = User::select('id')->where('name', $conditionVal)->first();
                                }
                                if (isset($author) && isset($author->id)) {
                                    $shopLimited->where("user_id", $author->id);
                                } else {
                                    $shopLimited->where("user_id", 0);
                                }
                            }
                        }
                    }
                    $this->_limitedItems['data'] = $shopLimited->pluck('id')->toArray();
                    if ($this->_limitedItems['data'] == null || count($this->_limitedItems['data']) <= 0) {
                        $this->_limitedItems['data'][] = 0;
                    }
                }
            }
        }
    }

    public function index(Request $request)
    {
        $searchParams = $request->all();
        $limit = Arr::get($searchParams, 'limit', static::ITEM_PER_PAGE);
        $list = ShopIndex::select('*')->orderBy('id')->paginate($limit);
        return ShopResource::collection($list);
    }

    public function selection(Request $request)
    {
        $searchParams = $request->all();
        $limit = Arr::get($searchParams, 'limit', static::ITEM_PER_PAGE);
        $list = ShopIndex::select('id', 'name');
        if ($this->_limitedItems['hasLimited']) $list->whereIn('id', $this->_limitedItems['data']);
        $list->orderBy('order_list');
        $result = $this->_data($list, $limit);

        return response()->json($result, 200);
    }

    protected function _data($query, $limit)
    {
        $currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
        $total = $query->count();
        $totalPage = floor($total / $limit);
        $totalPage += (($total % $limit) > 0) ? 1 : 0;
        if ($totalPage <= 0) return [];
        if ($currentPage > $totalPage) $currentPage = $totalPage;
        if ($currentPage < 1) $currentPage = 1;

        $prev_page_url = null;
        $next_page_url = null;
        $first_page_url = URL::current() . '?page=1';
        $last_page_url = URL::current() . '?page=' . $totalPage;
        if ($currentPage > 1) {
            $prev_page_url = URL::current() . '?page=' . ($currentPage - 1);
        }
        if (($currentPage + 1) <= $totalPage) {
            $next_page_url = URL::current() . '?page=' . ($currentPage + 1);
        }

        $offset = ($currentPage - 1) * $limit;
        $data = $query->orderByRaw("id asc LIMIT " . $offset . ", " . $limit . " option max_matches=2000")->get();

        return [
            'links' => [
                'first' => $first_page_url,
                'last'  => $last_page_url,
                'next'  => $next_page_url,
                'prev'  => $prev_page_url,
            ],
            'meta'  => [
                'current_page' => $currentPage,
                'from'         => $offset + 1,
                'last_page'    => $totalPage,
                'path'         => URL::current(),
                'per_page'     => $limit,
                'to'           => $offset + $limit,
                'total'        => $total,
            ],
            'data'  => $data->toArray(), //ShopIndexResource::collection($data),
        ];
    }
}
