<?php
require_once '../src/AccessToken.php';
require_once '../src/Database.php';
$conn = Database::getInstance();  // Keep the connection open

if (!isset($_GET['user_id'])) {
    echo "User ID not provided.";
    exit();
}

$bitrix24UserId = $_GET['user_id'];
$folderId = $projectId = $supportEmail = null;
// Get access token and client endpoint
$tokenData = AccessToken::getAccessTokenByUserId($bitrix24UserId);
$accessToken = $tokenData['access_token'];
$clientEndPoint = $tokenData['client_endpoint'];
$responsibleId = $tokenData['repo_id'];

// Fetch project_id, folder_id, and support_email
$sql = "SELECT Project_id, folder_id, support_email FROM bitrix24_users WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $bitrix24UserId);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$folderId = $row['folder_id'];
$projectId = $row['Project_id'];
$supportEmail = $row['support_email'];
$stmt->close();

function get_or_insert_user_id($email, $name,$bitrix24UserId,$folderId,$projectId) {
    global $conn;
    $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $userId = $row['id'];
        $stmt->close();
        return $userId;
    }

    $stmt = $conn->prepare("INSERT INTO users (email, name,bitrix24_user_id,folder_id,project_id) VALUES (?, ?,?,?,?)");
    $stmt->bind_param("ssiii", $email, $name,$bitrix24UserId,$folderId,$projectId);
    $stmt->execute();
    $userId = $stmt->insert_id;
    $stmt->close();
    
    return $userId;
}

function generateTicketId($length = 10) {
    $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $ticketId = '';
    for ($i = 0; $i < $length; $i++) {
        $ticketId .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $ticketId;
}

$timezone = new DateTimeZone('Asia/Kolkata');
$start = new DateTime('today midnight', $timezone);
$end = new DateTime('tomorrow midnight', $timezone);
$end->modify('-1 second');

$todayStart = $start->format(DateTime::ATOM);
$todayEnd   = $end->format(DateTime::ATOM);

function call_api($clientEndPoint,$accessToken,$method, $params = []) {
    $base_url = $clientEndPoint.$method."?auth=".$accessToken;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $base_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);
}

function clean_html($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);
}

function normalize_subject($subject) {
    return strtolower(trim($subject));
}

// Fetch today's emails
$params = [
    'filter' => [
        'TYPE_ID' => 4,
        '>=CREATED' => $todayStart,
        '<=CREATED' => $todayEnd,
        "DIRECTION" => 1,
        "COMPLETED" => "N",
    ],
    'select' => [
        'ID', 'SUBJECT', 'DESCRIPTION', 'CREATED', 'OWNER_ID', 'OWNER_TYPE_ID',
        'RESPONSIBLE_ID', 'AUTHOR_ID', 'COMMUNICATIONS', 'SETTINGS', 'FILES', 'PRIORITY'
    ],
    'order' => ['CREATED' => 'DESC']
];
$method='/crm.activity.list.json';
$response = call_api($clientEndPoint,$accessToken,$method, $params);
$emails = $response["result"];
 
if (empty($emails)) {
    echo "No unread emails found.\n";
    exit;
}

foreach ($emails as $email) {
    $receiverEmail = $email['SETTINGS']['EMAIL_META']['__email'] ?? '';

    if (strtolower($receiverEmail) !== $supportEmail) {
        continue;
    }

    $email['DESCRIPTION'] = clean_html($email['DESCRIPTION']);
    $normalized_subject = normalize_subject($email['SUBJECT']);
    if (strpos($normalized_subject, "re:") !== false) {
        continue;
    }

    $fielsId = [];
    if (!empty($email["FILES"])) {
        foreach ($email["FILES"] as $fileId) {
            $fielsId[] = $fileId['id'];
        }
    }

    $communications = $email['COMMUNICATIONS'] ?? [];
    $senderEmail = '';
    foreach ($communications as $comm) {
        if ($comm['TYPE'] === 'EMAIL') {
            $senderEmail = $comm['VALUE'];
            break;
        }
    }
    
    $emailId = $email["ID"];
    $emailDate = $email["CREATED"];
    $emailSubject = $email["SUBJECT"];
    $emailBody = $email["DESCRIPTION"];
    $priority = $email["PRIORITY"];
    $emailResponsible = $email["RESPONSIBLE_ID"];
    $entityType = $email["OWNER_TYPE_ID"];
    $entityId = $email["OWNER_ID"];
    $reciverEmail = $email['SETTINGS']['EMAIL_META']['__email'];

    // Always generate a unique ticket ID
    do {
        $ticketId = generateTicketId();
        $stmt = $conn->prepare("SELECT COUNT(*) FROM tickets WHERE ticket_id = ?");
        $stmt->bind_param("s", $ticketId);
        $stmt->execute();
        $stmt->bind_result($ticketExists);
        $stmt->fetch();
        $stmt->close();
    } while ($ticketExists > 0);

    // Create task in Bitrix
    $taskData = [
        "fields" => [
            "TITLE" => "Email:" . $ticketId . " " . $emailSubject,
            "DESCRIPTION" => $emailBody,
            "RESPONSIBLE_ID" =>$responsibleId,
            "GROUP_ID" => $projectId,
            "PRIORITY" => 1,
            "STATUS" => 1,
            "TAGS" => ["HelpDesk", "email", "Ticket"]
        ]
    ];

    $method='/tasks.task.add.json';
    $taskResult = call_api($clientEndPoint,$accessToken,$method, $taskData);
    $taskId = $taskResult['result']['task']['id'] ?? null;
    if (empty($taskId)) {
        echo "Failed to create task for email: $emailSubject\n";
        continue;
    }
    

    $ticketUserName = "Email user";
    $sorce="email";
    $userId = get_or_insert_user_id($senderEmail, $ticketUserName,$bitrix24UserId,$folderId,$projectId);

    // Insert into tickets table
    $sql = "INSERT INTO tickets (task_id, ticket_id, issue_type, priority, description, status, project_id, bitrix_user_id, ticket_user_id,sorce) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?,?)";
    $stmt = $conn->prepare($sql);
    $status = 1;
    $stmt->bind_param(
        "issisiiiis",
        $taskId,
        $ticketId,
        $emailSubject,
        $priority,
        $emailBody,
        $status,
        $projectId,
        $bitrix24UserId,
        $userId,
        $sorce
    );
    
    if ($stmt->execute()) {
        echo "Ticket Created for Email: $emailSubject\n";
    } else {
        echo "Failed to insert ticket for Email: $emailSubject\n";
    }
    $stmt->close();

    // Attach files to task
    if (!empty($fielsId)) {
        foreach ($fielsId as $fileVal) {
            $query_params = [
                "taskId" => $taskId,
                "fileId" => $fileVal
            ];
          
            $method='/tasks.task.files.attach';
    $response = call_api($clientEndPoint,$accessToken,$method, $query_params);
        }
    }

    // Mark the email as completed (optional)
    if ($emailId) {
        $update_params = [
            "ID" => $emailId,
            "FIELDS" => [
                "COMPLETED" => "Y"
            ]
        ];
        $method='/crm.activity.update.json';
        $response = call_api($clientEndPoint,$accessToken,$method, $update_params);

    }
}
?>
