<?php

namespace Digtective\Integrations;

use Digtective\Connectors\DigtectiveCoreConnector;
use Digtective\Repository\FormSubmissionRepository\FormSubmissionRepository;
use Digtective\Repository\FormSubmissionRepository\FormSubmissionRepositoryInterface;
use Digtective\Repository\TokenRepository;

class WooCommerceIntegration{
    private FormSubmissionRepositoryInterface $formSubmissionRepository;
    private DigtectiveCoreConnector           $coreConnector;

    public function __construct(){
        $token = (new TokenRepository())->getToken();

        $this->formSubmissionRepository = new FormSubmissionRepository();
        $this->coreConnector = new DigtectiveCoreConnector($token);
    }

    public static function isActive(): bool{
        if(!function_exists('isWoocommerceActivated')){
            function isWoocommerceActivated(){
                if(class_exists('woocommerce')){
                    return true;
                }else{
                    return false;
                }
            }
        }

        return true;
    }

    public function applyFilters(){
        add_action('woocommerce_order_status_changed', [$this, 'orderStatusChanged'], 10, 4);
        add_action('woocommerce_new_order', [$this, 'newOrder'], 10, 1);
    }

    public function newOrder($order_id){
        $orderExists = $this->formSubmissionRepository->doesOrderExist($order_id);
        $order = wc_get_order($order_id);

        if($orderExists === null){
            return;
        }

        if(!$orderExists){
            $price = $order->get_total();
            $this->createFormSubmission($order_id, $price);
        }
    }

    public function orderStatusChanged($order_id, $old_status, $new_status, $order){
        $orderExists = $this->formSubmissionRepository->doesOrderExist($order_id);

        if($orderExists === null){
            return;
        }

        $price = $order->get_total();

        $createNewFormSubmission = ["pending", 'processing', 'on-hold'];
        if(!$orderExists && in_array($new_status, $createNewFormSubmission)){
            $this->createFormSubmission($order_id, $price);
        }

        if($orderExists && $new_status === "completed"){
            $this->updateFormSubmission($order_id, 1, $price);
        }

        $updateLostStatus = ["cancelled", "refunded", "failed"];
        if($orderExists && in_array($new_status, $updateLostStatus)){
            $this->updateFormSubmission($order_id, 2, $price);
        }
    }

    public function createFormSubmission(int $order_id, float $income){
        session_start();

        $click_type = "gclid";
        $click_id = "";

        if(isset($_SESSION['gclid'])){
            $click_id = sanitize_text_field($_SESSION["gclid"]);
        }

        if(isset($_SESSION['gbraid'])){
            $click_id = sanitize_text_field($_SESSION["gbraid"]);
            $click_type = "gbraid";
        }

        if(isset($_SESSION['wbraid'])){
            $click_id = sanitize_text_field($_SESSION["wbraid"]);
            $click_type = "wbraid";
        }

        $body_params = [
            "originalReferrer" => sanitize_text_field($_SESSION['originalReferrer']),
            "sessionId"        => sanitize_text_field($_SESSION['sessionId']),
            "referrer"         => sanitize_text_field($_SESSION['referrer']),
            "browser"          => sanitize_text_field($_SESSION['browser']),
            "adCode"           => sanitize_text_field($_SESSION['adCode']),
            "path"             => sanitize_text_field($_SESSION['path']),
            "keyword"          => sanitize_text_field($_SESSION['kwd']),
            "income"           => $income,
            "status"           => 0,
            "googleClickId"    => [
                "type"    => $click_type,
                "clickId" => $click_id,
            ],
        ];

        $formSubmissionId = $this->coreConnector->createFormSubmission($body_params);

        $this->formSubmissionRepository->create($formSubmissionId, $order_id);
    }

    public function updateFormSubmission(int $order_id, int $status, int $income){
        $formSubmissionId = $this->formSubmissionRepository->getByWoocommerceOrderId($order_id);

        if($formSubmissionId === ""){
            error_log("Failed to gather form_submission_id from order_id, order_id:$order_id");

            return;
        }

        $this->coreConnector->updateFormSubmission(
            $formSubmissionId,
            [
                "income" => $income,
                "status" => $status,
            ]
        );
    }
}