<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/Database.php';
require_once __DIR__ . '/AccessToken.php';

class ExternalTicket {
    private static $conn;
    private static $accessToken;
    private static $clientEndpoint;

    public static function init($bitrixUserId) {
        if (!self::$conn) {
            self::$conn = Database::getInstance();
        }

        $tokenData = AccessToken::getAccessTokenByUserId($bitrixUserId);
        self::$accessToken = $tokenData['access_token'];
        self::$clientEndpoint = $tokenData['client_endpoint'];
    }

    private static function getNextResponsibleUser($internalProjectId) {
        $stmt = self::$conn->prepare("SELECT responsible_bitrix_id FROM project_responsible_users WHERE project_id = ? ORDER BY last_assigned_at ASC LIMIT 1");
        $stmt->bind_param("i", $internalProjectId);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();
        if (!$user) return null;

        $update = self::$conn->prepare("UPDATE project_responsible_users SET last_assigned_at = NOW() WHERE responsible_bitrix_id = ?");
        $update->bind_param("i", $user['responsible_bitrix_id']);
        $update->execute();

        return $user['responsible_bitrix_id'];
    }

    private static function callBitrixAPI($method, $params) {
        $url = self::$clientEndpoint . $method . '?auth=' . self::$accessToken;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        $response = curl_exec($ch);
        curl_close($ch);
        return json_decode($response, true);
    }

    private static function createBitrixTask($taskData) {
        for ($i = 0; $i < 3; $i++) {
            $response = self::callBitrixAPI("tasks.task.add.json", $taskData);
            if (isset($response['result']['task']['id'])) {
                return $response['result']['task']['id'];
            }
            sleep(1);
        }
        return null;
    }

