<?php
    require_once __DIR__ . '/vendor1/autoload.php'; // carga el sentiment analizer
    require_once 'conexion.php';

    use Sentiment\Analyzer;

    $analyzer = new Analyzer();

    // Obtener los tweets de la base de datos
    $sql = "SELECT user_name, text FROM tweets";
    $result = $conn->query($sql);


    function mode($array) {
        $values = array_count_values($array);
        $mode = array_search(max($values), $values);
        return $mode;
    }

    // Arreglo para almacenar los resultados
    $sentiments = [];

    // Vaciar la tabla "sentimiento"
    $sql = "TRUNCATE TABLE sentimiento";
    $conn->query($sql);


    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $user_name = $row["user_name"];
            $text = $row["text"];

            // Calcular el sentimiento del tweet
            $sentiment = $analyzer->getSentiment($text);

            // Almacenar el resultado en el arreglo
            if (!isset($sentiments[$user_name])) {
                $sentiments[$user_name] = [
                    "polarity" => [],
                    "sentiment" => [],
                    "count" => 0,
                    "positive" => 0,
                    "negative" => 0,
                    "neutral" => 0
                ];
            }
            $sentiments[$user_name]["polarity"][] = $sentiment["compound"];
            if ($sentiment["compound"] > 0) {
                $sentiments[$user_name]["sentiment"][] = "positive";
                $sentiments[$user_name]["positive"]++;
            } elseif ($sentiment["compound"] < 0) {
                $sentiments[$user_name]["sentiment"][] = "negative";
                $sentiments[$user_name]["negative"]++;
            } else {
                $sentiments[$user_name]["sentiment"][] = "neutral";
                $sentiments[$user_name]["neutral"]++;
            }
            $sentiments[$user_name]["count"]++;

            $sql = "INSERT INTO sentimiento (user_name, tweets_positivos, tweets_negativos, tweets_neutrales, polaridad_promedio, sentimiento_promedio, tweets_totales) 
            VALUES ('$user_name', '{$sentiments[$user_name]['positive']}', '{$sentiments[$user_name]['negative']}', '{$sentiments[$user_name]['neutral']}', '" . array_sum($sentiments[$user_name]['polarity']) / count($sentiments[$user_name]['polarity']) . "', '" . mode($sentiments[$user_name]['sentiment']) . "', '{$sentiments[$user_name]['count']}') 
            ON DUPLICATE KEY UPDATE tweets_positivos='{$sentiments[$user_name]['positive']}', tweets_negativos='{$sentiments[$user_name]['negative']}', tweets_neutrales='{$sentiments[$user_name]['neutral']}', polaridad_promedio='" . array_sum($sentiments[$user_name]['polarity']) / count($sentiments[$user_name]['polarity']) . "', sentimiento_promedio='" . mode($sentiments[$user_name]['sentiment']) . "', tweets_totales='{$sentiments[$user_name]['count']}'";
            $conn->query($sql);
        }
    }
?>



<!DOCTYPE html>
<html>
    <head>
        <title>Tweet Sentiment Analysis</title>
        <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700&display=swap" rel="stylesheet">
        <link rel="stylesheet" type="text/css" href="css/sentimiento.css">

    </head>
    <body>
        <a href="menu.html" class="button">Regresar a menu</a>
        <h1>Análisis de Sentimientos de Tweets</h1>
        <div class="container">
            <table>
                <tr>
                    <th>Usuario</th>
                    <th>Tweets Positivos</th>
                    <th>Tweets Negativos</th>
                    <th>Tweets Neutrales</th>
                    <th>Polaridad Promedio</th>
                    <th>Sentimiento Promedio</th>
                    <th>Tweets Totales</th>
                </tr>
                <?php foreach ($sentiments as $user_name => $data): ?>
                    <?php
                        $polarity_avg = array_sum($data["polarity"]) / count($data["polarity"]);
                        $sentiment_counts = array_count_values($data["sentiment"]);
                        arsort($sentiment_counts);
                        $sentiment_avg = key($sentiment_counts);
                        $count = $data["count"];
                    ?>
                    <tr>
                        <td><?php echo htmlspecialchars($user_name); ?></td>
                        <td><?php echo htmlspecialchars($data["positive"]); ?></td>
                        <td><?php echo htmlspecialchars($data["negative"]); ?></td>
                        <td><?php echo htmlspecialchars($data["neutral"]); ?></td>
                        <td><?php echo round($polarity_avg, 4); ?></td>
                        <td><?php echo ucfirst(htmlspecialchars($sentiment_avg)); ?></td>
                        <td><?php echo htmlspecialchars($count); ?></td>
                        
                    </tr>
                <?php endforeach; ?>
            </table>
        </div>
</body>
</html>