<?php
include('auth.php');
include('redirect.php');

// Code written with little too no sleep at 05:16
if ((isset($_GET['action'])) && (isset($_GET['file']))) {
    $path = '../uploads/audited/';

    if (file_exists($path.$_GET['file'])===false)
    {
        header("Location: /admin/audited.php");
        die('File does not exist');
    }
    switch ($_GET['action']) {
        case 'delete':
            // Is this safe?
            unlink($path.$_GET['file']);
            break;
        
        default:
            die('Action not found');
            break;
    }
    header("Location: /admin/audited.php");
    die();
}
?>

<?php include('../../_header.php'); ?>

<h3>Bilder som er i bruk</h3>
<?php
$directory = "../uploads/audited";
$files = array_diff(scandir($directory), array('..', '.'));
?>
<p>Totalt: <?=count($files)?></p>
<table>
    <tr>
        <th>Fil</th>
        <th>Handling</th>
    </tr>
    <?php foreach($files as $file): ?>
        <tr>
            <td><a href="/uploads/audited/<?=$file;?>"><img class="img" src="/uploads/audited/<?=$file;?>" alt=""></a></td>
            <td style="text-align: center;">
                <a style="color: red;" href="audited.php?action=delete&file=<?=$file;?>">Slett</a>
            </td>
        </tr>
    <?php endforeach;?>
</table>

<style>
table {
    border-collapse: collapse;
    width: 100%;
}

table, td, th {
    border: 1px solid #888;
}

tr:nth-child(even) {background-color: #f2f2f2;}

.img {
    margin: auto;
    object-fit: contain;
    width:100%;
    max-height: 600px;
    min-height: 150px;
    height: auto;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
</style>


<?php include('../../_footer.php'); ?>