    private static function uploadFileToBitrix($file, $folderId) {
        $uploadUrlData = self::callBitrixAPI("disk.folder.uploadfile.json", [
            'id' => $folderId,
            'data[NAME]' => $file['name'],
            'generateUniqueName' => true
        ]);
        if (!isset($uploadUrlData['result']['uploadUrl'])) return null;

        $uploadUrl = $uploadUrlData['result']['uploadUrl'];
        $fieldName = $uploadUrlData['result']['field'];
        $postData = [
            $fieldName => curl_file_create($file['tmp_name'], $file['type'], $file['name'])
        ];

        $ch = curl_init($uploadUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        $uploadResult = curl_exec($ch);
        curl_close($ch);
        $resultData = json_decode($uploadResult, true);
        return $resultData['result']['ID'] ?? null;
    }
public static function html_to_bbcode_description($text) {
    $text = str_replace('<strong>', '[B]', $text);
    $text = str_replace('</strong>', '[/B]', $text);
    $text = str_replace('<br>', "\n", $text);
    $text = strip_tags($text, '<br>'); // Retain line breaks temporarily
    return $text;
}
    public static function handleTicket($postData, $fileData) {
       if (empty($postData['bitrix24_user_id'])) {
    return ['success' => false, 'message' => 'Bitrix24 user ID missing'];
}

self::init($postData['bitrix24_user_id']);
$bitrixUserId = $postData['bitrix24_user_id'];
$bitrixDeadline = null;

if ($bitrixUserId == 10) {
    $createdOn = date("jS F, Y \\a\\t H:i", strtotime($postData['created_on'] ?? 'now'));
    $dueOn = date("jS F, Y \\a\\t H:i", strtotime($postData['due_on'] ?? 'now'));

    $dueDate = new DateTime($postData['due_on'] ?? 'now', new DateTimeZone("UTC"));
    $dueDate->setTimezone(new DateTimeZone("UTC"));
    $bitrixDeadline = $dueDate->format("Y-m-d\TH:i:sP");

    $taskDescriptionHtml = <<<HTML
<strong>Clerk Name:</strong> {$postData['clerk_name']}<br>
<strong>Clerk Email:</strong> {$postData['user_email']}<br>
<strong>Report Type:</strong> {$postData['report_type']}<br>
<strong>Property:</strong> {$postData['subject']}<br>
<strong>Created On:</strong> {$createdOn}<br>
<strong>Due On:</strong> {$dueOn}
HTML;

    $taskDescription = self::html_to_bbcode_description($taskDescriptionHtml);
}

$userEmail    = (string) ($postData['user_email'] ?? '');
$userName     = null;
$priority     = htmlspecialchars(trim((string) ($postData['priority'] ?? '1')));
$description  = htmlspecialchars(trim((string) ($postData['description'] ?? $taskDescription)));
$subject      = htmlspecialchars(trim((string) ($postData['subject'] ?? '')));
$ticketUserId = htmlspecialchars(trim((string) ($postData['ticket_user_id'] ?? '0')));
$status       = 'New';
$source       = "form";
$ticketId     = "No";
$phone        = null;

$projectType       = (string) ($postData['project_type'] ?? '');
$bitrixProjectId   = intval($postData['project_id'] ?? 0);
$folderId          = (string) ($postData['folder_id'] ?? '');
$internalProjectId = intval($postData['id'] ?? 0);

        $responsibleId = self::getNextResponsibleUser($internalProjectId);
        if (!$responsibleId) {
            return ['success' => false, 'message' => 'No responsible user available'];
        }

        $bitrixTask = [
            "fields" => [
                "TITLE" => "Ticket: $subject",
                "DESCRIPTION" => $description,
                "RESPONSIBLE_ID" => $responsibleId,
                "DESCRIPTION_IN_BBCODE" => "Y", 
                "GROUP_ID" => $bitrixProjectId,
                "PRIORITY" => $priority,
                "STATUS" => 1,
                "TAGS" => [$projectType],
                "DEADLINE" => $bitrixDeadline
                
            ]
        ];

        $task_id = self::createBitrixTask($bitrixTask);
        if (!$task_id) {
            return ['success' => false, 'message' => 'Bitrix24 task creation failed'];
        }

        if (!empty($fileData['attachment']) && is_uploaded_file($fileData['attachment']['tmp_name'])) {
            $fileId = self::uploadFileToBitrix($fileData['attachment'], $folderId);
            if ($fileId) {
                self::callBitrixAPI("tasks.task.files.attach", [
                    "taskId" => $task_id,
                    "fileId" => $fileId
                ]);
            }
        }

       $stmt = self::$conn->prepare("
    INSERT INTO external_ticket (
        ticket_id, task_id, bitrix_user_id, ticket_user_id, project_id,responsible_id,
        name, phone, email, subject, issue_type,
        priority, sorce, description, status,
        created_at, updated_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
");

$stmt->bind_param(
    "siiiiisssssssss", 
    $ticketId,
    $task_id,
    $bitrixUserId,
    $ticketUserId,
    $bitrixProjectId,
    $responsibleId,
    $userName,
    $phone,
    $userEmail,
    $subject,
    $projectType,
    $priority,
    $source,
    $description,
    $status
);
        if ($stmt->execute()) {
            return ['success' => true, 'message' => 'Ticket created successfully', 'task_id' => $task_id];
        } else {
            return ['success' => false, 'message' => 'Database error while saving ticket'];
        }
    }
}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_POST['issue_type'])) {
        $parts = explode('|', $_POST['issue_type']);
        $_POST['project_type'] = $parts[0] ?? '';
        $_POST['project_id']   = $parts[1] ?? ''; // Bitrix24 Project ID
        $_POST['folder_id']    = $parts[2] ?? '';
        $_POST['id']           = $parts[3] ?? ''; // Internal Project ID
 
        // Send to TicketHandler
         
// Handle POST request
       $result = ExternalTicket::handleTicket($_POST, $_FILES);
      echo "<pre>";
          print_r($result);
          exit;
      session_start();
if ($result['success'] == 1) {
    $_SESSION['success_message'] = $result['message']."! Your Ticket ID is #" . $result['task_id'];
    header("Location: https://integrations.notamedia.co.in/helpdesk-core-php/ticket-user/index.php");
    exit;
} else {
    $_SESSION['error_message'] = "Error: " . ($result['message'] ?? "Something went wrong. Please try again.");
    header("Location: https://integrations.notamedia.co.in/helpdesk-core-php/ticket-user/index.php");
    exit;
}



    }
}
?>