<?php
include "classes/DatabaseConnection.php";

echo "<p class='debug'>";
if ($_GET["from_language"]) {
    $from_language = $_GET["from_language"];
    echo "</br>From Language supplied:=" . $from_language . "\n";
} else {
    $from_language = 2; // default Greek
    echo "</br>From Language defaulted:=" . $from_language . "\n";
}

if ($_GET["to_language"]) {
    $to_language = $_GET["to_language"];
    echo "</br>To Language supplied:=" . $to_language . "\n";
} else {
    $to_language = 1; // default English
    echo "</br>To Language defaulted:=" . $to_language . "\n";
}
echo "</p>\n";

// read word with linked meanings from database
$db_conn = DatabaseConnection::getConnection();

$query = "SELECT fw.word as from_word, tw.word as to_word, fw.id as from_word_id FROM words fw left join word_meanings wm on fw.id = wm.from_word_id left join words tw on wm.to_word_id = tw.id where fw.language = " . $from_language. " and nvl(tw.language," . $to_language . ") = " . $to_language . " order by fw.word";

$result = $db_conn->connection->query($query);

// initialise variables
$first_time = TRUE;
$prv_word_id = "";
$word_details = "";
$meaning_cell = "";

echo "<table class='main'>\n";

foreach ($result as $row) {
    // when "from word" changes...
    if ($row['from_word_id'] != $prv_word_id) {
        // output previous word details if not first time
        if (!$first_time) {
            // output previous word's details
            $meaning_cell .= "</table>";
            echo "<tr>" . $word_details . $meaning_cell . "</tr>";
        }
        // set up details of "from word"
        $word_details = "<td class='main'><button onclick='enter_meaning(" . $row['from_word_id'] . "," . $to_language . ")' class='meaning'>?</button></td><td class='main'>" . $row['from_word'] . "</td>";
        // because more than one meaning can be assigned use table within cell
        $meaning_cell = "<td class='main'><table class='meaning'><tr><td class='meaning'>" . ($row['to_word'] ?$row['to_word']:"...") . "</td></tr>";
        $prv_word_id = $row['from_word_id'];
    } else {
        $meaning_cell .= "<tr><td class='meaning'>" . $row['to_word'] . "</td></tr>";
    }
    $first_time = FALSE;
}

// output last word's details
if (!$first_time) {
    $meaning_cell .= "</table>";
    echo "<tr>" . $word_details . $meaning_cell . "</tr>";
}

// close table
echo "</table>\n";
?>