<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\AppBaseController;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class BondProductStockAPIController extends AppBaseController
{
    public function packedStock(Request $request){
        $bondProduct = $request->get('bond_product');
        $productType = $request->get('product_type');
        if(!empty($productType)){
            return DB::table('packed_stock_view')->selectRaw('bond_product, bond_name ,sum(qty) as qty, product_type, unit ')->groupBy('bond_product')->having('product_type', $productType)->orderBy('qty','DESC')->get();
        }else if(!empty($bondProduct)){
            return DB::table('packed_stock_view')->selectRaw("material_id, packing_id, bond_product, bond_name, sum(qty) as qty, product_type, unit")->groupBy('packing_id')->where('bond_product', '=', $bondProduct)->having('qty',">", 0)->orderBy('qty','DESC')->get();    
        }
        return DB::table('packed_stock_view')->selectRaw('product_type  , sum(qty) as qty, count(DISTINCT bond_product) as product_count')->groupBy('product_type')->orderBy('qty','DESC')->get();
    }

    public function rawStock(Request $request){
        $bondProduct = $request->get('bond_product');
        $productType = $request->get('product_type');
        if(!empty($productType)){
            return DB::table('stock_view')->selectRaw('bond_product, bond_name ,sum(qty) as qty, product_type, unit')->groupBy('bond_product')->having('product_type', $productType)->orderBy('qty','DESC')->get();
        }else if(!empty($bondProduct)){
            return DB::table('stock_view')->selectRaw('material_id, bond_product, bond_name, sum(qty) as qty, sum(rejection_under_size_qty) as rejection_under_size_qty, sum(rejection_over_size_qty) as rejection_over_size_qty, sum(rejection_shape_qty) as rejection_shape_qty,  (qty+ rejection_under_size_qty+rejection_over_size_qty+rejection_shape_qty)  as net_qty, unit')->groupBy('material_id')->where('bond_product', '=', $bondProduct)->having('qty',">", 0)->orderBy('qty','DESC')->get();    
        }
        return DB::table('packed_stock_view')->selectRaw('product_type, sum(qty) as qty, count(DISTINCT bond_product) as product_count')->groupBy('product_type')->orderBy('qty','DESC')->get();
    }
}