<?php

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/layout.php';

$currentUserRole = $_SESSION['admin_role'] ?? '';

$message = '';

// ----------------------
// DELETE IMAGE
// ----------------------

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['delete_image'])
) {

    if (
        !in_array(
            $currentUserRole,
            ['Admin', 'Editor'],
            true
        )
    ) {

        die('You do not have permission.');
    }

    $fileName = basename($_POST['delete_image']);

    $filePath =
        __DIR__ . '/../uploads/media/' . $fileName;

    if (
        file_exists($filePath) &&
        is_file($filePath)
    ) {

        unlink($filePath);

        $message = 'Image deleted successfully.';

    } else {

        $message = 'Image not found.';
    }
}

// ----------------------
// UPLOAD IMAGE
// ----------------------

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    !isset($_POST['delete_image'])
) {

    if (
        isset($_FILES['file']) &&
        $_FILES['file']['error'] === UPLOAD_ERR_OK
    ) {

        $uploadDir = __DIR__ . '/../uploads/media/';

        if (!is_dir($uploadDir)) {

            mkdir($uploadDir, 0755, true);
        }

        $fileTmp = $_FILES['file']['tmp_name'];

        $fileName = basename($_FILES['file']['name']);

        $ext = strtolower(
            pathinfo($fileName, PATHINFO_EXTENSION)
        );

        $allowedTypes = [
            'image/jpeg',
            'image/png',
            'image/gif',
            'image/webp'
        ];

        $mimeType = mime_content_type($fileTmp);

        if (
            in_array($mimeType, $allowedTypes, true)
        ) {

            $newFileName =
                uniqid('media_', true) . '.' . $ext;

            $destination =
                $uploadDir . $newFileName;

            if (
                move_uploaded_file(
                    $fileTmp,
                    $destination
                )
            ) {

                $message =
                    'Image uploaded successfully!';

            } else {

                $message =
                    'Failed to upload image.';
            }

        } else {

            $message =
                'Only JPG, PNG, GIF, and WEBP allowed.';
        }

    } else {

        $message = 'Please select an image.';
    }
}

// ----------------------
// LOAD MEDIA FILES
// ----------------------

$mediaFiles = [];

$mediaDir = __DIR__ . '/../uploads/media/';

if (is_dir($mediaDir)) {

    $files = scandir($mediaDir);

    $files = array_diff($files, ['.', '..']);

    foreach ($files as $file) {

        $fullPath = $mediaDir . $file;

        if (is_file($fullPath)) {

            $mediaFiles[] = [
                'name' => $file,
                'url' => '/uploads/media/' . $file,
                'modified' => filemtime($fullPath)
            ];
        }
    }

    usort($mediaFiles, function ($a, $b) {

        return $b['modified'] <=> $a['modified'];
    });
}

?>

<style>

.media-card img {
    width: 100%;
    height: 160px;
    object-fit: cover;
}

.url-input {
    font-size: 11px;
}

.media-card .card-body {
    padding: 0.75rem;
}

</style>

<div class="container">

    <div class="d-flex justify-content-between align-items-center mb-4">

        <h2 class="mb-0">
            Media Library
        </h2>

    </div>

    <!-- UPLOAD CARD -->

    <div class="card shadow-sm p-4 mb-4">

        <form
            method="post"
            enctype="multipart/form-data"
        >

            <div class="row g-3 align-items-end">

                <div class="col-md-10">

                    <label class="form-label">
                        Upload Image
                    </label>

                    <input
                        type="file"
                        name="file"
                        class="form-control"
                        accept="image/*"
                        required
                    >

                </div>

                <div class="col-md-2">

                    <button
                        type="submit"
                        class="btn btn-primary w-100"
                    >
                        Upload
                    </button>

                </div>

            </div>

        </form>

    </div>

    <!-- MESSAGE -->

    <?php if ($message): ?>

        <div class="alert alert-info">

            <?= htmlspecialchars(
                $message,
                ENT_QUOTES,
                'UTF-8'
            ) ?>

        </div>

    <?php endif; ?>

    <!-- MEDIA GRID -->

    <div class="row g-3">

        <?php if (empty($mediaFiles)): ?>

            <div class="col-12">

                <div class="alert alert-secondary">

                    No media uploaded yet.

                </div>

            </div>

        <?php endif; ?>

        <?php foreach ($mediaFiles as $media): ?>

            <div class="col-xl-2 col-lg-3 col-md-4 col-6">

                <div class="card media-card h-100 shadow-sm">

                    <img
                        src="<?= htmlspecialchars($media['url'], ENT_QUOTES, 'UTF-8') ?>"
                        alt=""
                    >

                    <div class="card-body">

                        <input
                            type="text"
                            class="form-control mb-2 url-input"
                            value="<?= htmlspecialchars($media['url'], ENT_QUOTES, 'UTF-8') ?>"
                            readonly
                        >

                        <button
                            type="button"
                            class="btn btn-outline-primary btn-sm w-100 mb-2"
                            onclick="copyMediaUrl('<?= htmlspecialchars($media['url'], ENT_QUOTES, 'UTF-8') ?>')"
                        >
                            Copy URL
                        </button>

                        <?php if (
                            in_array(
                                $currentUserRole,
                                ['Admin', 'Editor'],
                                true
                            )
                        ): ?>

                            <form method="post">

                                <input
                                    type="hidden"
                                    name="delete_image"
                                    value="<?= htmlspecialchars($media['name'], ENT_QUOTES, 'UTF-8') ?>"
                                >

                                <button
                                    type="submit"
                                    class="btn btn-danger btn-sm w-100"
                                    onclick="return confirm('Delete this image?')"
                                >
                                    Delete
                                </button>

                            </form>

                        <?php endif; ?>

                    </div>

                </div>

            </div>

        <?php endforeach; ?>

    </div>

</div>

<script>

function copyMediaUrl(url) {

    navigator.clipboard.writeText(url);

    alert('Copied!');
}

</script>