<?php
require_once '../src/AccessToken.php';
require_once '../src/Database.php';

class EmailActivityProcessor
{
    private $conn;
    private $clientEndPoint;
    private $accessToken;
    private $responsibleId;
    private $bitrix24UserId;
    private $processedActivities = [];

    public function __construct($userId)
    {
        if (!$userId) {
            exit("User ID not provided.");
        }

        $this->conn = Database::getInstance();
        $this->bitrix24UserId = intval($userId);
        $tokenData = AccessToken::getAccessTokenByUserId($this->bitrix24UserId);
        $this->accessToken = $tokenData['access_token'];
        $this->clientEndPoint = $tokenData['client_endpoint'];
        $this->responsibleId = $tokenData['repo_id'];
    }

    private function callApi($method, $params = [])
    {
        $url = $this->clientEndPoint . $method . "?auth=" . $this->accessToken;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        $response = curl_exec($ch);
        curl_close($ch);
        return json_decode($response, true);
    }

    public function processTicketsFromEmail()
    {
        $sql = "SELECT bitrix_user_id, ticket_user_id, subject, task_id 
                FROM external_ticket 
                WHERE sorce = 'email' AND bitrix_user_id = {$this->bitrix24UserId}";

        $result = mysqli_query($this->conn, $sql);

        if (mysqli_num_rows($result) > 0) {
            while ($ticket = mysqli_fetch_assoc($result)) {
                $this->handleTicket($ticket);
            }
        }

        $this->postCommentsAndCompleteActivities();
    }

    private function handleTicket($ticket)
    {
        $subject_clean = trim($ticket['subject']);

        $params = [
            "filter" => [
                "TYPE_ID" => 4,
                "DIRECTION" => 1,
                "SUBJECT" => "Re: " . $subject_clean,
                "COMPLETED" => "N"
            ],
            "select" => [
                "ID", "SUBJECT", "DESCRIPTION", "CREATED", "OWNER_ID", "OWNER_TYPE_ID",
                "RESPONSIBLE_ID", "AUTHOR_ID", "COMMUNICATIONS", "FILES"
            ],
            "order" => ["ID" => "desc"],
        ];

        $response = $this->callApi('/crm.activity.list.json', $params);

        if (!empty($response['result'])) {
            foreach ($response['result'] as $activity) {
                $this->processActivity($ticket, $activity);
            }
        }
    }

    private function processActivity($ticket, $activity)
    {
        $cleanBody = $this->cleanHtml($activity['DESCRIPTION'] ?? '');
        $emailId = $activity['ID'];

        $this->processedActivities[] = [
            'task_id' => $ticket['task_id'],
            'email' => $ticket['ticket_user_id'],
            'description' => $cleanBody,
            'email_id' => $emailId
        ];

        // Attach files to task
        if (!empty($activity['FILES'])) {
            foreach ($activity['FILES'] as $fileId) {
                $query_params = [
                    "taskId" => $ticket['task_id'],
                    "fileId" => $fileId['id']
                ];
                $this->callApi('/tasks.task.files.attach', $query_params);
            }
        }
    }

    private function postCommentsAndCompleteActivities()
    {
        if (empty($this->processedActivities)) {
            echo "No incoming email activity found.";
            return;
        }

        foreach ($this->processedActivities as $item) {
            $params = [
                "taskId" => $item['task_id'],
                "fields" => [
                    "POST_MESSAGE" => $item['description']
                ]
            ];
            $response = $this->callApi('/task.commentitem.add', $params);
            print_r($response);

            
            if (!empty($response['result'])) {
                $update_params = [
                    "ID" => $item['email_id'],
                    "FIELDS" => [
                        "COMPLETED" => "Y"
                    ]
                ];
                $this->callApi('/crm.activity.update.json', $update_params);
            }
            
        }
    }

    private function cleanHtml($html)
    {
        $html = preg_replace('#<style.*?>.*?</style>#si', '', $html);
        $html = preg_replace('#<script.*?>.*?</script>#si', '', $html);
        $html = preg_replace('#<!--.*?-->#s', '', $html);
        $html = preg_replace('#<blockquote.*?>.*?</blockquote>#si', '', $html);
        $html = strip_tags($html);
        $html = html_entity_decode($html, ENT_QUOTES, 'UTF-8');
        $html = preg_replace('/On\s.+?wrote:/is', '', $html);
        $html = preg_replace('/(From:|To:|Subject:|Date:).*/i', '', $html);
        $html = preg_replace('/-----Original Message-----/i', '', $html);
        $html = preg_replace('/-{2,}\s*Forwarded message\s*-{2,}/i', '', $html);
        $html = preg_replace('/\n>+.*/', '', $html);
        $html = preg_replace('/\s+/', ' ', $html);
        return trim($html);
    }
}

// Run the processor
$userId = $_GET['user_id'] ?? null;
$processor = new EmailActivityProcessor($userId);
$processor->processTicketsFromEmail();
