<?php

namespace Mtc\Shop\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Mtc\Shop\Category;
use Mtc\Shop\Item;
use Mtc\Shop\Category\CategoriesDisplayTag;
use Mtc\Shop\Item\ItemsDisplayTag;


class DisplayTagsController extends \App\Http\Controllers\Controller
{

    public function save_category_data($category_id, Request $request)
    {
        $category = Category::findOrFail($category_id);

        $tags_to_save = [];

        $group_name = $request->input('group_name', CategoriesDisplayTag::DEFAULT_GROUP_NAME);

        $input_data = $request->input('data');
        foreach ($input_data as $line) {
            $t = new CategoriesDisplayTag();
            $t->label = $line['label'];
            $t->icon_id = $line['icon_id'];
            $t->group_name = $group_name;

            $tags_to_save[] = $t;
        }

        $category->display_tags()->where('group_name', $group_name)->delete();
        $category->display_tags()->saveMany($tags_to_save);

        return [
            'success' => true,
        ];
    }



    public function get_category_data($category_id, Request $request)
    {
        $category = Category::findOrFail($category_id);

        $group_name = $request->input('group_name', CategoriesDisplayTag::DEFAULT_GROUP_NAME);

        $data = $category->display_tags->where('group_name', $group_name)->toArray();

        return array_values($data); // remove array keys
    }


    public function save_product_data($product_id, Request $request)
    {
        $product = Item::findOrFail($product_id);

        $tags_to_save = [];

        $group_name = $request->input('group_name', CategoriesDisplayTag::DEFAULT_GROUP_NAME);

        $input_data = $request->input('data');
        foreach ($input_data as $line) {
            $t = new ItemsDisplayTag();
            $t->label = $line['label'];
            if ($line['icon_id']) {
                $t->icon_id = $line['icon_id'];
            }
            $t->group_name = $group_name;

            $tags_to_save[] = $t;
        }

        $product->display_tags()->where('group_name', $group_name)->delete();
        $product->display_tags()->saveMany($tags_to_save);

        return [
            'success' => true,
        ];
    }


    public function get_product_data($product_id, Request $request)
    {
        $product = Item::findOrFail($product_id);

        $group_name = $request->input('group_name', CategoriesDisplayTag::DEFAULT_GROUP_NAME);
        $data = $product->display_tags->where('group_name', $group_name)->toArray();

        return array_values($data); // remove array keys
    }

}
