<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Category;
use App\Product;
use App\Settings;
use DataTables;
class ManageSearch extends Controller
{
    public function index()
    {
    	$data['categories'] = Category::all();
    	return view('manage.product.search')->with($data);
    }

    public function search(Request $request)
    {
    	$product = new Product();
    	$product = $product->newQuery();

    	if ($request->name) {
    		$product->whereTranslations('product_name', 'like', '%'.$request->name.'%');
    	}
    	if ($request->weight) {
    		$product->where('product_weight', $request->weight);
    	}
    	if ($request->price) {
    		$product->where('product_price', $request->price);
    	}
    	if ($request->margin) {
    		$product->where('product_margin', $request->margin);
    	}
    	if ($request->category) {
    		$product->join('category', 'category.id', '=', 'product.product_category')
    		->where('product_category', $request->category);
    	}

        $data = collect($product->orderBy('product.id', 'desc')->get());
        $products = $data->values()->all();

        return DataTables::of($products)
        	->addColumn('action', function($product) {
	    		return '
	    		<a href="'.route("manage.product.show", $product->id).'" class="btn btn-default btn-xs dt-info">
					<i class="fa fa-info"></i>
	    		</a>
	    		<a href="'.route("manage.product.edit", $product->id).'" class="btn btn-primary btn-xs dt-edit">
					<i class="fa fa-edit"></i>
	    		</a>
	         	<a href="'.route("manage.product.destroy", $product->id).'" class="btn btn-danger btn-xs dt-delete">
					<i class="fa fa-trash"></i>
	         	</a>';
	    	})
	    	->editColumn('product_category', function($product) {
	    		if (count($product->category)) {
	    			return $product->category->category_name;
    			}
	    	})
            ->editColumn('product_price', function($product) {
                $currency = Settings::where('setting_name','currency')->first();
                return $currency ? $currency->setting_value.' '.number_format($product->product_price, 0) : number_format($product->product_price, 0);
            })
            ->editColumn('product_margin', function($product) {
              if ($product->product_price && $product->product_cost) {
                $margin = ($product->product_price - $product->product_cost) / $product->product_price;
                return round($margin * 100). '%';
              } else {
                return 0;
              }
            })
	    	->addindexColumn()
	    	->make(true);
    }
}
