<?php
require_once 'Database.php';

class InternalTicket {
    private static $conn;
    private static $accessToken;
    private static $clientEndpoint;
    public function __construct() {
        if (!self::$conn) {
            self::$conn = Database::getInstance();
        }
    }
 
    public static function init($bitrixUserId) {
        $tokenData = AccessToken::getAccessTokenByUserId($bitrixUserId);
        self::$accessToken = $tokenData['access_token'];
        self::$clientEndpoint = $tokenData['client_endpoint'];
    }
    public static function getCurrentUser($bitrixUserId) {
        self::init($bitrixUserId); // Set token and endpoint

        $url = self::$clientEndpoint . "user.current.json?auth=" . self::$accessToken;

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);

        $data = json_decode($response, true);

        if (isset($data['result'])) {
            return $data['result']; // User info
        } else {
            return [
                'error' => $data['error_description'] ?? 'Unknown error',
                'raw_response' => $data
            ];
        }
    }
    public static function getInternalProjects($bitrix24_user_id) {
       
        $instance = new self();
        $conn = self::$conn;

        $projects = [];
        $query = "SELECT * FROM projects WHERE flow_type = 'Internal' AND bitrix24_user_id={$bitrix24_user_id}";
        $stmt = $conn->prepare($query);

        if ($stmt) {
            $stmt->execute();
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $projects[] = $row;
            }
            $stmt->close();
        } else {
            return "Prepare failed: " . $conn->error;
        }

        return $projects;
    }
       public static function getInternalTicket($bitrix24_user_id, $userId) {
    $instance = new self(); // Initialize DB connection
    $conn = self::$conn;

    if (!$conn) {
        die("DB Connection not initialized.");
    }

    $userId = (int)$userId;
    $bitrix24_user_id = (int)$bitrix24_user_id;

    $query = "SELECT * FROM internal_ticket WHERE user_id = $userId AND bitrix24_user_id = $bitrix24_user_id";
    $result = $conn->query($query);

    if (!$result) {
        die("Query failed: " . $conn->error);
    }

    $internalTicket = [];
    while ($row = $result->fetch_assoc()) {
        $internalTicket[] = $row;
    }

    

    return $internalTicket;
}




    public static function getEternalProjects($bitrix24_user_id) {
       
        $instance = new self();
        $conn = self::$conn;

        $projects = [];
        $query = "SELECT * FROM projects WHERE flow_type = 'external' AND bitrix24_user_id={$bitrix24_user_id}";
        $stmt = $conn->prepare($query);

        if ($stmt) {
            $stmt->execute();
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $projects[] = $row;
            }
            $stmt->close();
        } else {
            return "Prepare failed: " . $conn->error;
        }

        return $projects;
    }
    public static function getDistinctFieldValues($field, $bitrixUserId, $userId) {
    $allowedFields = ['project_type', 'priority', 'status'];
    if (!in_array($field, $allowedFields)) {
        return [];
    }

    $conn = self::$conn; // mysqli connection

    // Correct SQL with placeholders
    $sql = "SELECT DISTINCT `$field` FROM internal_ticket WHERE bitrix24_user_id = ? AND user_id = ?";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        // Handle prepare error
        return [];
    }

    $stmt->bind_param("ii", $bitrixUserId, $userId); // assuming both are integers, change if needed
    $stmt->execute();

    $result = $stmt->get_result();

    $values = [];
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $values[] = $row[$field];
        }
    }

    $stmt->close();

    return $values;
}



}





