<?php
include_once 'serverMessanger.php';

function getData() {
    $db = new SQLite3('dropper.db');

    if($db === false){
        $message = "Server: [Error] --> Database connection failed!";
        serverMessage("error", $message);
        die("ERROR: Could not connect to db.");
    }

    $res = $db->query('Select * FROM Dropper');
    $GeneratedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><LIST>";
    while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
        $GeneratedXML .= "<BLOB>" .
               "<TYPE>" . $row['type'] . "</TYPE>" .
               "<DATA>" . $row['data'] . "</DATA>" .
           "</BLOB>";
    }
    $GeneratedXML .= "</LIST>";
    echo $GeneratedXML;
}

function manageData($ACTION, $TYPE, $VAL) {
    $db = new SQLite3('dropper.db');
    $ACTION_TYPE = "";

    if($db === false){
        $message = "Server: [Error] --> Database connection failed!";
        serverMessage("error", $message);
        die("ERROR: Could not connect to db.");
    }

    // If action isn't true then we add else we delete or exit.
    if ($ACTION == "false") {
        $stmt = $db->prepare('INSERT INTO Dropper VALUES(:type , :data)');
        $ACTION_TYPE = "added to";
    } elseif ($ACTION == "true") {
        $stmt = $db->prepare('DELETE FROM Dropper WHERE type = :type AND data = :data');
        $ACTION_TYPE = "deleted from";
    } else {
        $message = "Server: [Error] --> Action for adding or deleting isn't set properly!";
        serverMessage("error", $message);
        return;
    }

    $stmt->bindValue(":type", $TYPE, SQLITE3_TEXT);
    $stmt->bindValue(":data", $VAL, SQLITE3_TEXT);
    $stmt->execute();

    $message = "Server: [Success] --> Data: " .
                $VAL . "    " . $ACTION_TYPE . " the database!";
    serverMessage("success", $message);
}


// Determin action
chdir("../db/");
if (isset($_POST['getData'])) {
    getData();
} elseif (isset($_POST['deleteData'],
                $_POST['type'],
                $_POST['data'])) {
    manageData($_POST['deleteData'], $_POST['type'], $_POST['data']);
} else {
    $message = "Server: [Error] --> Illegal Access Method!";
    serverMessage("error", $message);
}

?>
