<?php 
/**
 * All-in-One WP Migration 
 * Copyright (C) 2014-2018 ServMask Inc.
 *
 * Modified Copyright (C) 2025 Lead Connector
 * 
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
class Lcm_Events{
    private string $eventName;
    private array $eventAttributes;
    private string $eventEndPoint = 'wordpress/lc-plugin/migrator/events/update'; 

    /**
     * Constructor for the Lcm_Events
     * @param string $eventName The name of the event
     * @param array $eventAttributes K,V pairs of the event attributes
     * @return static 
     */
    public function __construct(string $eventName, array $eventAttributes){
        $this->eventName = $eventName;
        $this->eventAttributes = $eventAttributes;
        $this->eventEndPoint = $this->eventEndPoint . "/" . $this->getAccountId();
        return $this;
    }

    /**
     * Function to add an attribute to the event
     * @param string $attributeName
     * @param mixed $attributeValue
     * @return Lcm_Events
     */
    public function addEventAttribute(string $attributeName, $attributeValue): Lcm_Events {
        $this->eventAttributes[$attributeName] = $attributeValue;
        return $this;
    }

    /**
     * Function to add multiple attributes to the event
     * @param array $eventAttributes
     * @return Lcm_Events
     */
    public function addEventAttributes(array $eventAttributes): Lcm_Events {
        $this->eventAttributes = array_merge($this->eventAttributes, $eventAttributes);
        return $this;
    }

    private function getAccountId(?string $locationId = null): string {
        $leadMigratorOptions = Lcm_Option_Manager::getInstance();
        if($locationId){
            return $locationId;
        }
        $storedLocationId = $leadMigratorOptions->get('location_id');
        // Return stored location_id or fallback to 'unknown' for CLI/cases where not set
        return $storedLocationId ?? 'unknown';
    }
    
    private function getAdditionalEventAttributes(): array{
        return array(
            'remote_ip' => $_SERVER['REMOTE_ADDR'],
            'host' => $_SERVER['HTTP_HOST'],
            'admin_email' => get_option('admin_email'),
            'php_version' => phpversion(),
        );
    }

    /**
     * Creates the event body that is sent to Backend
     * @return array
     */
    private function createEventBody(): Array{
        $body = Array(
            'eventName' => $this->eventName,
            'eventAttributes' => array_merge($this->eventAttributes, $this->getAdditionalEventAttributes()),
            'accountId' => $this->getAccountId(),
        );
        return $body;
    }

    /**
     * Sends the event to the backend
     * @return bool True if the event was sent successfully, false otherwise
     */
    public function send(): bool {
        try{
            // Sanity checks for event name and attributes
            if (empty($this->eventName)) {
                throw new \Exception('Event name cannot be empty');
            }

            if (!is_array($this->eventAttributes)) {
                throw new \Exception('Event attributes must be an array');
            }
            $request = new Lcm_HTTP_Requests();
            $response = $request->request($this->eventEndPoint, 'POST', $this->createEventBody());
            if (isset($response->success) && $response->success === true) {
                return true;
            }
            else{
                throw new Lcm_Event_Exception("Event API Call Failed");
            }
        }
        catch(\Exception $e){
            throw new Lcm_Event_Exception("Event Failed: " . $e->getMessage());
        }
    }
}