<?php

namespace Mtc\Shop\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Mtc\Shop\Item;
use Mtc\Shop\Item\ItemsDisplayTag;

class DisplayTagsController extends \App\Http\Controllers\Controller
{
    public function save_product_data($product_id, Request $request)
    {
        $product = Item::findOrFail($product_id);

        $tags_to_save = [];

        $group_name = $request->input('group_name', 'a');

        $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', 'a');
        $data = $product->display_tags->where('group_name', $group_name)->toArray();

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