<?php

namespace App\Http\Controllers\Shop;

use App\Http\Controllers\Controller;
use App\Repositories\Core\User\ShopCart;
use App\Repositories\Shop\Baskets;
use App\Repositories\Shop\Contents;
use App\Repositories\Shop\Customers;
use App\Repositories\Shop\Offers;
use App\Repositories\Shop\Orders;
use App\Repositories\Users;
use Illuminate\Http\Request;

class BasketController extends Controller
{
    public function getPrice(Request $request)
    {
        $offerId = $request->input('offer_id');
        $quantity = $request->input('quantity') ?? 1;
        $offer = Offers::getPrice($offerId, $quantity);
        $price = $offer ? $offer->price_taxed : 0;

        return number_format($quantity * $price, 2);
    }

    public function addBasket(Request $request)
    {
        $offerId = $request->input('offer_id');
        $quantity = $request->input('quantity') ?? 1;
        $update = $request->input('update') ?? false;

        return Baskets::addBasket($offerId, $quantity, $update);
    }

    public function modalBasket($offerId, $quantity = 1)
    {
        $data = [
            'offer' => Offers::getFull($offerId)->toArray(),
            'basket' => Baskets::addBasket($offerId, $quantity),
        ];

        return view('Shop.Baskets.partials.modalBasket', $data);
    }

    public function basket()
    {
        $data = [
            'basket' => Baskets::getBasket(),
            'sale_channel' => Customers::getSaleChannel(),
            'header' => Contents::getBasketContent(),
        ];

        return view('Shop.Baskets.basket', $data);
    }

    public function getBasket()
    {
        $data = ShopCart::getContent();

        return response()->json(['data' => $data, 'code' => '200']);
    }

    public function countBasket()
    {
        return ShopCart::count();
    }

    public function getBasketTotal($deliveryId = false, $deliveryTypeId = false)
    {
        $basket = Baskets::getBasketTotal($deliveryId, $deliveryTypeId);
        $data = [
            'basket' => $basket,
            'sale_channel' => $basket['sale_channel'] ?? null,
        ];

        return view('Shop.Baskets.partials.basketTotal', $data);
    }

    public function getSummary()
    {
        $data = ShopCart::getSummary();

        return response()->json(['data' => $data, 'code' => '200']);
    }

    public function order(Request $request)
    {
        ShopCart::clear();
        $data = $request->all();
        unset($data['_token']);
        $data['user_id'] = Customers::getId();
        Orders::saveOrder($data);

        return response()->json(['code' => '200']);
    }

    public function clearBasket()
    {
        return ShopCart::clear();
    }
}
