<?php

namespace App\Http\Controllers\Admin;

use App\Area;
use App\Article;
use App\Consultation;
use App\Contact;
use App\Fortunemethod;
use App\Fortuneteller;
use App\Header;
use App\Http\Controllers\Controller;
use App\Keyword;
use App\RuleCustom;
use App\Schedule;
use App\Seo;
use App\Shop;
use App\Laravue\Models\User;
use Illuminate\Http\Request;
use App\Laravue\Acl;

class DashboardController extends Controller
{
    private $_limitedItems;
    private $_limitedUserByShop;
    private $_limitedUserByOwner;
    private $_limitedUserByAssign;
    private $_limitedArticleByShop;
    private $_limitedArticleByOwner;

    public function __construct()
    {
        $this->_limitedItems = ['hasLimited' => false, 'data' => []];
        $this->_limitedUserByShop = ['hasLimited' => false, 'data' => []];
        $this->_limitedUserByOwner = ['hasLimited' => false, 'data' => []];
        $this->_limitedUserByAssign = ['hasLimited' => false, 'data' => []];
        $this->_limitedArticleByShop = ['hasLimited' => false, 'data' => []];
        $this->_limitedArticleByOwner = ['hasLimited' => false, 'data' => []];

        $user = auth('api')->user();
        if ($user != null && !$user->hasRole('admin') && !$user->hasRole('manager')) {
            $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 (!$user->hasPermissionTo('manage-shop') && $user->hasPermissionTo('manage-shop-custom')) {
                $this->_limitedItems['hasLimited'] = true;
                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") {
                                    if (isset($user) && $user->id != null) {
                                        $cUser = \App\Laravue\Models\User::select('created_by')->where('id', $user->id)->first();
                                        if (isset($cUser) && $cUser->created_by != null) {
                                            $storeManger = User::role('storemanage')->select('id')->where('id', $cUser->created_by)->first();
                                            if (isset($storeManger) && $storeManger->id != null) {
                                                $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;
                        }
                    }
                }
            }

            if (!$user->hasPermissionTo('manage-fortuneteller')) {
                if ($user->hasPermissionTo('manage-fortuneteller-group') && $user->hasPermissionTo('manage-shop-custom')) {
                    $this->_limitedUserByShop['hasLimited'] = true;
                    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') {
                                    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->_limitedUserByShop['data'] = $shopLimited->pluck('id')->toArray();
                            if ($this->_limitedUserByShop['data'] == null || count($this->_limitedUserByShop['data']) <= 0) {
                                $this->_limitedUserByShop['data'][] = 0;
                            }
                        }
                    }
                }

                if ($user->hasPermissionTo('manage-fortuneteller-owner')) {
                    $this->_limitedUserByOwner['hasLimited'] = true;
                    $this->_limitedUserByOwner['data'] = Fortuneteller::select('id')->where('is_deleted', false)->where('user_id', $user->id)->pluck('id')->toArray();
                }

                if ($user->hasPermissionTo('manage-fortuneteller-assign')) {
                    $this->_limitedUserByAssign['hasLimited'] = true;
                    $this->_limitedUserByAssign['data'] = Fortuneteller::select('id')->where('is_deleted', false)->where('assigned_user_id', $user->id)->pluck('id')->toArray();
                }
            }

