<?php

$path = "../img/haus/wohn/";
$ref = "index.php?section=fotos&t=" . $_GET['t'];

if (!isset($_GET['action'])) {
    echo "<p>Auf ein Bild klicken um es zu ersetzen<br />";

    for ($i = 0; $i < 2; $i++) {
        $pic = $path . $i . ".jpg";
        $link = $ref . "&action=add&pic=" . $i;
        if (file_exists($pic)) {
            if (0 == $i) {
                echo "<p>Wohnung Gaby:</p>\n";
            } else {
                echo "<p>Wohnung Amelie:</p>\n";
            }
            echo "<a href=\"$link\">";
            echo "<img style=\"border: 2px solid red;\" src=\"$pic\" width=\"100px\" height=\"100px\"/>";
            echo "</a>\n";
            echo "<br />&nbsp;";
        } else {
            echo "<a href=\"$link\">";
            echo "<img style=\"border: 2px solid red;\" src=\"../img/no.jpg\" />";
            echo "</a>\n";
        }
    }
} else {
    if ('add' == $_GET['action']) {
        $ref .= "&action=speichern&pic=" . $_GET['pic']
        ?>
        <form action="<?php echo $ref; ?>" method="post" enctype="multipart/form-data">
            <label>Foto auswählen</label>
            <input type="file" name="Foto"/>
            <br/>
            <input type="submit" name="Speichern" value="Speichern"/>
        </form>
        <?php
    } elseif ('speichern' == $_GET['action']) {
        $delfile = $path . $_GET['pic'] . ".jpg";
        unlink($delfile);
        $uploadfile = $path . $_FILES['Foto']['name'];
        move_uploaded_file($_FILES['Foto']['tmp_name'], $uploadfile);
        $src = imagecreatefromjpeg($uploadfile);
        list($width, $height) = getimagesize($uploadfile);
        if ($height > $width) {
            $newheight = 200;
            $newwidth = ($width / $height) * 200;
        } else {
            $newwidth = 200;
            $newheight = ($height / $width) * 200;
        }
        $tmp = imagecreatetruecolor($newwidth, $newheight);
        imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        $filename = $path . $_GET['pic'] . ".jpg";
        imagejpeg($tmp, $filename, 80);
        imagedestroy($src);
        imagedestroy($tmp);
        unlink($path . $_FILES['Foto']['name']);
        echo "<p>Bild hochgeladen</p>";
        echo "<a href=\"index.php?section=fotos&t=$_GET[t]\">Zurück zur Übersicht</a>\n";
    }
}
?>