<?php

session_start();
ob_start();

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

require_once './src/D2Functions.php';
require_once './src/D2Crud.php';

error_reporting(E_ERROR | E_PARSE);
set_time_limit(-1);
ini_set('max_input_time', '-1');
ini_set('max_execution_time', '0');

define('DB_FILE', $_SESSION['modname'] . ".db");
PDO_Connect("sqlite:" . DB_FILE);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check if the "Add" button was clicked
    if (isset($_POST['add'])) {
        $tableName = $_POST['tableName'];
        
        // Retrieve the Key and String values from the form
        $key = $_POST['key'];
        $string = $_POST['string'];
                
        // Insert the new row into the table
        $inserted = PDO_Execute("INSERT INTO $tableName (Key, String) VALUES (?, ?)", array($key, $string));
        
        if ($inserted) {
            // Redirect or display success message
            header('Location: /TblEditorGUI.php');
        } else {
            // Handle the insertion failure
            echo PDO_ErrorInfo();            
        }
    }
}


// Handle the DELETE submission
    // Check if the "Delete" button was clicked
    if ($_GET['cmd'] == "delete") {
              
        $tableName = $_GET['t'];
        $key = $_GET['k'];
        
        // Delete the row from the table based on the Key
        $deleted = PDO_Execute("DELETE FROM $tableName WHERE Key = ?", array($key));
        
        if ($deleted) {
            // Redirect or display success message
            echo "Deleted $key from $tableName";
        } else {
            // Handle the deletion failure
            echo PDO_ErrorInfo();            

        }
    }