<?php

namespace App\Http\Controllers;

use App\Models\Item;
use App\Models\Offer;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class UserOffersController extends Controller
{

    public function index(Request $request)
    {
        $user = $request->user();
        $offersArr = collect()
            ->concat($user->offersFromUser()->get())
            ->concat($user->offersToUser()->get());

        return view('users.singl_offers', ['user' => $user, 'offers' => $offersArr ?? collect()]);
    }

    public function multiExchange()
    {

        $user = Auth::user();

        $offers = DB::table('offers')->select('offers.*')
            ->join('items', function ($join) {
                $join->on('item_id', 'items.id')
                    ->orOn('item_offer_id', 'items.id');
            })
            ->where('items.user_id', $user->id)
//            ->groupBy('items_exchange.item_id')
            ->get();

        $itemsArr = [];
        foreach ($offers as $offer) {
            $itemsArr[] = &$offer->item_id;
            $itemsArr[] = &$offer->item_offer_id;
        }
        $items = Item::with('user')->find(array_unique($itemsArr));

        $itemsArray = [];

        foreach ($items as $item) {
            $itemsArray[$item->id] = $item;
        }

        foreach ($offers as $offer) {
            $offersArr[$offer->item_id]['id'] = $offer->id;
            $offersArr[$offer->item_id]['item'] = $itemsArray[$offer->item_id];
            $offersArr[$offer->item_id]['offer'][$offer->id] = $itemsArray[$offer->item_offer_id];
        }


        return view('users.offers', ['offers' => $offersArr ?? collect()]);
    }

    public function offersStatusAJAX(Request $request)
    {
        return dump($request->json()->all());
    }

    public function archive()
    {
        $user = Auth::user();
        $offersArr = collect()
            ->concat($user->offersFromUser()->onlyTrashed()->get())
            ->concat($user->offersToUser()->onlyTrashed()->get());
//        foreach ($offersArr as $offer){
//            $offer->items;
//        }
        return view('users.offers_archive', ['user' => $user, 'offers' => $offersArr ?? collect()]);
    }
}
