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

class TicketHandler {
    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 handleTicket($postData, $fileData) {
        if (empty($postData['bitrix24_user_id'])) {
            return ['success' => false, 'message' => 'Bitrix24 user ID missing'];
        }

        self::init($postData['bitrix24_user_id']);

        $ticketId     = strtoupper(substr(md5(time()), 0, 15));
        $userId       = intval($postData['created_by']);
        $userEmail    = htmlspecialchars(trim($postData['userEmail']));
        $userName     = htmlspecialchars(trim($postData['userName']));
        $priority     = htmlspecialchars(trim($postData['priority']));
        $description  = htmlspecialchars(trim($postData['comment']));
        $subject  = htmlspecialchars(trim($postData['ticket_name']));
        $status       = 'New';

        // Use pre-extracted values from POST
        $projectType       = $postData['project_type'] ?? '';
        $bitrixProjectId   = intval($postData['project_id'] ?? 0); // used in Bitrix
        $folderId          = $postData['folder_id'] ?? '';
        $internalProjectId = intval($postData['id'] ?? 0); // used for fetching responsible user only

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

        $bitrixTask = [
            "fields" => [
                "TITLE" => "Ticket: $subject",
                "DESCRIPTION" => $description,
                "RESPONSIBLE_ID" => $responsibleId,
                "GROUP_ID" => $bitrixProjectId,
                "PRIORITY" => $priority,
                "TAGS" => [$projectType],
                "CREATED_BY" =>$userId 
            ]
        ];

        $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 internal_ticket (
    task_id, user_id, bitrix24_user_id, project_id, responsible_id,
    ticket_subject, ticket_description, priority, project_type, status,
    user_email, user_name, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");

$stmt->bind_param(
    "iiiissssssss",  
    $task_id,                          
    $userId,                           
    $postData['bitrix24_user_id'],    
    $bitrixProjectId,                 
    $responsibleId,                   
    $subject,                         
    $description,                     
    $priority,                        
    $projectType,                     
    $status,                          
    $userEmail,                       
    $userName                         
);

        if ($stmt->execute()) {
            return ['success' => true, 'message' => 'Ticket created successfully', 'task_id' => $task_id];
        } else {
            return ['success' => false, 'message' => 'Database error while saving ticket'];
        }
    }
}

// Handle POST request
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
        $result = TicketHandler::handleTicket($_POST, $_FILES);
      
if ($result['success'] == 1) {
    $_SESSION['success_message'] = $result['message'];
    header("Location: ../intrnal_ticket.php");
    exit;
} else {
    $_SESSION['error_message'] = $result['message'];
    header("Location: ./intrnal-ticket-create.php");
    exit;
}



    }
}
?>