<?php

namespace MtcPharmacy\Bundles\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Routing\Controller as BaseController;
use MtcPharmacy\Bundles\Classes\Bundle;
use MtcPharmacy\Bundles\Classes\BundleItem;
use MtcPharmacy\Bundles\Classes\BundleType;
use MtcPharmacy\Bundles\Classes\BundleTypeItem;
use Illuminate\Support\Collection;


class BundlesCheckoutController extends BaseController
{

    public function add_to_basket(Request $request)
    {
        $bundle = Bundle::find($request->input('bundle_id'));
        if ($bundle) {
            $bundle->authorise_access_by_current_user();
        }

        $clean_bundle = self::addBundletypeItemsToBasket($request->input('item_ids'), $bundle);

        if ($request->ajax()) {
            return [
                'success' => true,
                'bundle' => $clean_bundle->load('items'),
            ];
        } else {
            return redirect('/shop/checkout/basket.php');
        }
    }



    /*** HELPERS ***/

    public static function addBundletypeItemsToBasket(array $bundletype_items_ids, Bundle $bundle = null)
    {
        $bundle_type__items = BundleTypeItem::findMany($bundletype_items_ids);

        $basket = \Basket::getCurrent();

        $clean_bundle = self::get_empty_bundle($bundle, $basket, $bundle_type__items);
        $clean_bundle->addItems($bundle_type__items);
        $clean_bundle->addToBasket($basket);

        return $clean_bundle;
    }


    private static function get_empty_bundle(Bundle $bundle = null, \Basket $basket, Collection $bundle_type_items)
    {
        if ($bundle) {

            $bundle->items()->delete();

            foreach ($basket->eloquent()->items as $basket_item) {
                if ($basket_item->bundle_id == $bundle->id) {
                    $basket_item->delete();
                }
            }

        } else {
            $bundle = new Bundle();
            $bundle->type()->associate($bundle_type_items->first()->bundle_type);
            $bundle->save();
        }

        return $bundle;
    }

}
