<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_roles(['super_admin', 'clinic_admin']);
require DENTAL_ROOT . '/app/layout.php';

function website_media_redirect(string $extra = ''): never
{
    header('Location: website_media.php' . $extra);
    exit;
}

function website_media_upload(string $field = 'media_file'): array
{
    if (empty($_FILES[$field]) || ($_FILES[$field]['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
        throw new RuntimeException('Choose an image to upload.');
    }
    $file = $_FILES[$field];
    if (($file['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) {
        throw new RuntimeException('The media upload failed.');
    }
    if ((int)($file['size'] ?? 0) > 5 * 1024 * 1024) {
        throw new RuntimeException('Media images must be 5 MB or smaller.');
    }
    $tmp = (string)($file['tmp_name'] ?? '');
    if ($tmp === '' || !is_uploaded_file($tmp)) {
        throw new RuntimeException('The uploaded file could not be verified.');
    }
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = (string)$finfo->file($tmp);
    $allowed = ['image/png' => 'png', 'image/jpeg' => 'jpg', 'image/webp' => 'webp'];
    if (!isset($allowed[$mime])) {
        throw new RuntimeException('Use a JPG, PNG, or WebP image.');
    }
    $size = @getimagesize($tmp);
    if (!is_array($size) || (int)($size[0] ?? 0) < 1 || (int)($size[1] ?? 0) < 1) {
        throw new RuntimeException('The uploaded file is not a valid image.');
    }
    if ((int)$size[0] > 6000 || (int)$size[1] > 6000) {
        throw new RuntimeException('Media images must be 6000 px or smaller on each side.');
    }
    $dir = DENTAL_ROOT . '/public/uploads/website-media';
    if (!is_dir($dir)) {
        mkdir($dir, 0775, true);
    }
    $htaccess = $dir . '/.htaccess';
    if (!is_file($htaccess)) {
        file_put_contents($htaccess, "Options -Indexes\n\n<FilesMatch \"\\.(?:php[0-9]?|phtml|phar|cgi|pl|py|sh|shtml)$\">\n  <IfModule mod_authz_core.c>\n    Require all denied\n  </IfModule>\n  <IfModule !mod_authz_core.c>\n    Order allow,deny\n    Deny from all\n  </IfModule>\n</FilesMatch>\n");
    }
    $original = preg_replace('/[^A-Za-z0-9_.-]+/', '-', (string)($file['name'] ?? 'image')) ?: 'image';
    $base = strtolower(trim(pathinfo($original, PATHINFO_FILENAME), '-_.')) ?: 'website-image';
    $base = substr($base, 0, 48);
    $name = $base . '-' . date('YmdHis') . '-' . bin2hex(random_bytes(4)) . '.' . $allowed[$mime];
    if (!move_uploaded_file($tmp, $dir . '/' . $name)) {
        throw new RuntimeException('The image could not be saved. Check public/uploads permissions.');
    }
    return [
        'path' => 'public/uploads/website-media/' . $name,
        'width' => (int)$size[0],
        'height' => (int)$size[1],
        'bytes' => (int)($file['size'] ?? 0),
        'original' => $original,
    ];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        $action = (string)($_POST['action'] ?? '');
        $items = public_website_media_items();

        if ($action === 'upload_media') {
            $upload = website_media_upload();
            $label = substr(trim((string)($_POST['label'] ?? '')), 0, 120);
            $alt = substr(trim((string)($_POST['alt'] ?? '')), 0, 160);
            public_website_register_media((string)$upload['path'], $label ?: (string)$upload['original'], $alt, 'media_library');
            audit('website_media_uploaded', 'website_media', null, ['path' => $upload['path'], 'label' => $label, 'width' => $upload['width'], 'height' => $upload['height']]);
            flash('success', 'Image uploaded to the Website Media Library.');
            website_media_redirect();
        }

        if ($action === 'save_media_meta') {
            $id = preg_replace('/[^a-zA-Z0-9_-]/', '', (string)($_POST['id'] ?? ''));
            foreach ($items as &$item) {
                if (($item['id'] ?? '') === $id) {
                    $item['label'] = substr(trim((string)($_POST['label'] ?? $item['label'])), 0, 120);
                    $item['alt'] = substr(trim((string)($_POST['alt'] ?? $item['alt'])), 0, 160);
                }
            }
            unset($item);
            public_website_save_media_items($items);
            audit('website_media_updated', 'website_media', $id);
            flash('success', 'Media details saved.');
            website_media_redirect('#media-library');
        }

        if ($action === 'delete_media') {
            $id = preg_replace('/[^a-zA-Z0-9_-]/', '', (string)($_POST['id'] ?? ''));
            $deleteFile = !empty($_POST['delete_file']);
            $path = '';
            $items = array_values(array_filter($items, static function (array $item) use ($id, &$path): bool {
                if (($item['id'] ?? '') === $id) {
                    $path = (string)($item['path'] ?? '');
                    return false;
                }
                return true;
            }));
            public_website_save_media_items($items);
            if ($deleteFile && public_website_image_path_allowed($path)) {
                $real = DENTAL_ROOT . '/' . $path;
                if (is_file($real)) @unlink($real);
            }
            audit('website_media_deleted', 'website_media', $id, ['file_deleted' => $deleteFile]);
            flash('success', 'Media item removed from the library.' . ($deleteFile ? ' The file was also deleted.' : ''));
            website_media_redirect('#media-library');
        }

        throw new RuntimeException('Unknown media action.');
    } catch (Throwable $exception) {
        flash('error', $exception->getMessage());
        website_media_redirect();
    }
}

$mediaItems = public_website_media_items();
render_header('Website Media Library');
?>
<div class="tabs"><a href="settings.php">Landing Page Editor</a><a href="website_pages.php">Pages &amp; Navigation</a><a class="active">Media Library</a><a href="branding.php">Branding &amp; Identity</a><a href="index.php" target="_blank" rel="noopener">Preview Public Website</a></div>
<section class="website-builder-intro card">
    <div><span class="eyebrow">Media library</span><h2>Upload once, reuse across landing sections and public webpages</h2><p>Use this for hero photos, service images, announcement graphics, branch photos, and page banners. Images stay in <code>public/uploads/website-media</code> with executable files blocked.</p></div>
    <a class="btn ghost" href="website_pages.php">Back to Pages</a>
</section>
<section class="grid two website-media-manager">
    <form method="post" enctype="multipart/form-data" class="card form-grid">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="action" value="upload_media">
        <h2 class="wide">Upload image</h2>
        <label class="wide">Image file<input type="file" name="media_file" accept="image/png,image/jpeg,image/webp" required><small>JPG, PNG, or WebP. Maximum 5 MB.</small></label>
        <label>Library label<input name="label" maxlength="120" placeholder="Clinic front desk"></label>
        <label>Default alt text<input name="alt" maxlength="160" placeholder="Describe the image for accessibility"></label>
        <button class="btn primary wide" type="submit">Upload to Media Library</button>
    </form>
    <div class="card">
        <h2>How to use media</h2>
        <p>After uploading, open <strong>Landing Page Editor</strong> to assign images to landing-page sections, or open <strong>Pages &amp; Navigation</strong> to select the image as a page hero/content image.</p>
        <div class="quick-actions"><a href="settings.php">Landing editor</a><a href="website_pages.php">Page designer</a><a href="branding.php">Logo and favicon</a></div>
    </div>
</section>
<section id="media-library" class="card">
    <div class="card-head"><div><h2>Uploaded media</h2><p><?= count($mediaItems) ?> image<?= count($mediaItems) === 1 ? '' : 's' ?> available for reuse.</p></div></div>
    <?php if (!$mediaItems): ?>
        <div class="empty-cell">No images uploaded yet.</div>
    <?php else: ?>
        <div class="website-media-grid">
        <?php foreach ($mediaItems as $media): ?>
            <article class="website-media-card">
                <figure><img src="<?= e((string)$media['path']) ?>" alt="<?= e((string)$media['alt']) ?>"></figure>
                <form method="post" class="form-grid compact-form">
                    <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                    <input type="hidden" name="action" value="save_media_meta">
                    <input type="hidden" name="id" value="<?= e((string)$media['id']) ?>">
                    <label class="wide">Label<input name="label" maxlength="120" value="<?= e((string)$media['label']) ?>"></label>
                    <label class="wide">Alt text<input name="alt" maxlength="160" value="<?= e((string)$media['alt']) ?>"></label>
                    <div class="wide media-path"><code><?= e((string)$media['path']) ?></code></div>
                    <button class="btn ghost wide" type="submit">Save Details</button>
                </form>
                <form method="post" class="media-delete-form" onsubmit="return confirm('Remove this image from the media library?')">
                    <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                    <input type="hidden" name="action" value="delete_media">
                    <input type="hidden" name="id" value="<?= e((string)$media['id']) ?>">
                    <label class="check-label"><input type="checkbox" name="delete_file" value="1"><span>Also delete physical file</span></label>
                    <button class="btn danger" type="submit">Remove</button>
                </form>
            </article>
        <?php endforeach; ?>
        </div>
    <?php endif; ?>
</section>
<?php render_footer();
