<?php

use Mtc\Modules\Members\Models\Member;
use Mtc\Plugins\BasketBuilder\Classes\BasketBuilder;

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

// Process AJAX requests

if (empty($_POST['action'])) {
    exit;
}

if ($_POST['action'] === 'searchMembers') {
    echo json_encode([
        'success' => '1',
        'members' => Member::searchMembers($_POST['query']),
    ]);
    exit;
}

if ($_POST['action'] === 'searchItems') {
    $basketBuilder = new BasketBuilder();
    echo json_encode([
        'success' => '1',
        'items' => $basketBuilder->findItems($_POST['query']),
    ]);
    exit;
}

if ($_POST['action'] === 'init') {
    echo json_encode([
        'success' => '1',
        'deliveryMethods' => DeliveryMethod::query()
            ->where('disable', '0')
            ->get(),
        'siteUrl' => SITE_URL,
    ]);
    exit;
}

if ($_POST['action'] === 'createBasket') {
    $basketBuilder = new BasketBuilder();
    $basketBuilder->memberId = $_POST['memberId'];
    $basketBuilder->parentId = $_POST['parentId'] ?: null;
    $basketBuilder->items = $_POST['items'];
    $basketBuilder->shippingAddress = $_POST['shippingAddress'];
    $basketBuilder->deliveryMethodId = $_POST['deliveryMethodId'];

    try {
        $order = $basketBuilder->createBasket();
        echo json_encode([
            'success' => '1',
            'order' => $order,
        ]);
    } catch (Exception $e) {
        echo json_encode([
            'errors' => $e->getMessage(),
        ]);
    }
    exit;
}

if ($_POST['action'] === 'sendToMember') {
    $basketBuilder = new BasketBuilder();
    try {
        $basketBuilder->sendToMember($_POST['orderId']);
    } catch (Exception $e) {
        echo json_encode([
            'error' => $e->getMessage(),
        ]);
        exit;
    }
    echo json_encode([
        'success' => '1',
    ]);
    exit;
}