<?php
namespace App\Http\Controllers\Api;
use App\Product;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\CreateProductRequest;
use App\Http\Requests\Api\UpdateProductRequest;
class ProductController extends Controller
{
public function index() {
$products = new Product();
$products = $this->fetchAll($products);
$products = $this->order($products);
$products = $this->search($products);
$products = $this->paginate($products);
return $this->responseData($products);
}
public function store(CreateProductRequest $request)
{
$productInfo = $request->only('employee_id','type','diameter','softness','color', 'origin', 'long', 'height', 'amount', 'remark', 'date');
if($productInfo['remark'] == null) {
$productInfo['remark'] = "";
}
$product = new Product();
$product->fill($productInfo);
$product->paid = false;
$product->save();
return $this->responseSuccess();
}
public function update(UpdateProductRequest $request, $id)
{
if($id == null || $id == ''){
return $this->responseError(config('errors.ID_MUST_BE_NOT_NULL'));
}
$product = Product::find($id);
if(!$product){
return $this->responseError(config('errors.PRODUCT_NOT_EXISTS'));
}
$productInfo = $request->only('employee_id','type','diameter','softness','color', 'origin', 'long', 'height', 'amount', 'remark', 'date');
if($productInfo['remark'] == null) {
$productInfo['remark'] = "";
}
$product->fill($productInfo)->save();
return $this->responseSuccess();
}
public function destroy($id)
{
if($id == null || $id == ''){
return $this->responseError(config('errors.ID_MUST_BE_NOT_NULL'));
}
$product = Product::find($id);
if(!$product){
return $this->responseError(config('errors.PRODUCT_NOT_EXISTS'));
}
$product->delete();
return $this->responseSuccess();
}
private function search($products){
if(request()->employee_id != null) {
$products->where('employee_id', request()->employee_id);
}
if(request()->type != null) {
$products->where('type', request()->type);
}
if(request()->diameter != null) {
$products->where('diameter', request()->diameter);
}
if(request()->softness != null) {
$products->where('softness', request()->softness);
}
if(request()->color != null) {
$products->where('color', request()->color);
}
if(request()->origin != null) {
$products->where('origin', request()->origin);
}
if(request()->long != null) {
$products->where('long', request()->long);
}
if(request()->height != null) {
$products->where('height', request()->height);
}
if(request()->from_date != null) {
$products->where('date', '>=', request()->from_date);
}
if(request()->to_date != null) {
$products->where('date', '<=', request()->to_date);
}
return $products;
}
}