<?php

namespace App\Http\Controllers;

use App\Http\Resources\AreaResource;
use App\Http\Resources\AreaSelectionResource;
use App\Area;
use App\Indexer\AreaIndex;
use App\Indexer\AreaStaIndex;
use App\Shop;
use App\FortuneReview;
use App\Fortuneteller;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;

class AreaController extends Controller
{
    const ITEM_PER_PAGE = 20;

    public function index()
    {
        $list = Area::select('id', 'name', 'slug', 'logo', 'show_search', 'parent_id', 'position')
            ->isPublished()
            ->orderBy('position')
            ->orderBy('id')
            ->get();

        return AreaResource::collection($list);
    }

    public function top()
    {
        $list = Cache::remember('area_top_sta', (7 * 24 * 60 * 60), function () {
            //$items = AreaStaIndex::all();
            $areas = Area::select('id', 'name', 'slug', 'logo', 'parent_id', 'show_top')
                ->isPublished()
                ->orderBy('position')
                ->orderBy('id')
                ->get();

            $rs = [];
            foreach ($areas as $item) {
                if ($item->show_top == 1) {
                    $listAreaIds = $this->getAreaItem($areas, $item->id);
                    $listAreaIds[] = $item->id;
                    $shopListId = Shop::select('id')
                        ->isPublished()
                        ->whereIn('area_id', $listAreaIds)
                        ->pluck('id')
                        ->toArray();
                    $fortuneTellerCount = Fortuneteller::isPublished()->whereIn('shop_id', $shopListId)->count();

                    $dataItem = [
                        'id'           => $item->id,
                        'name'         => $item->name,
                        'slug'         => $item->slug,
                        'logo'         => $item->logo,
                        'teller_total' => $fortuneTellerCount,
                        'shop_total'   => count($shopListId),
                    ];

                    $rs[] = $dataItem;
                }
            }

            return ['items' => $rs, 'lastModify' => (gmdate('D, d M Y H:i:s') . ' GMT')];
        });

        return response()->json(['data' => $list['items']], 200)->header('Last-Modified', $list['lastModify']);

        /*$list = Area::select('id', 'name',  'slug', 'logo', 'parent_id', 'position')
            ->isPublished()
            ->where('show_top', true)
            ->orderBy('position')
            ->orderBy('id')
            ->limit(30)
            ->get();
        return AreaResource::collection($list);*/
    }

    private function getAreaItem($list, $parentId)
    {
        $rs = [];
        if ($parentId != null && $parentId != "") {
            foreach ($list as $item) {
                if ($item->parent_id == $parentId) {
                    $rs[] = $item->id;
                    $child = $this->getAreaItem($list, $item->id);
                    $rs = array_merge($rs, $child);
                }
            }
        }
        return $rs;
    }

    public function search()
    {
        $list = Cache::remember('area_search', (7 * 24 * 60 * 60), function () {
            $items = Area::with('parent')->select('id', 'name', 'slug', 'parent_id', 'show_search')
                ->isPublished()
                ->where('is_activated', true)
                ->orderBy('position')
                ->orderBy('id')
                ->get();

            return ['items' => $items, 'lastModify' => (gmdate('D, d M Y H:i:s') . ' GMT')];
        });

        return response()->json(['data' => $list['items']], 200)->header('Last-Modified', $list['lastModify']);


        /*$list = Area::with('parent')->select('id', 'name', 'slug', 'parent_id', 'show_search')
            ->isPublished()
            ->orderBy('position')
            ->orderBy('id')
            ->get();

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

    public function getBySlug($slug = '')
    {
        $area = Area::select('id', 'name', 'slug', 'title', 'sub_title', 'link')
            ->isPublished()
            ->where('slug', $slug)
            ->first();
        if (!isset($area)) return response()->json(['errors' => 'Area is not valid'], 403);
        return response()->json(['data' => $area], 200);
    }

    public function childList(Request $request)
    {
        $params = $request->all();
        $limit = Arr::get($params, 'limit', static::ITEM_PER_PAGE);
        $page = Arr::get($params, 'page', 1);

        $list = Cache::remember('area_child_' . $page, (7 * 24 * 60 * 60), function () use ($limit) {
            $items = AreaIndex::select('id', 'name', 'slug', 'logo', 'parent_id', 'position')
                ->where('is_activated', true)
                ->where('parent_id', '!=', 0)
                ->orderBy('position')
                ->paginate($limit);

            return ['items' => $items, 'lastModify' => (gmdate('D, d M Y H:i:s') . ' GMT')];
        });

        return AreaResource::collection($list['items'])->response()->header('Last-Modified', $list['lastModify']);

        /*$list = AreaIndex::select('id', 'name',  'slug', 'logo', 'parent_id', 'position')
            ->where('is_activated', true)
            ->where('parent_id', '!=', 0)
            ->orderBy('position')
            ->paginate($limit);
        return AreaResource::collection($list)->response()->header('Last-Modified', 'Sat, 01 May 2021 07:44:32 GMT');*/
    }

