<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\OrderActionRequest;
use App\Http\Requests\Admin\OrdersListRequest;
use App\Models\Order;
use App\SAP\SAPService;
use App\Shopify\OrdersService;
use App\Shopify\ShopifyService;
use Exception;

/**
 * Controller class that supports integration dashboard for order related features
 */
class OrdersController extends Controller
{
    /**
     * Available order actions
     */
    const ORDER_ACTIONS = ['sync-to-sap', 'sync-from-sap', 'sync-to-shopify', 'sync-from-shopify'];

    /**
     * Logic for orders
     *
     * @var OrdersService
     */
    private $ordersService;

    /**
     * Constructor.
     *
     * @param OrdersService $ordersService
     * @param SapService $sapService
     */
    public function __construct(OrdersService $ordersService, SAPService $sapService, ShopifyService $shopifyService)
    {
        $this->ordersService = $ordersService;
        $this->sapService = $sapService;
        $this->shopifyService = $shopifyService;
    }

    public function listOrders(OrdersListRequest $request)
    {
        $data = $request->validated();

        $ordersResults = $this->ordersService->listOrders($data);

        $ordersResults['success'] = true;

        return $ordersResults;
    }

    public function doAction(String $action, OrderActionRequest $request)
    {
        $data = $request->validated();
        $shopifyId = $data['shopifyId'];

        if (!in_array($action, self::ORDER_ACTIONS)) {
            return [
                'success' => false,
                'error' => 'Action not supported'
            ];
        }

        $order = Order::where('shopify_id', $shopifyId)
            ->first();

        if (!$order && $action !== 'sync-from-shopify') {
            return [
                'success' => false,
                'error' => 'Order not found'
            ];
        }

        $output = [
            'success' => true
        ];
        try {
            switch ($action) {
                case 'sync-from-shopify':
                    $order = $this->shopifyService->syncShopifyOrder($shopifyId);
                    /*
                    if (empty($order->sap_order_nr) && $order->financial_status === 'paid') {
                        CreateSapOrderJob::dispatch($order);
                    }
                    */
                    $output['syncStatus'] = 'PENDING';
                    $output['integrationId'] = $order->id;
                    $output['toSync'] = $order->to_sync;
                    break;
                case 'sync-to-shopify':
                    $output['success'] = $this->shopifyService->orderStatusUpdate($order);
                    if ($output['success']) {
                        $output['syncStatus'] = 'SYNCED';
                    }
                    break;
                case 'sync-to-sap':
                    $this->sapService->createSapOrder($order);
                case 'sync-from-sap':
                    $order = $this->sapService->checkOrderStatus($order);
                    $output['sapId'] = $order->sap_order_nr;
                    $output['syncStatus'] = $order->to_sync_status ? 'PENDING' : 'SYNCED';
                    break;
            }
        } catch (Exception $e) {
            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }

        return $output;
    }

    public function getStatus()
    {
        $notIntOrders = $this->ordersService->getOrdersNotIntegrated();
        $pendingToSAP = $this->ordersService->countOrdersNotSentToSAP();
        $pedndingStatus = $this->ordersService->countPendingStatusUpdate();

        return [
            'success' => true,
            'ordersStatus' => [
                'notIntegrated' => sizeof($notIntOrders),
                'notSap' => $pendingToSAP,
                'pendingStatus' => $pedndingStatus
            ]
        ];
    }
}
