<?php

namespace App\Http\Controllers;

use App\Http\Resources\MenuResource;
use Illuminate\Support\Facades\Cache;
use App\Menu;

class MenuController extends Controller
{
    const ITEM_PER_PAGE = 25;

    public function index()
    {
        $list = Menu::with('slider')->select('id', 'name', 'type', 'link', 'category_id', 'parent_id')
        ->isPublished()
        ->orderBy('order')
        ->orderBy('id')
        ->get();
        $rs = $this->getChildItems($list, 0);

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

    public function getChildItems($list, $parent = 0) {
        $rs = [];
        foreach ($list as $item) {
            if($item->parent_id == $parent) {
                $item['elements'] = $this->getChildItems($list, $item->id);
                $item['hasChild'] = (count($item['elements']) > 0) ? true : false;
                $rs[] = $item;
            }
        }

        return $rs;
    }

    public function header() {
        $list = Cache::remember('menu_header', (7*24*60*60), function () {
            $items = Menu::with('slider')->select('id', 'name', 'type', 'link', 'position')
                ->isPublished()
                ->where('position', 'header')
                ->orderBy('order')
                ->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']);
    }

    public function footer() {
        $list = Cache::remember('menu_footer', (7*24*60*60), function () {
            $items = Menu::with('slider')->select('id', 'name', 'type', 'link', 'position')
                ->isPublished()
                ->where('position', 'footer')
                ->orderBy('order')
                ->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']);
    }
}
