<?php

namespace BitApps\PiPro\src\Integrations\EasyCommerce;

// Prevent direct script access
if (!\defined('ABSPATH')) {
    exit;
}

use BitApps\Pi\Services\FlowService;
use BitApps\PiPro\src\Integrations\IntegrationHelper;
use EasyCommerce\Models\Attribute;
use EasyCommerce\Models\Coupon;
use EasyCommerce\Models\Order;
use EasyCommerce\Models\Shipping_Plan;

final class EasyCommerceTrigger
{
    public static function userCreated($userId, $userData)
    {
        return self::execute('userCreated', $userData);
    }

    public static function userUpdated($userId, $userData)
    {
        return self::execute('userUpdated', $userData);
    }

    public static function attributeCreated($attributeId)
    {
        if (empty($attributeId) || !class_exists('\EasyCommerce\Models\Attribute')) {
            return;
        }

        $attribute = new Attribute();

        $data = $attribute->get($attributeId);

        return self::execute('attributeCreated', $data);
    }

    public static function addToCart($products)
    {
        if (empty($products) || !class_exists('\EasyCommerce\Models\Product')) {
            return;
        }

        $data = ['cart' => $products];

        foreach ($products as $product) {
            $data['products'][] = EasyCommerceHelper::getProductData($product['id']);
        }

        return self::execute('addToCart', $data);
    }

    public static function cartUpdated($productId, $priceId, $quantity)
    {
        if (empty($productId) || !class_exists('\EasyCommerce\Models\Product')) {
            return;
        }

        $data = [
            'cart' => [
                'product_id' => $productId,
                'price_id'   => $priceId,
                'quantity'   => $quantity,
            ]
        ];

        $data['product'] = EasyCommerceHelper::getProductData($productId);

        return self::execute('cartUpdated', $data);
    }

    public static function productRemoveFromCart($productId)
    {
        if (empty($productId) || !class_exists('\EasyCommerce\Models\Product')) {
            return;
        }

        $data = EasyCommerceHelper::getProductData($productId);

        return self::execute('productRemoveFromCart', $data);
    }

    public static function cartCleared($request)
    {
        $data = EasyCommerceHelper::getRequestData($request);

        return self::execute('cartCleared', $data);
    }

    public static function setCheckoutShippingMethod($methodId)
    {
        if (empty($methodId) || !class_exists('\EasyCommerce\Models\Shipping_Plan')) {
            return;
        }

        $data = Shipping_Plan::get_method_by_id($methodId);

        return self::execute('setCheckoutShippingMethod', $data);
    }

    public static function couponApplied($coupon)
    {
        $data = EasyCommerceHelper::getCouponData($coupon);

        return self::execute('couponApplied', $data);
    }

    public static function couponRemovedFromCheckoutPage($code, $request)
    {
        if (!class_exists('\EasyCommerce\Models\Coupon')) {
            return;
        }

        $coupon = new Coupon($code);

        $data = [
            'coupon'  => EasyCommerceHelper::getCouponData($coupon),
            'request' => EasyCommerceHelper::getRequestData($request),
        ];

        return self::execute('couponRemovedFromCheckoutPage', $data);
    }

    public static function couponStatusUpdated($id, $status)
    {
        if (!class_exists('\EasyCommerce\Models\Coupon')) {
            return;
        }

        $coupon = new Coupon($id);

        $data = EasyCommerceHelper::getCouponData($coupon);

        $data['status'] = $status;

        return self::execute('couponStatusUpdated', $data);
    }

    public static function couponDeleted($id)
    {
        if (!class_exists('\EasyCommerce\Models\Coupon')) {
            return;
        }

        $coupon = new Coupon($id);

        $data = EasyCommerceHelper::getCouponData($coupon);

        return self::execute('couponDeleted', $data);
    }

    public static function orderCreated($orderId, $params, $customerId)
    {
        if (!class_exists('\EasyCommerce\Models\Order')) {
            return;
        }

        $order = new Order($orderId);
        $orderData = EasyCommerceHelper::getOrderData($order);

        $data = [
            'order'       => $orderData,
            'params'      => $params,
            'customer_id' => $customerId,
        ];

        if (
            !empty($params['shipping_method'])
            && class_exists('\EasyCommerce\Models\Shipping_Plan')
        ) {
            $data['shipping_method'] = Shipping_Plan::get_method_by_id($params['shipping_method']);
        }

        return self::execute('orderCreated', $data);
    }

    public static function orderStatusUpdated($orderId, $newStatus, $oldStatus)
    {
        return self::handleOrderStatusRelatedTrigger(
            $orderId,
            $newStatus,
            $oldStatus,
            'orderStatusUpdated'
        );
    }

    public static function orderRefunded($order, $reason)
    {
        $data = [
            'order'  => EasyCommerceHelper::getOrderData($order),
            'reason' => $reason
        ];

        return self::execute('orderRefunded', $data);
    }

