<?php

declare(strict_types=1);

// If DeliveryMethod is in the global namespace, keep this import; otherwise adjust.
use DeliveryMethod;
use Illuminate\Http\Request;
use Mtc\Modules\Members\Models\Member;
use Mtc\Plugins\BasketBuilder\Classes\BasketBuilder;

$path = '../../../';
require_once $path.'core/includes/header.inc.php';

/**
 * Force JSON responses for this endpoint.
 */
header('Content-Type: application/json; charset=utf-8');

/**
 * Convenience: always get the current request object.
 * In Laravel 11 this will be an instance of Illuminate\Http\Request.
 *
 * @var Request $req
 */
$req = request();

/**
 * Robust array reader: accepts native arrays or JSON-encoded strings.
 */
$getArray = function (string $key, array $default = []) use ($req): array {
    $val = $req->input($key);

    if (is_array($val)) {
        return $val;
    }

    if (is_string($val)) {
        $decoded = json_decode($val, true);
        if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
            return $decoded;
        }
    }

    return $default;
};

/**
 * Read action (defaults to empty if not provided).
 */
$action = (string) $req->input('action', '');

if ($action === '') {
    echo json_encode(['error' => 'Missing action']);
    exit();
}

/**
 * Action handlers (return associative arrays to be JSON-encoded).
 */
$handlers = [
    'searchMembers' => function () use ($req): array {
        $query = (string) $req->input('query', '');

        return [
            'success' => '1',
            'members' => Member::searchMembers($query),
        ];
    },

    'searchItems' => function () use ($req): array {
        $query = (string) $req->input('query', '');
        $basketBuilder = new BasketBuilder;

        return [
            'success' => '1',
            'items' => $basketBuilder->findItems($query),
        ];
    },

    'init' => function (): array {
        return [
            'success' => '1',
            'deliveryMethods' => DeliveryMethod::query()->where('disable', '0')->get(),
            'siteUrl' => SITE_URL,
        ];
    },

    'createBasket' => function () use ($req, $getArray): array {
        $basketBuilder = new BasketBuilder;

        $basketBuilder->memberId = (int) $req->input('memberId', 0);
        $basketBuilder->parentId = $req->filled('parentId') && $req->input('parentId') !== ''
            ? $req->input('parentId')
            : null;
        $basketBuilder->items = $getArray('items');
        $basketBuilder->shippingAddress = $getArray('shippingAddress');
        $basketBuilder->deliveryMethodId = (int) $req->input('deliveryMethodId', 0);

        $order = $basketBuilder->createBasket();

        return [
            'success' => '1',
            'order' => $order,
        ];
    },

    'sendToMember' => function () use ($req): array {
        $basketBuilder = new BasketBuilder;
        $basketBuilder->sendToMember($req->input('orderId'));

        return ['success' => '1'];
    },
];

/**
 * Dispatch and emit JSON.
 */
try {
    if (! isset($handlers[$action])) {
        echo json_encode(['error' => 'Unknown action']);
        exit();
    }

    $result = $handlers[$action]();
    echo json_encode($result);
} catch (Throwable $e) {
    // Optional: log server-side
    error_log('[BasketBuilder ajax] '.$e->getMessage());

    echo json_encode(['errors' => $e->getMessage()]);
}

exit();
