<?php

namespace App\Http\Resources\Reports\SupplyChain;


use App\Models\AssemblyProducts;
use App\Models\Brands;
use App\Models\GeneralDaily;
use App\Models\ItemsGroups;
use App\Models\ProductSales;
use App\Models\ProductsQty;
use App\Models\ProductUnits;
use App\Models\ReciptVoucherDetails;
use App\Models\Sales;
use Illuminate\Http\Resources\Json\JsonResource;
use DB;
use Auth;

class ProductSalesGroupsReportApiResources extends JsonResource
{


    public function toArray($request)
    {


        $lang = $request->header('lang', '');
        $From = $request->get('From');
        $To = $request->get('To');
        $Group = $request->get('Group');
        $Brand = $request->get('Brand');


        $Group_Name = Brands::find($this->id);


        $qty = ProductSales::
        whereRelation('Product', 'Group', $this->id)
            ->whereRelation('Sales', function ($query) use ($From, $To) {
                return $query->whereBetween('Date', [$From, $To]);

            })
            ->get()->sum('Qty');

        $tot = ProductSales::
        whereRelation('Product', 'Group', $this->id)
            ->whereRelation('Sales', function ($query) use ($From, $To) {
                return $query->whereBetween('Date', [$From, $To]);

            })
            ->get()->sum('Total_Net');


        if ($lang == 'ar') {
            $xName = $Group_Name->Name;

        } else {
            $xName = $Group_Name->Name;

        }



        $data=[

            'Name'=>$xName
            ,'Total_Qty'=>$qty
            ,'Total_Price'=>$tot
            ,'details'=>$this->when(!empty($this->id), function () {

                $From = request('From');
                $To = request('To');
                $Group = request('Group');
                $Brand = request('Brand');

                if(!empty($Group)){
                    $Sales = ProductSales::

                    whereRelation('Sales', function ($query) use ($From, $To) {
                        return $query->whereBetween('Date', [$From, $To]);

                    })
                        ->whereRelation('Product', 'Group', $this->id)
                        ->distinct(['Product_Code'])
                        ->get();


                }elseif($Brand){

                    $Sales = ProductSales::

                    whereRelation('Sales', function ($query) use ($From, $To) {
                        return $query->whereBetween('Date', [$From, $To]);

                    })
                        ->whereRelation('Product', 'Brand', $this->id)
                        ->distinct(['Product_Code'])
                        ->get();



                }


                $details=DetailsGroupBrandSalesApiResources::collection($Sales);

                return $details;
            }),



        ];


        return $data ;







    }

}