            if (!$user->hasPermissionTo('manage-article')) {
                if ($user->hasPermissionTo('manage-article-group') && $user->hasPermissionTo('manage-shop-custom')) {
                    $this->_limitedArticleByShop['hasLimited'] = true;
                    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') {
                                    if ($conditionVal == "" || $conditionVal == "own" || $conditionVal == "owner") {
                                        $shopLimited->where("user_id", $user->id);
                                    } 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->_limitedArticleByShop['data'] = $shopLimited->pluck('id')->toArray();
                            if ($this->_limitedArticleByShop['data'] == null || count($this->_limitedArticleByShop['data']) <= 0) {
                                $this->_limitedArticleByShop['data'][] = 0;
                            }
                        }
                    }
                }

                if ($user->hasPermissionTo('manage-article-owner')) {
                    $this->_limitedArticleByOwner['hasLimited'] = true;
                    $this->_limitedArticleByOwner['data'] = Article::select('id')->where('is_deleted', false)->where('user_id', $user->id)->pluck('id')->toArray();
                }
            }


        }
    }

    public function statistic()
    {
        $data = [];

        $user = auth('api')->user();
        if ($user->hasRole(['admin', 'manager']) || $user->can(Acl::PERMISSION_DASHBOARD_FORTUNETELLER_MANAGE)) {
            $totalTeller = Fortuneteller::where('is_deleted', false);
            if ($this->_limitedUserByShop['hasLimited']) $totalTeller->whereIn('shop_id', $this->_limitedUserByShop['data']);
            if ($this->_limitedUserByOwner['hasLimited'] && $this->_limitedUserByAssign['hasLimited']) {
                $ownerAssignList = array_merge($this->_limitedUserByOwner['data'], $this->_limitedUserByAssign['data']);
                $totalTeller->whereIn('id', $ownerAssignList);
            } else if ($this->_limitedUserByOwner['hasLimited']) {
                $totalTeller->whereIn('id', $this->_limitedUserByOwner['data']);
            } else if ($this->_limitedUserByAssign['hasLimited']) {
                $totalTeller->whereIn('id', $this->_limitedUserByAssign['data']);
            }
            $data['fortuneteller'] = ['total' => $totalTeller->count(), 'statistic' => [[20, 10, 50, 30, 40, 20, 50], [20, 10, 50, 30, 40, 20, 50]]];
        }
        if ($user->hasRole(['admin', 'manager']) || $user->can(Acl::PERMISSION_DASHBOARD_AREA_MANAGE)) {
            $totalArea = Area::where('is_deleted', false)->count();
            $data['area'] = ['total' => $totalArea, 'statistic' => [[20, 10, 50, 30, 40, 20, 50], [20, 10, 50, 30, 40, 20, 50]]];
        }
        if ($user->hasRole(['admin', 'manager']) || $user->can(Acl::PERMISSION_DASHBOARD_SHOP_MANAGE)) {
            if ($this->_limitedItems['hasLimited']) {
                $totalShop = Shop::where('is_deleted', false)->whereIn('id', $this->_limitedItems['data'])->count();
            } else {
                $totalShop = Shop::where('is_deleted', false)->count();
            }
            $data['shop'] = ['total' => $totalShop, 'statistic' => [[20, 10, 50, 30, 40, 20, 50], [20, 10, 50, 30, 40, 20, 50]]];
        }
        if ($user->hasRole(['admin', 'manager']) || $user->can(Acl::PERMISSION_DASHBOARD_CONSULTATION_MANAGE)) {
            $totalConsultation = Consultation::where('is_deleted', false)->count();
            $data['consultation'] = ['total' => $totalConsultation, 'statistic' => [[20, 10, 50, 30, 40, 20, 50], [20, 10, 50, 30, 40, 20, 50]]];
        }
        if ($user->hasRole(['admin', 'manager']) || $user->can(Acl::PERMISSION_DASHBOARD_METHOD_MANAGE)) {
            $totalMethod = Fortunemethod::where('is_deleted', false)->count();
            $data['method'] = ['total' => $totalMethod, 'statistic' => [[20, 10, 50, 30, 40, 20, 50], [20, 10, 50, 30, 40, 20, 50]]];
        }
        if ($user->hasRole(['admin', 'manager']) || $user->can(Acl::PERMISSION_DASHBOARD_ARTICLE_MANAGE)) {
            $totalArticle = Article::where('is_deleted', false)->where('type', 'article');
            if ($this->_limitedArticleByShop['hasLimited']) {
                $totalArticle->whereIn('shop_id', $this->_limitedArticleByShop['data']);
            }
            if ($this->_limitedArticleByOwner['hasLimited']) {
                $totalArticle->whereIn('id', $this->_limitedArticleByOwner['data']);
            }
            $data['article'] = ['total' => $totalArticle->count(), 'statistic' => [[20, 10, 50, 30, 40, 20, 50], [20, 10, 50, 30, 40, 20, 50]]];
        }
        /*
        if ($user->hasRole(['admin', 'manager']) || $user->can(Acl::PERMISSION_DASHBOARD_MAGAZINE_MANAGE)) {
            $totalMagazine = Article::where('is_deleted', false)->where('type', 'magazine');
            if ($this->_limitedArticleByShop['hasLimited']) {
                $totalMagazine->whereIn('shop_id', $this->_limitedArticleByShop['data']);
            }
            if ($this->_limitedArticleByOwner['hasLimited']) {
                $totalMagazine->whereIn('id', $this->_limitedArticleByOwner['data']);
            }
            $data['magazine'] = ['total' => $totalMagazine->count(), 'statistic' => [[20, 10, 50, 30, 40, 20, 50], [20, 10, 50, 30, 40, 20, 50]]];
        }*/
        if ($user->hasRole(['admin', 'manager']) || $user->can(Acl::PERMISSION_DASHBOARD_HEADER_MANAGE)) {
            $totalHeader = Header::where('is_deleted', false)->count();
            $data['header'] = ['total' => $totalHeader, 'statistic' => [[20, 10, 50, 30, 40, 20, 50], [20, 10, 50, 30, 40, 20, 50]]];
        }
        if ($user->hasRole(['admin', 'manager']) || $user->can(Acl::PERMISSION_DASHBOARD_KEYWORD_MANAGE)) {
            $totalKeyword = Keyword::where('is_deleted', false)->count();
            $data['keyword'] = ['total' => $totalKeyword, 'statistic' => [[20, 10, 50, 30, 40, 20, 50], [20, 10, 50, 30, 40, 20, 50]]];
        }
        if ($user->hasRole(['admin', 'manager']) || $user->can(Acl::PERMISSION_DASHBOARD_USER_MANAGE)) {
            $totalUser = User::count();
            $data['user'] = ['total' => $totalUser, 'statistic' => [[20, 10, 50, 30, 40, 20, 50], [20, 10, 50, 30, 40, 20, 50]]];
        }
        if ($user->hasRole(['admin', 'manager']) || $user->can(Acl::PERMISSION_DASHBOARD_SCHEDULE_MANAGE)) {
            $totalSchedule = Schedule::where('is_deleted', false)->count();
            $data['schedule'] = ['total' => $totalSchedule, 'statistic' => [[20, 10, 50, 30, 40, 20, 50], [20, 10, 50, 30, 40, 20, 50]]];
        }
        if ($user->hasRole(['admin', 'manager']) || $user->can(Acl::PERMISSION_DASHBOARD_CONTACT_MANAGE)) {
            $totalContact = Contact::where('is_deleted', false)->count();
            $data['contact'] = ['total' => $totalContact, 'statistic' => [[20, 10, 50, 30, 40, 20, 50], [20, 10, 50, 30, 40, 20, 50]]];
        }
        if ($user->hasRole(['admin', 'manager']) || $user->can(Acl::PERMISSION_DASHBOARD_SEO_MANAGE)) {
            $totalSeo = Seo::count();
            $data['seo'] = ['total' => $totalSeo, 'statistic' => [[20, 10, 50, 30, 40, 20, 50], [20, 10, 50, 30, 40, 20, 50]]];
        }

        return response()->json(['data' => $data], 200);
    }
}
