<?php

namespace Filanco\Cms\Http\Controllers;

use Illuminate\Http\Request;
use Filanco\Cms\Facades\Cms;

class CmsMenuController extends Controller
{
    public function builder($id)
    {
        Cms::canOrFail('edit_menus');

        $menu = Cms::model('Menu')->findOrFail($id);

        $isModelTranslatable = isBreadTranslatable(Cms::model('MenuItem'));

        return view('Cms::menus.builder', compact('menu', 'isModelTranslatable'));
    }

    public function delete_menu($menu, $id)
    {
        Cms::canOrFail('delete_menus');

        $item = Cms::model('MenuItem')->findOrFail($id);

        $item->deleteAttributeTranslation('title');

        $item->destroy($id);

        return redirect()
            ->route('Cms.menus.builder', [$menu])
            ->with([
                'message'    => 'Successfully Deleted Menu Item.',
                'alert-type' => 'success',
            ]);
    }

    public function add_item(Request $request)
    {
        Cms::canOrFail('add_menus');

        $data = $this->prepareParameters(
            $request->all()
        );

        $data['order'] = 1;

        $highestOrderMenuItem = Cms::model('MenuItem')->where('parent_id', '=', null)
            ->orderBy('order', 'DESC')
            ->first();

        if (!is_null($highestOrderMenuItem)) {
            $data['order'] = intval($highestOrderMenuItem->order) + 1;
        }

        // Check if is translatable
        $_isTranslatable = isBreadTranslatable(Cms::model('MenuItem'));
        if ($_isTranslatable) {
            // Prepare data before saving the menu
            $trans = $this->prepareMenuTranslations($data, 'add');
        }

        $menuItem = Cms::model('MenuItem')->create($data);

        // Save menu translations
        if ($_isTranslatable) {
            $menuItem->setAttributeTranslations('title', $trans, true);
        }

        return redirect()
            ->route('Cms.menus.builder', [$data['menu_id']])
            ->with([
                'message'    => 'Successfully Created New Menu Item.',
                'alert-type' => 'success',
            ]);
    }

    public function update_item(Request $request)
    {
        Cms::canOrFail('edit_menus');

        $id = $request->input('id');
        $data = $this->prepareParameters(
            $request->except(['id'])
        );

        $menuItem = Cms::model('MenuItem')->findOrFail($id);

        if (isBreadTranslatable($menuItem)) {
            $trans = $this->prepareMenuTranslations($data, 'edit');

            // Save menu translations
            $menuItem->setAttributeTranslations('title', $trans, true);
        }

        $menuItem->update($data);

        return redirect()
            ->route('Cms.menus.builder', [$menuItem->menu_id])
            ->with([
                'message'    => 'Успешно сохранено Menu Item.',
                'alert-type' => 'success',
            ]);
    }

    public function order_item(Request $request)
    {
        $menuItemOrder = json_decode($request->input('order'));

        $this->orderMenu($menuItemOrder, null);
    }

    private function orderMenu(array $menuItems, $parentId)
    {
        foreach ($menuItems as $index => $menuItem) {
            $item = Cms::model('MenuItem')->findOrFail($menuItem->id);
            $item->order = $index + 1;
            $item->parent_id = $parentId;
            $item->save();

            if (isset($menuItem->children)) {
                $this->orderMenu($menuItem->children, $item->id);
            }
        }
    }

    protected function prepareParameters($parameters)
    {
        switch (array_get($parameters, 'type')) {
            case 'route':
                $parameters['url'] = null;
                break;
            default:
                $parameters['route'] = null;
                $parameters['parameters'] = '';
                break;
        }

        if (isset($parameters['type'])) {
            unset($parameters['type']);
        }

        return $parameters;
    }

    /**
     * Prepare menu translations.
     *
     * @param array  $data   menu data
     * @param string $action add or edit action
     *
     * @return JSON translated item
     */
    protected function prepareMenuTranslations(&$data, $action)
    {
        $key = $action.'_title_i18n';
        $trans = json_decode($data[$key], true);

        // Set field value with the default locale
        $data['title'] = $trans[config('Cms.multilingual.default', 'en')];

        unset($data[$key]);             // Remove hidden input holding translations
        unset($data['i18n_selector']);  // Remove language selector input radio

        return $trans;
    }
}
