<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    && isset($_POST['request_id'], $_POST['action'])
    && !empty($GLOBALS['mysql_con'])
) {
    $contactId = (int) $_POST['request_id'];
    $actionRaw = $_POST['action'];
    $action = ($actionRaw === 'approve') ? 'approve' : 'reject';

    if ($contactId > 0) {

        if ($action === 'approve') {
            // Approve image: move image_new → image
            $sql = "
                UPDATE main_contact
                SET 
                    image       = image_new,
                    image_new   = NULL,
                    image_state = 'approved'
                WHERE id = {$contactId}
                LIMIT 1
            ";
        } else {
            // Reject image: remove image_new, set discard
            $sql = "
                UPDATE main_contact
                SET 
                    image_new   = NULL,
                    image_state = 'discard'
                WHERE id = {$contactId}
                LIMIT 1
            ";
        }

        @mysqli_query($GLOBALS['mysql_con'], $sql);
    }


    echo "<script>document.location.href = document.location.href</script>";
}

$requests = [];

if (!empty($GLOBALS['mysql_con'])) {
    $sql = "
        SELECT 
            id,
            name,
            image_new,
            image_state
        FROM main_contact
        WHERE image_state = 'approve_required'
          AND image_new IS NOT NULL
          AND image_new != ''
    ";

    $res = @mysqli_query($GLOBALS['mysql_con'], $sql);

    if ($res) {
        while ($row = mysqli_fetch_assoc($res)) {
            $requests[] = [
                'id'         => (int) $row['id'],
                'user_id'    => (int) $row['id'],
                'photo_path' => $row['image_new'],
                'username'   => $row['name'],
                'created_at' => "" // No date currently stored; placeholder left empty
            ];
        }
        mysqli_free_result($res);
    }
}

?>
<link rel="stylesheet" type="text/css"
      href="/module/photo_approve/photo_approve.css?time=<?php echo filemtime($_SERVER['DOCUMENT_ROOT'] . '/module/photo_approve/photo_approve.css'); ?>">

<div class="pa-container">
    <h2>Foto-Anfragen zur Genehmigung</h2>

    <?php if (empty($requests)): ?>
        <p>Keine ausstehenden Foto-Anfragen.</p>
    <?php endif; ?>

    <div class="pa-grid">
        <?php foreach ($requests as $req): ?>
            <div class="pa-card">

                <?php
                // -----------------------------------------------------------
                // Determine real image path
                // -----------------------------------------------------------
                $img = '/plugins/Semantic-UI-master/images/image.png'; // fallback

                if (!empty($req['photo_path'])) {
                    $raw = $req['photo_path'];

                    // If absolute URL or path → use directly
                    if (preg_match('#^(https?:)?//#i', $raw) || strpos($raw, '/') === 0) {
                        $img = $raw;
                    } else {
                        // Saved filename → attach to userdata path
                        $img = '/userdata/intranet/contact/' . ltrim($raw, '/');
                    }

                    // Verify file exists in filesystem
                    $fullPath = $_SERVER['DOCUMENT_ROOT'] . $img;
                    if (!file_exists($fullPath)) {
                        $img = '/plugins/Semantic-UI-master/images/image.png';
                    }
                }

                $username = $req['username'] ?: ('Benutzer #' . $req['id']);
                ?>

                <img src="<?= htmlspecialchars($img) ?>"
                     alt="Foto von <?= htmlspecialchars($username) ?>">

                <div class="meta">
                    <div><strong><?= htmlspecialchars($username) ?></strong></div>
                </div>

                <div class="pa-actions">
                    <form method="post" onsubmit="return confirm('Foto wirklich freigeben?');">
                        <input type="hidden" name="request_id" value="<?= (int) $req['id'] ?>">
                        <input type="hidden" name="action" value="approve">
                        <button type="submit" class="ui positive button">Erlauben</button>
                    </form>

                    <form method="post" onsubmit="return confirm('Foto wirklich ablehnen?');">
                        <input type="hidden" name="request_id" value="<?= (int) $req['id'] ?>">
                        <input type="hidden" name="action" value="reject">
                        <button type="submit" class="ui negative button">Ablehnen</button>
                    </form>
                </div>

            </div>
        <?php endforeach; ?>
    </div>
</div>

<?php
// EOF
?>