    public function selectionList(Request $request)
    {
        $params = $request->all();
        $limit = Arr::get($params, 'limit', static::ITEM_PER_PAGE);
        $page = Arr::get($params, 'page', 1);

        $list = Cache::remember('area_selection_' . $page, (7 * 24 * 60 * 60), function () use ($limit) {
            $items = AreaIndex::select('id', 'name', 'slug')
                ->where('is_activated', true)
                ->orderBy('parent_id')
                ->orderBy('position')
                ->paginate($limit);

            return ['items' => $items, 'lastModify' => (gmdate('D, d M Y H:i:s') . ' GMT')];
        });

        return AreaSelectionResource::collection($list['items'])->response()->header('Last-Modified', $list['lastModify']);
    }

    public function rootArea(Request $request)
    {
        $params = $request->all();
        $limit = Arr::get($params, 'limit', 6);

        $list = Cache::remember('area_root_' . $limit, (7 * 24 * 60 * 60), function () use ($limit) {
            $items = Area::with('item')->select('id', 'name', 'slug', 'parent_id', 'position')
                ->isPublished()
                ->where('parent_id', 0)
                ->orderBy('position')
                ->limit($limit)
                ->get();

            return ['items' => $items, 'lastModify' => (gmdate('D, d M Y H:i:s') . ' GMT')];
        });

        return response()->json(['data' => $list['items']], 200)->header('Last-Modified', $list['lastModify']);

        /*$items = Area::with('item')->select('id', 'name',  'slug', 'parent_id')
            ->isPublished()
            ->where('parent_id', 0)
            ->orderBy('position')
            ->orderBy('id')
            ->limit($limit)
            ->get();

        return response()->json(['data' => $items], 200)->header('Last-Modified', (gmdate('D, d M Y H:i:s') . ' GMT'));*/

    }

    public function statistic()
    {
        $list = Cache::remember('area_statistic', (7 * 24 * 60 * 60), function () {
            $shopTotal = Shop::where('is_deleted', false)->count();
            $reviewTotal = FortuneReview::count();
            $tellerTotal = Fortuneteller::where('is_deleted', false)->count();

            return ['items' => [
                "shopTotal"   => $shopTotal,
                "reviewTotal" => $reviewTotal,
                "tellerTotal" => $tellerTotal,
            ], 'lastModify' => (gmdate('D, d M Y H:i:s') . ' GMT')];
        });

        return response()->json(['data' => $list['items']], 200)->header('Last-Modified', $list['lastModify']);

        /*$shopTotal = Shop::where('is_deleted', false)->count();
        $reviewTotal = FortuneReview::count();
        $tellerTotal = Fortuneteller::where('is_deleted', false)->count();

        return response()->json(['data' => [
            "shopTotal"     => $shopTotal,
            "reviewTotal"   => $reviewTotal,
            "tellerTotal"   => $tellerTotal,
        ]], 200);*/
    }

}
