<?php

namespace App\Http\Controllers;

use App\Models\PriceList;
use App\Models\ProfitCenter;
use App\Repositories\SupplierRepository;
use App\Services\SupplierService;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;

class SupplierController extends Controller
{
    protected SupplierService $service;

    public function __construct(SupplierService $service)
    {
        $this->service = $service;
    }

    /**
     * Display a listing of the resource.
     */
    public function index(): View
    {
        return view('modules.supplier.index');
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(): Response|JsonResponse
    {
        return response()->noContent();
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): Response|JsonResponse
    {
        return response()->noContent();
    }

    /**
     * Display the specified resource.
     */
    public function show(int $SupplierId): View|Response|JsonResponse
    {
        if (\request()->get('t')) {
            $supplierData = $this->service->getWithAllRelations($SupplierId);
            dd($supplierData);

            $priceLists = PriceList::where('supplier_id', $SupplierId)->with('attachment');
            $PriceList = $priceLists->where('available', '<=', Carbon::now()->format('Y-m-d'));
            if ($priceLists->orderBy('available', 'desc')->first()) {
                $PriceList = $priceLists->orderBy('available', 'desc')->first();

            }
            dd($PriceList->toArray());
        }

        if (! $supplierData = $this->service->getWithAllRelations($SupplierId)) {
            return response()->noContent();
        }
        $viewData = [];
        $needData = ['name', 'openHours', 'ordersDeadline', 'minOrderValue', 'contact', 'note'];
        foreach ($needData as $pointer) {
            $viewData[$pointer] = $supplierData[$pointer];
        }
        $viewData['product_group'] = [];
        foreach ($supplierData['product_group'] as $productGroup) {
            $viewData['product_group'][] = [
                'name' => $productGroup['name'],
                'type' => $productGroup['type'],
            ];
        }

        $viewData['service'] = [];
        $supplierData['service'] = collect($supplierData['service'])->sortBy('name')->toArray();
        foreach ($supplierData['service'] as $service) {
            $viewData['service'][] = [
                'name' => $service['name'],
                'id' => $service['id'],
            ];
        }
        $retData = [];
        $retData['supplierData'] = $viewData;
        $retData['attachment'] = $supplierData['attachment'];
        unset($viewData,$needData,$supplierData);

        $retData['files'] = [];
        /*
         * PriceList file
         */
        $priceLists = PriceList::where('supplier_id', $SupplierId)->with('attachment');
        $PriceList = $priceLists->where('available', '<=', Carbon::now()->format('Y-m-d'));
        if ($priceLists->orderBy('available', 'desc')->first()) {
            $PriceList = $priceLists->orderBy('available', 'desc')->first();
            $retData['files']['priceList'] = $PriceList->toArray();
            unset($priceLists,$PriceList);
        }

        return view('modules.supplier.show')->with($retData);
        dd($retData, $supplierData);

        $retData['supplierData'] = $supplierData;
        $retData['testMode'] = ($this->testMode) ? 'true' : 'false';
        $retData['init'] = false;
        $ProductGroup = new \App\Models\ProductGroup;
        $productGroupArray = $ProductGroup->allWithParents(2);
        $retData['productGroup'] = $productGroupArray;
        $retData['profitCenter'] = ProfitCenter::orderBy('name', 'asc')->get()->toArray();

        return view('modules.supplier.show')->with($retData);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(int $SupplierId): Response|JsonResponse
    {
        return response()->noContent();
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, int $SupplierId): Response|JsonResponse
    {
        return response()->noContent();
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(int $SupplierId): Response|JsonResponse
    {
        return response()->noContent();
    }

    public function getDataTableContent(): JsonResponse
    {

        $accessSupplier = ProfitCenter::with('suppliers')->find(auth()->user()->profitCenters->first()->id)->suppliers->pluck('id')->toArray();
        // $suppliers=Supplier::all()->toArray();
        $repo = new SupplierRepository;
        $suppliers = $repo->allWithRelations();
        $suppliers = array_filter($suppliers, function ($item) use ($accessSupplier) {
            if (in_array($item['id'], $accessSupplier)) {
                return true;
            }

            return false;
        });
        // dd($suppliers);
        // $repository=new  SupplierRepository();
        $ret = ['data' => []];
        // $items=$repository->getQueryWithRelations()->orderBy('name')->get()->toArray();
        foreach ($suppliers as $item) {
            // dd(collect($item['product_group'])->pluck('name')->all());
            // dd(collect($item['product_group'])->implode('name',','));
            $data['id'] = $item['id'];
            $data['name'] = $item['name'];
            $data['hooreycaId'] = $item['hooreycaId'];
            $data['nameId'] = $item['nameId'];
            $data['product_group'] = collect($item['product_group'])->implode('name', ', ');
            $data['service'] = collect($item['service'])->implode('name', ', ');
            $data['created_at'] = formatterDateTime($item['created_at']);
            $data['canSeeInOrder'] = $item['canSeeInOrder'];
            $ret['data'][] = $data;
        }

        return \response()->json($ret);
    }
}
