<?php
session_start();

error_reporting(E_ALL);error_reporting(E_ALL);

require_once './config.php';
require_once './_pdo.php';
require_once './src/D2Functions.php';


// Define the database file path
define('DB_FILE', $_SESSION['modname'] . ".db");

// Connect to the SQLite database
$db = new SQLite3(DB_FILE);

// Retrieve the POST data
$treasureClass = $db->escapeString($_POST['treasureClass']);
$noDrop = $db->escapeString($_POST['noDrop']);
$prob = [];
for ($i = 1; $i <= 10; $i++) {
    $prob[$i] = isset($_POST["prob$i"]) ? $db->escapeString($_POST["prob$i"]) : 0;
}

// Prepare the SQL UPDATE statement
$query = "
    UPDATE treasureclassex
    SET NoDrop = $noDrop,
        Prob1 = {$prob[1]}, Prob2 = {$prob[2]}, Prob3 = {$prob[3]}, Prob4 = {$prob[4]},
        Prob5 = {$prob[5]}, Prob6 = {$prob[6]}, Prob7 = {$prob[7]}, Prob8 = {$prob[8]},
        Prob9 = {$prob[9]}, Prob10 = {$prob[10]}
    WHERE `Treasure Class` = '$treasureClass'
";

// Execute the update statement
$result = $db->exec($query);

if ($result) {
    echo "Successfully updated!";
} else {
    echo "Failed to update! Error: " . $db->lastErrorMsg();
}

$tsvFilePath = $_SESSION['path'] . "/TreasureClassEx.txt";

// Open the file for writing
$fileHandle = fopen($tsvFilePath, 'w');

// Query to select all rows from the treasureclassex table
$query = "SELECT * FROM treasureclassex";

// Execute the query
$result = $db->query($query);

// Write the column headers to the file
$columnNames = [];
for ($i = 0; $i < $result->numColumns(); $i++) {
    $columnNames[] = $result->columnName($i);
}
fwrite($fileHandle, implode("\t", $columnNames) . "\n");

// Write the rows to the file
while ($row = $result->fetchArray(SQLITE3_NUM)) {
    fwrite($fileHandle, implode("\t", $row) . "\n");
}

// Close the file
fclose($fileHandle);

echo "Successfully updated and written to TSV file!";