    public static function emailToCustomer($email, $subject, $body, $placeholders)
    {
        $data = [
            'email'        => $email,
            'subject'      => $subject,
            'body'         => $body,
            'placeholders' => $placeholders,
        ];

        return self::execute('emailToCustomer', $data);
    }

    public static function setOrderStatusToProcessing($orderId, $newStatus, $oldStatus)
    {
        if ($newStatus !== 'processing') {
            return;
        }

        return self::handleOrderStatusRelatedTrigger(
            $orderId,
            $newStatus,
            $oldStatus,
            'setOrderStatusToProcessing'
        );
    }

    public static function setOrderStatusToCompleted($orderId, $newStatus, $oldStatus)
    {
        if ($newStatus !== 'completed') {
            return;
        }

        return self::handleOrderStatusRelatedTrigger(
            $orderId,
            $newStatus,
            $oldStatus,
            'setOrderStatusToCompleted'
        );
    }

    public static function setOrderStatusToPending($orderId, $newStatus, $oldStatus)
    {
        if ($newStatus !== 'pending') {
            return;
        }

        return self::handleOrderStatusRelatedTrigger(
            $orderId,
            $newStatus,
            $oldStatus,
            'setOrderStatusToPending'
        );
    }

    public static function setOrderStatusToRefunded($orderId, $newStatus, $oldStatus)
    {
        if ($newStatus !== 'refunded') {
            return;
        }

        return self::handleOrderStatusRelatedTrigger(
            $orderId,
            $newStatus,
            $oldStatus,
            'setOrderStatusToRefunded'
        );
    }

    public static function setOrderStatusToOnHold($orderId, $newStatus, $oldStatus)
    {
        if ($newStatus !== 'on_hold') {
            return;
        }

        return self::handleOrderStatusRelatedTrigger(
            $orderId,
            $newStatus,
            $oldStatus,
            'setOrderStatusToOnHold'
        );
    }

    public static function setOrderStatusToCancelled($orderId, $newStatus, $oldStatus)
    {
        if ($newStatus !== 'cancelled') {
            return;
        }

        return self::handleOrderStatusRelatedTrigger(
            $orderId,
            $newStatus,
            $oldStatus,
            'setOrderStatusToCancelled'
        );
    }

    public static function productCreated($productData)
    {
        if (!class_exists('\EasyCommerce\Models\Product')) {
            return;
        }

        $data = EasyCommerceHelper::getProductData($productData['id']);

        return self::execute('productCreated', $data);
    }

    public static function productUpdated($productData)
    {
        if (!class_exists('\EasyCommerce\Models\Product')) {
            return;
        }

        $data = EasyCommerceHelper::getProductData($productData['id']);

        return self::execute('productUpdated', $data);
    }

    public static function productDeleted($productId)
    {
        if (!class_exists('\EasyCommerce\Models\Product')) {
            return;
        }

        $data = EasyCommerceHelper::getProductData($productId);

        return self::execute('productDeleted', $data);
    }

    public static function productStatusUpdated($status, $productId)
    {
        $data = EasyCommerceHelper::getProductData($productId);

        return self::execute('productStatusUpdated', $data);
    }

    public static function setProductStatusToLive($status, $productId)
    {
        if ($status !== 'publish') {
            return;
        }

        $data = EasyCommerceHelper::getProductData($productId);

        return self::execute('setProductStatusToLive', $data);
    }

    public static function setProductStatusToDraft($status, $productId)
    {
        if ($status !== 'draft') {
            return;
        }

        $data = EasyCommerceHelper::getProductData($productId);

        return self::execute('setProductStatusToDraft', $data);
    }

    public static function setProductStatusToTrash($status, $productId)
    {
        if ($status !== 'trash') {
            return;
        }

        $data = EasyCommerceHelper::getProductData($productId);

        return self::execute('setProductStatusToTrash', $data);
    }

    public static function abandonedCartDeleted($hash, $isDeleted, $request)
    {
        $data = EasyCommerceHelper::prepareAbandonedCartData($hash, $request, $isDeleted);

        return self::execute('abandonedCartDeleted', $data);
    }

    public static function abandonedCartReminderSent($hash, $request)
    {
        $data = EasyCommerceHelper::prepareAbandonedCartData($hash, $request);

        return self::execute('abandonedCartReminderSent', $data);
    }

    private static function handleOrderStatusRelatedTrigger($orderId, $newStatus, $oldStatus, $machineSlug)
    {
        if (empty($orderId) || !class_exists('\EasyCommerce\Models\Order')) {
            return;
        }

        $data = [
            'order'      => EasyCommerceHelper::getOrderData(new Order($orderId)),
            'new_status' => $newStatus,
            'old_status' => $oldStatus,
        ];

        return self::execute($machineSlug, $data);
    }

    private static function execute($machineSlug, $data)
    {
        $flows = FlowService::exists('easyCommerce', $machineSlug);

        if (!$flows) {
            return;
        }

        IntegrationHelper::handleFlowForForm($flows, $data);
    }

    // TODO:: need to implement
    private static function isPluginInstalled()
    {
        return \defined('EASYCOMMERCE_VERSION');
    }
}
