<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;
use Auth;
class HomeController extends Controller
{
    public function settingGet(){
        $setting = DB::table('settings')->select('frontend_img_url','color','vat')->first();
        $auth = Auth::check();
        return response()->json([
            'setting'=>$setting,
            'auth'=>$auth,
        ]);
    }
    public function HomePage(){
        $ReadyProducts = DB::table('products')->where('stock','>',0)->select('type','product_name','selling_price','min_order','code','created_at','stock')->paginate(8);
        $SampleProducts = DB::table('products')->where('stock','<=',0)->select('type','product_name','highest_price','lowest_price','selling_price','min_order','code','created_at')->paginate(8);
        return response()->json([
            'ReadyProducts'=>$ReadyProducts,
            'SampleProducts'=>$SampleProducts,
        ]);
    }
    public function HomePageReady(Request $request, $sortBy){
        // return $request->all();
        if($request->filter == 'price'){
            $ReadyProducts = DB::table('products')->orderBy('selling_price',$request->price)->select('id','type','product_name','selling_price','min_order','code','created_at','stock','highest_price','lowest_price')->paginate(8);
        }else if($request->filter == 'stock'){
            $ReadyProducts = DB::table('products')->orderBy('stock',$request->stock)->select('id','type','product_name','selling_price','min_order','code','created_at','stock','highest_price','lowest_price')->paginate(8);
        }
        
        foreach($ReadyProducts as $ReadyProduct){
            $readyProdutImage[] = DB::table('images')->where(['product_id'=>$ReadyProduct->id])->orderBy('id','ASC')->select('name')->first();
        }
        return response()->json([
            'ReadyProducts'=>$ReadyProducts,
            'readyProductImage'=>$readyProdutImage
        ]);
    }
    public function HomePageSample($sortBy){
        $SampleProducts = DB::table('products')->where('stock','<=',0)->orderBy('id',$sortBy)->select('id','type','product_name','highest_price','lowest_price','selling_price','min_order','code','created_at')->paginate(8);
        foreach($SampleProducts as $ReadyProduct){
            $readyProdutImage[] = DB::table('images')->where(['product_id'=>$ReadyProduct->id])->orderBy('id','ASC')->select('name')->first();
        }
        return response()->json([
            'SampleProducts'=>$SampleProducts,
            'sampleProductImage'=>$readyProdutImage
        ]);
    }
}
