<?php

namespace Digtective\Controllers;

use Digtective\Base\Route;
use Digtective\Connectors\DigtectiveCoreConnector;
use Digtective\Repository\TokenRepository;

class FormSubmissionController{
    private const FORM_SUBMISSION_ROUTE = 'form-submission';
    private TokenRepository         $tokenRepository;
    private DigtectiveCoreConnector $coreConnector;

    public function __construct(){
        $this->tokenRepository = new TokenRepository();

        if($this->tokenRepository->tableExists()){
            $token = $this->tokenRepository->getToken();
        }else {
            $token = "";
        }
        $this->coreConnector = new DigtectiveCoreConnector($token);
    }

    public function createFormSubmission($request, $customFields = []){
        session_start();
        $status = 0;
        $email = $request["email"] ?? "";
        $income = $request["income"] ?? 0;

        $clickType = "gclid";
        $clickId = "";

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

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

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

        $bodyParams = [
            "sessionId"        => sanitize_text_field($_SESSION['sessionId'] ?? ""),
            "path"             => sanitize_text_field($_SESSION['path'] ?? ""),
            "browser"          => sanitize_text_field($_SESSION['browser'] ?? ""),
            "referrer"         => sanitize_text_field($_SESSION['referrer'] ?? ""),
            "adCode"           => sanitize_text_field($_SESSION['adCode'] ?? ""),
            "originalReferrer" => sanitize_text_field($_SESSION['originalReferrer'] ?? ""),
            "income"           => (float) $income,
            "status"           => (float) $status,
            "email"            => sanitize_email($email),
            "googleClickId"    => [
                "clickId" => $clickId,
                "type"    => $clickType,
            ],
            "facebookClickId" => [
                "clickId" => sanitize_text_field($_SESSION['fbclid'] ?? ""),
                "type" => "fbclid",
            ]
        ];

        if($customFields){
            $bodyParams['customFields'] = $customFields;
        }

        return $this->coreConnector->createFormSubmission($bodyParams);
    }

    public function createPaddleFormSubmission($request){
        session_start();
        $status = 0;
        $paddleCustomerId = $request["paddleCustomerId"];
        $income = $request["income"] ?? 0;

        $clickType = "gclid";
        $clickId = "";

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

        if(isset($_SESSION['gbraid'])){
            $clickId = sanitize_text_field($_SESSION["gbraid"] ?? "");
            $clickType = "gbraid";
        }

        if(isset($_SESSION['wbraid'])){
            $clickId = sanitize_text_field($_SESSION["wbraid"] ?? "");
            $clickType = "wbraid";
        }

        $bodyParams = [
            "sessionId"        => sanitize_text_field($_SESSION['sessionId'] ?? ""),
            "path"             => sanitize_text_field($_SESSION['path'] ?? ""),
            "browser"          => sanitize_text_field($_SESSION['browser'] ?? ""),
            "referrer"         => sanitize_text_field($_SESSION['referrer'] ?? ""),
            "adCode"           => sanitize_text_field($_SESSION['adCode'] ?? ""),
            "originalReferrer" => sanitize_text_field($_SESSION['originalReferrer'] ?? ""),
            "income"           => (float) $income,
            "status"           => (float) $status,
            "paddleCustomerId" => sanitize_text_field($paddleCustomerId),
            "googleClickId"    => [
                "clickId" => $clickId,
                "type"    => $clickType,
            ],
        ];

        return $this->coreConnector->createFormSubmission($bodyParams);
    }

    public function register(){
        add_action('rest_api_init', function(){
            register_rest_route(
                Route::BASE_PATH, self::FORM_SUBMISSION_ROUTE, [
                    'methods'  => 'POST',
                    'callback' => [$this, 'createFormSubmission'],
                    'args'     => [
                        "email"  => [
                            "required"          => true,
                            "validate_callback" => function($param, $request, $key){
                                return is_string($param) && trim($param, " ") != "" && is_email($param);
                            },
                        ],
                        "income" => [
                            "default"           => 0,
                            "validate_callback" => function($param, $request, $key){
                                return is_numeric($param);
                            },
                        ],
                    ],
                ]
            );
        });

        add_action('rest_api_init', function(){
            register_rest_route(
                Route::BASE_PATH, self::FORM_SUBMISSION_ROUTE."/paddle", [
                    'methods'  => 'POST',
                    'callback' => [$this, 'createPaddleFormSubmission'],
                    'args'     => [
                        "paddleCustomerId"  => [
                            "required"          => true
                        ],
                        "income" => [
                            "default"           => 0,
                            "validate_callback" => function($param, $request, $key){
                                return is_numeric($param);
                            },
                        ],
                    ],
                ]
            );
        });
    }
}
