
<?php
$data = file_get_contents("https://docs.google.com/spreadsheets/d/e/2PACX-1vSgR16GNT2WBWa926rAMG2EKRgXc9APNHcnqFw3Qs9WqL7OZhWW08Q--pu44AFJ2IW0JEtUqDy4YV4s/pub?gid=0&single=true&output=tsv");




// Print the contents of $data
//echo "<pre>";
//echo htmlspecialchars($data);
//echo "</pre>";

$rows = explode("\n", trim($data)); // Split data into rows

$topics = []; // Store topics as keys and count as values
$individuals = []; // Store individual and their topics
$topicNames = []; // To store the names of the topics



foreach ($rows as $index => $row) {
    $cols = explode("\t", trim($row)); // Assuming tab-separated values

    if ($index === 0) {
        // First row contains topic names
        $topicNames = array_slice($cols, 0);
        continue;
    }

    $individual = $cols[0];
    $individuals[$individual] = [];

    foreach ($cols as $colIndex => $col) {
        if ($colIndex === 0) continue; // Skip individual's name

        $topic = $topicNames[$colIndex - 1];
        if (trim($col) === '1') {
            if (!isset($topics[$topic])) {
                $topics[$topic] = 0;
            }
            $topics[$topic]++;
            $individuals[$individual][] = $topic;
        }
    }
}

// Now create nodes
$nodes = [];
foreach ($topics as $topic => $count) {
    $nodes[] = ['id' => $topic, 'group' => 1, 'name' => $topic, 'value' => $count];
    
}
// Create links
$links = [];
foreach ($individuals as $individual => $indivTopics) {
    if (count($indivTopics) > 1) {
        for ($i = 0; $i < count($indivTopics); $i++) {
            for ($j = $i + 1; $j < count($indivTopics); $j++) {
                $source = $indivTopics[$i];
                $target = $indivTopics[$j];

                // Check if both source and target exist in the overall topics list
                // and that neither is null
                if (isset($topics[$source]) && isset($topics[$target]) && $target !== null) {
                    $links[] = ['source' => $source, 'target' => $target, 'value' => 1];
                }
            }
        }
    }
}



?>



<!DOCTYPE html>
<html>
<head>
    <title>Red Mexicana de Biolog&iacute;a &amp; Matem&aacute;ticas</title>
    <script src="https://d3js.org/d3.v5.min.js"></script>
    <style>
      

        .link {
            stroke: #999;
            stroke-opacity: 0.6;
        }
        #tooltip {
            position: absolute;
            text-align: center;
            width: auto;
            height: auto;
            padding: 2px;
            font: 12px sans-serif;
            background: lightgray;
            border: 0px;
            border-radius: 8px;
            pointer-events: none;
            opacity: 0;
        }

        .labels text {
            font-size: 10px;
            font-family: Arial, sans-serif;
            fill: #DDDDDD; /* Or any color you prefer */
        }

    </style>
</head>
<body>

    <div id="tooltip"></div>
    <svg width="960" height="600"></svg>
    <script>
        var colorMapping = {
            "Microbiología": "#E1F6CC",
            "Probabilidad": "#CEDCE8",
            "Sistemas Dinámicos": "#CEDCE8",
            "Genética": "#E1F6CC",
            "Evolución": "#E1F6CC",
            "Topología": "#CEDCE8",
            "Ecología": "#CEDCE8",
        };
        
        var defaultColor = "#F6F6CD"; // This is the default color
        var nodes = <?php echo json_encode($nodes); ?>;
        var links = <?php echo json_encode($links); ?>;

        console.log("Nodes:", nodes);
        console.log("Links:", links);
        console.log("Color Mapping:", colorMapping);

        // Width and height for SVG
        var width = 960,
            height = 600;

        // SVG element
        var svg = d3.select("svg")
            .attr("width", width)
            .attr("height", height);

        
        var simulation = d3.forceSimulation(nodes)
            .force("link", d3.forceLink(links).id(d => d.id).distance(100)) // Increased distance
            .force("charge", d3.forceManyBody().strength(-50)) // More repulsive force
            .force("center", d3.forceCenter(width / 2, height / 2));


        // Create links
        var link = svg.append("g")
            .attr("class", "links")
            .selectAll("line")
            .data(links)
            .enter().append("line")
            .attr("class", "link");

        var labels = svg.append("g")
            .attr("class", "labels")
            .selectAll("text")
            .data(nodes)
            .enter().append("text")
            .attr("dx", 12)
            .attr("dy", ".35em")
            .text(d => d.name); // Or any other property you want to display


        var node = svg.append("g")
            .attr("class", "nodes")
            .selectAll("circle")
            .data(nodes)
            .enter().append("circle")
            .attr("class", "node")
            .attr("r", d => d.value * 2 + 5)
            .attr("fill", d => {
                if (colorMapping[d.name] === undefined) {
                    this_color=defaultColor
                }else{
                    this_color=colorMapping[d.name]
                }
                console.log("Node name:", d.name, "color:", this_color);
                return this_color;
            })
            .on("mouseover", mouseover)
            .on("mouseout", mouseout)
            .call(d3.drag()
                .on("start", dragstarted)
                .on("drag", dragged)
                .on("end", dragended));


        var tooltip = d3.select("#tooltip");

        function mouseover(event, d) {
            tooltip.style("opacity", 1);
            tooltip.html(d.name) // Use node name as tooltip text
                .style("left", (event.pageX + 10) + "px")
                .style("top", (event.pageY - 10) + "px");
        }

        function mouseout() {
            tooltip.style("opacity", 0);
        }
        

        simulation.on("tick", () => {
            link.attr("x1", d => d.source.x)
                .attr("y1", d => d.source.y)
                .attr("x2", d => d.target.x)
                .attr("y2", d => d.target.y);

            node.attr("cx", d => d.x)
                .attr("cy", d => d.y);

            labels.attr("x", d => d.x)
                  .attr("y", d => d.y);
        });


        // Drag functions
        function dragstarted(d) {
            if (!d3.event.active) simulation.alphaTarget(0.3).restart();
            d.fx = d.x;
            d.fy = d.y;
        }

        function dragged(d) {
            d.fx = d3.event.x;
            d.fy = d3.event.y;
        }

        function dragended(d) {
            if (!d3.event.active) simulation.alphaTarget(0);
            d.fx = null;
            d.fy = null;
        }
    </script>
</body>
</html>
