<?php

use Illuminate\Support\Facades\Event;
use Mtc\Shop\Events\AddToBasketEvent;
use Illuminate\Support\Facades\DB;
use MtcPharmacy\Bundles\Http\Controllers\BundlesCheckoutController;


$path="../";
require($path .'core/includes/header.inc.php');

$basket = Basket::getCurrent();

$basket_item_id = null;

$ajax = isset($_REQUEST['ajax']) ? true : false;


// Item ID must be passed along
if (empty($_REQUEST['id'])) {
    http_response_code(400);
    exit();
}
$id = (int)$_REQUEST['id'];

$item = new Item();
$item->Get_Item($id);


$default_request_values = [
    'size' => null,
];
$_REQUEST += $default_request_values;

if (
    $item->eloquent()->sizes->count() > 0 &&
    (
        empty($_REQUEST['size']) ||
        (
            is_array($_REQUEST['size']) &&
            !array_search(true, $_REQUEST['size'])
        )
    )
) {

    if ($ajax) {
        $response = [
            'status' => 'failed',
            'error' => 'size',
            'url' => !empty($_REQUEST['url_redirect']) ? $_REQUEST['url_redirect'] : ''
        ];

        if (is_array($_REQUEST['size'])) {
            $response['error'] = 'quantity';
        }
    } else {
        $params = [
            'error' => 'size'
        ];

        if (!empty($_REQUEST['size'])) {
            $params['size'] = clean_page($_REQUEST['size']);
        }
        $url = $item->url . '?' . http_build_query($params);
    }
} else {

    $assessmentID = null;
    if (!empty($_SESSION['assessments'][$item->id])) {
        // Assessment has been filled for a specific product
        $assessmentID = $_SESSION['assessments'][$item->id];
    } else {
        // Assessment has been filed for the whole category
        $mainCategory = $item->getMainCategory();
        if (!empty($mainCategory) && !empty($_SESSION['category_assessments'][$mainCategory->id])) {
            $assessmentID = $_SESSION['category_assessments'][$mainCategory->id];
        }
    }

    $params = [
        'id' => $id,
        'quantity' => 1,
        'PLU' => $item->epos_code,
        'assessment_id' => $assessmentID,
    ];

    if (QUICK_ADDTOBASKET === true && is_array($_REQUEST['size'])) {
        foreach ($_REQUEST['size'] as $size_id => $quantity) {
            if ($quantity > 0) {
                $params['quantity'] = $quantity;
                $size = DB::table('items_sizes')
                          ->where('id', $size_id)
                          ->first();
                if (!empty($size)) {
                    $params['size'] = $size->size;
                    $params['size_id'] = $size->id;
                    if (!empty($size->PLU)) {
                        $params['PLU'] = $size->PLU;
                    }
                } else {
                    $params['size'] = $item->is_groupbuy_container ? 'Group Buy' : 'One Size';
                    $params['size_id'] = 0;
                }
                $basket_item_id = $basket->Add_Item($params);
                $basket->set_expiry_time();

                $_SESSION['itemadded'] = true;
            }
        }

        // Add a log of how many times it's added to the basket
        $item->incrementNumBasket();
    } else {

     
        
        if (!empty($_REQUEST['quantity']) && (int) $_REQUEST['quantity'] > 0) {
            $params['quantity'] = (int) $_REQUEST['quantity'];
        }

        if ( empty($_REQUEST['size']) || $_REQUEST['size'] == 'false' ) {

            $params['size'] = $item->is_groupbuy_container ? 'Group Buy' : 'One Size';
            $params['size_id'] = 0;

        } else {

            $size = DB::table('items_sizes')
                      ->where('id', $_REQUEST['size'])
                      ->first();
            if (!empty($size)) {
                $params['size'] = $size->size;
                $params['size_id'] = $size->id;
                if (!empty($size->PLU)) {
                    $params['PLU'] = $size->PLU;
                }
            }

        }

        

        $basket_item_id = $basket->Add_Item($params);


        $basket->set_expiry_time();

        // Add a log of how many times it's added to the basket
        $item->incrementNumBasket();
        
        $_SESSION['itemadded'] = true;

        $url = $_REQUEST['url_redirect'] ?? '/shop/checkout/basket.php';
        
    }

    /*
     * Expecting results in the format of array
     * [
     *   'status' => ok|failed
     *   'error' => info about error
     *   'url' => redirect url non-ajax request
     * ]
     */
    $middleware_actions = Event::dispatch(new AddToBasketEvent($basket, $member, $item, $params, $_REQUEST));

    if (!empty(array_filter($middleware_actions))) {
        /**
         * fetch the last non-empty action
         * Getting last one because quick-buy will be defined last
         */
        $response = end(array_filter($middleware_actions));
        $url = !empty($response['url']) ? $response['url'] : $item->url;
    }

    if (empty($response) && !empty($_REQUEST['add-bag'])) {
        if ($ajax) {

            if(!empty($_REQUEST['url_redirect'])) {
                $url_redirect = $_REQUEST['url_redirect'];
            } else {
                $url_redirect = '/shop/checkout/basket.php';
            }
            $response = [
                'status' => 'ok',
                'url' => $url_redirect
            ];
        } else {
            $url = '/shop/checkout/basket.php';
        }
    }
}




if ($ajax) {
    header('Content-Type: application/json');
    echo json_encode($response);
} else {
    header("Location:" . $url);
    exit();
}
