<?php

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


$exclude_header_inc = $exclude_header_inc ?? [];
$exclude_header_inc['not_for_ajax'] = true;

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

$executionStart = microtime(true);
$basket = Basket::getCurrent(false);

$basket_item_id = null;

$ajax = isset($_REQUEST['ajax']);
$response = null;


// 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, true);


$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 filled for one of the item's categories
        // Check all categories the item belongs to, not just the main one
        $itemCategoryIds = $item->getAllCategoryIDs() ?? [];
        foreach ($itemCategoryIds as $catId) {
            if (!empty($_SESSION['category_assessments'][$catId])) {
                $assessmentID = $_SESSION['category_assessments'][$catId];
                break;
            }
        }
    }

    // For doctor/pharmacy products that require assessment, redirect to assessment form if no valid assessment
    // Skip if assessment forms are disabled for this product
    $eloquentItem = $item->eloquent();
    if (empty($assessmentID) && in_array($item->product_type, ['doctor', 'pharmacy']) && (!$eloquentItem || !$eloquentItem->disable_assessment_forms)) {
        $mainCategory = $mainCategory ?? $item->getMainCategory();
        $formId = null;
        $categoryId = null;

        // Check item-level form_id first, then category-level
        if (!empty($item->form_id) && (int)$item->form_id > 0) {
            $formId = (int)$item->form_id;
            $categoryId = $mainCategory ? $mainCategory->id : 0;
        } elseif ($mainCategory && !empty($mainCategory->form_id) && (int)$mainCategory->form_id > 0) {
            $formId = (int)$mainCategory->form_id;
            $categoryId = $mainCategory->id;
        }

        if ($formId) {
            // Build assessment form URL
            $sizeParam = $_REQUEST['size'] ?? 0;
            $qtyParam = $_REQUEST['quantity'] ?? 1;
            $assessmentUrl = "/assessment/{$formId}?p={$item->id}&c={$categoryId}&s={$sizeParam}&q={$qtyParam}";

            if ($ajax) {
                $response = [
                    'status' => 'failed',
                    'error' => 'assessment_required',
                    'message' => 'Please complete the consultation form before adding this item to your basket.',
                    'url' => $assessmentUrl
                ];
                header('Content-Type: application/json');
                echo json_encode($response);
                exit();
            } else {
                header("Location:" . $assessmentUrl);
                exit();
            }
        }
    }

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

    if (QUICK_ADDTOBASKET === true && is_array($_REQUEST['size'])) {
        $requestedSizes = array_filter(
            $_REQUEST['size'],
            static function ($quantity) {
                return (int)$quantity > 0;
            }
        );

        $sizeIds = array_map('intval', array_keys($requestedSizes));
        $sizes = [];

        if (!empty($sizeIds)) {
            $sizes = Size::query()
                ->whereIn('id', $sizeIds)
                ->get()
                ->keyBy('id');
        }

        foreach ($requestedSizes as $size_id => $quantity) {
            $quantity = (int)$quantity;
            if ($quantity <= 0) {
                continue;
            }

            $params['quantity'] = $quantity;
            $sizeId = (int)$size_id;

            if (!empty($sizes) && $sizes->has($sizeId)) {
                $size = $sizes->get($sizeId);
                $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 {
            if ($size = Size::query()->find($_REQUEST['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 ($ajax && empty($response)) {
        $response = [
            'status' => 'ok',
            'basket_item_id' => $basket_item_id,
        ];

        if (!empty($_REQUEST['url_redirect'])) {
            $response['url'] = $_REQUEST['url_redirect'];
        }
    }

    if (!$ajax && empty($response) && !empty($_REQUEST['add-bag'])) {
        $url = '/shop/checkout/basket.php';
    }
}




if ($ajax) {
    if (config('app.debug')) {
        header('X-AddToBasket-Execution-Time: ' . number_format((microtime(true) - $executionStart), 4));
    }
    header('Content-Type: application/json');
    echo json_encode($response);
} else {
    if (config('app.debug')) {
        header('X-AddToBasket-Execution-Time: ' . number_format((microtime(true) - $executionStart), 4));
    }
    header("Location:" . $url);
    exit();
}
