<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\TagMaster;
use App\CategoryMaster;
use App\ProductTag;
use App\Product;
use Auth;

class TagMasterController extends Controller
{
	public function __construct()
    {
        $this->middleware('auth');
    }
	
	public function index()
	{	
		$tag = TagMaster::all();
		return view('tag/index',compact('tag'));
	}

	public function store(Request $request)
	{	
		
		
		if($request->get('tag_id') != NULL){
			$update = TagMaster::where('id','=',$request->get('tag_id'))
								->update([
											'name' => strtoupper(trim($request->get('tag')))
										]);
			return redirect()->route('tag_master.index')->with(['update' => true]);
		}
		else{
			$exist = TagMaster::where('name','=',strtoupper(trim($request->get('tag'))))->count();
			
			if($exist != 0){
				return redirect()->route('tag_master.index')->with(['exist' => true]);
			}

			$insert = TagMaster::create([
											'name' => strtoupper(trim($request->get('tag')))
										]);
			return redirect()->route('tag_master.index')->with(['message' => true]);
		}
		
	}

	public function edit(Request $request)
	{
		$id = $request->get('option');
		$tag = TagMaster::find($id);

		return $tag;
	}

	public function delete(Request $request)
	{
		TagMaster::where('id','=',$request->get('option'))->delete();
	}

	public function mapIndex($id)
	{
        $categories = CategoryMaster::orderBy('category')->get();
        $products   = NULL;
        $tagId = $id; 
        $tagPdct  = ProductTag::where('tag_id','=',$id)->pluck('product_id')->toArray();
        $selctCat  = NULL;
		return view('tag/map_tag',compact('categories','products','tagId','tagPdct','selctCat'));
	}

	public function mapShow(Request $request)
	{
		$tagPdct  = ProductTag::where('tag_id','=',$request->get('tag_id'))
                                    ->pluck('product_id')->toArray(); 
        $tagId      = $request->get('tag_id');  
        $categories = CategoryMaster::orderBy('category')->get();
        $products   = Product::where('category_id','=',$request->get('category'))
                             ->orderBy('name')->get();
        $selctCat   = $request->get('category');

		return view('tag/map_tag',compact('categories','products','tagId','tagPdct','selctCat'));
	}

	public function addProduct(Request $request)
	{
		$product = ProductTag::create(array('tag_id'       => $request->get('option'),
       	                                    'product_id'   => $request->get('option1')));

        return $product;
	}

	public function deleteProduct(Request $request)
	{
	   $product = ProductTag::where('tag_id','=',$request->get('option'))
	                        ->where('product_id','=',$request->get('option1'))->delete();

        return $product;	
	}
}