<?php
require_once __DIR__ . '/bootstrap.php';
/**
 * Admin Media Library
 */

if (!\Core\Auth::check()) {
    header('Location: /admin/login.php');
    exit;
}

// Database and Models are already handled.

$successMessage = null;
$errorMessage = null;
$isAjaxUpload = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';

// Handle upload (both form and AJAX)
if ((isset($_POST['upload']) || $isAjaxUpload) && isset($_FILES['file'])) {
    $uploadDir = __DIR__ . '/../uploads/';

    // Ensure upload dir exists
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    // Normalize $_FILES structure for both single and multiple file uploads
    $files = $_FILES['file'];
    $uploadedPaths = [];

    // Check if it's a multi-file upload (GrapesJS sends as array)
    if (is_array($files['name'])) {
        $fileCount = count($files['name']);
        for ($i = 0; $i < $fileCount; $i++) {
            if ($files['error'][$i] === UPLOAD_ERR_OK) {
                $result = processUpload(
                    $files['tmp_name'][$i],
                    $files['name'][$i],
                    $files['type'][$i],
                    $files['size'][$i],
                    $uploadDir
                );
                if ($result)
                    $uploadedPaths[] = $result;
            }
        }
    } else {
        // Single file upload
        if ($files['error'] === UPLOAD_ERR_OK) {
            $result = processUpload(
                $files['tmp_name'],
                $files['name'],
                $files['type'],
                $files['size'],
                $uploadDir
            );
            if ($result)
                $uploadedPaths[] = $result;
        }
    }

    // Return JSON for AJAX (GrapesJS Asset Manager)
    if ($isAjaxUpload) {
        header('Content-Type: application/json');
        echo json_encode(['data' => $uploadedPaths]);
        exit;
    }

    if (!empty($uploadedPaths)) {
        $successMessage = count($uploadedPaths) . ' file(s) uploaded successfully!';
    } else {
        $errorMessage = 'Failed to upload file(s).';
    }
}

/**
 * Process a single file upload
 * @return string|null Path to uploaded file or null on failure
 */
function processUpload($tmpName, $originalName, $mimeType, $fileSize, $uploadDir)
{
    $filename = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', basename($originalName));
    $targetPath = $uploadDir . $filename;

    if (move_uploaded_file($tmpName, $targetPath)) {
        $webpFilename = pathinfo($filename, PATHINFO_FILENAME) . '.webp';
        $webpPath = $uploadDir . $webpFilename;

        if (strpos($mimeType, 'image/') === 0) {
            \Core\ImageProcessor::convertToWebP($targetPath, $webpPath);

            // Generate thumbnail
            $thumbFilename = pathinfo($filename, PATHINFO_FILENAME) . '_thumb.webp';
            $thumbPath = $uploadDir . $thumbFilename;
            \Core\ImageProcessor::resize($targetPath, $thumbPath, 300);

            // Remove original if WebP created successfully
            if (file_exists($webpPath)) {
                @unlink($targetPath);
            }

            $finalFilename = $webpFilename;
            $finalPath = '/uploads/' . $webpFilename;
            $finalType = 'image/webp';
        } else {
            $finalFilename = $filename;
            $finalPath = '/uploads/' . $filename;
            $finalType = $mimeType;
        }

        \Models\Media::create([
            'filename' => $finalFilename,
            'filepath' => $finalPath,
            'mimetype' => $finalType,
            'filesize' => $fileSize
        ]);

        return $finalPath;
    }

    return null;
}

// Handle delete
if (isset($_POST['delete']) && isset($_POST['media_id'])) {
    $media = \Models\Media::find($_POST['media_id']);
    if ($media) {
        $filePath = __DIR__ . '/../uploads/' . $media['filename'];
        if (file_exists($filePath)) {
            unlink($filePath);
        }
        \Models\Media::delete($_POST['media_id']);
        $successMessage = 'Media deleted successfully!';
    }
}

$mediaItems = \Models\Media::all();

// Page settings
$pageTitle = 'Media Library';
$currentPage = 'media';
$headerActions = '<button class="button is-primary" onclick="document.getElementById(\'uploadModal\').classList.add(\'is-active\')">
    <span class="icon"><i class="fas fa-upload"></i></span>
    <span>Upload Media</span>
</button>';

// Start content buffer
ob_start();
?>

<!-- Stats -->
<div class="columns mb-5">
    <div class="column is-3">
        <div class="stat-card">
            <div class="stat-icon is-info">
                <i class="fas fa-images"></i>
            </div>
            <div class="stat-content">
                <div class="stat-value"><?= count($mediaItems) ?></div>
                <div class="stat-label">Total Files</div>
            </div>
        </div>
    </div>
    <div class="column is-3">
        <div class="stat-card">
            <div class="stat-icon is-success">
                <i class="fas fa-image"></i>
            </div>
            <div class="stat-content">
                <div class="stat-value">
                    <?= count(array_filter($mediaItems, fn($m) => strpos($m['mimetype'] ?? '', 'image') !== false)) ?>
                </div>
                <div class="stat-label">Images</div>
            </div>
        </div>
    </div>
    <div class="column is-3">
        <div class="stat-card">
            <div class="stat-icon is-warning">
                <i class="fas fa-file"></i>
            </div>
            <div class="stat-content">
                <div class="stat-value">
                    <?= count(array_filter($mediaItems, fn($m) => strpos($m['mimetype'] ?? '', 'image') === false)) ?>
                </div>
                <div class="stat-label">Documents</div>
            </div>
        </div>
    </div>
    <div class="column is-3">
        <div class="stat-card">
            <div class="stat-icon is-primary">
                <i class="fas fa-database"></i>
            </div>
            <div class="stat-content">
                <div class="stat-value"><?= round(array_sum(array_column($mediaItems, 'filesize')) / 1024 / 1024, 1) ?>
                    MB</div>
                <div class="stat-label">Total Size</div>
            </div>
        </div>
    </div>
</div>

<!-- Media Grid -->
<div class="admin-card">
    <h2 class="card-header-title">
        <span class="icon mr-2"><i class="fas fa-images"></i></span>
        Media Files
    </h2>

    <?php if (empty($mediaItems)): ?>
        <div class="has-text-centered p-6">
            <span class="icon is-large has-text-grey-light">
                <i class="fas fa-images fa-3x"></i>
            </span>
            <p class="has-text-grey mt-4">No media files yet. Upload your first file!</p>
        </div>
    <?php else: ?>
        <div class="columns is-multiline">
            <?php foreach ($mediaItems as $item): ?>
                <div class="column is-2">
                    <div class="media-card box p-3">
                        <?php if (strpos($item['mimetype'] ?? '', 'image/') === 0): ?>
                            <figure class="image is-square mb-2">
                                <img src="/uploads/<?= htmlspecialchars($item['filename']) ?>"
                                    alt="<?= htmlspecialchars($item['alt_text'] ?? '') ?>"
                                    style="object-fit: cover; border-radius: 4px;">
                            </figure>
                        <?php else: ?>
                            <div class="has-background-light has-text-centered p-4 mb-2" style="border-radius: 4px;">
                                <span class="icon is-large has-text-grey">
                                    <i class="fas fa-file fa-2x"></i>
                                </span>
                            </div>
                        <?php endif; ?>

                        <p class="is-size-7 has-text-weight-semibold" style="word-break: break-all;">
                            <?= htmlspecialchars($item['filename']) ?>
                        </p>
                        <p class="is-size-7 has-text-grey">
                            <?= round(($item['filesize'] ?? 0) / 1024, 1) ?> KB
                        </p>

                        <div class="buttons are-small mt-2">
                            <button class="button is-small is-fullwidth copy-url"
                                data-url="/uploads/<?= htmlspecialchars($item['filename']) ?>">
                                <span class="icon"><i class="fas fa-copy"></i></span>
                                <span>Copy URL</span>
                            </button>
                            <form method="POST" class="is-fullwidth" onsubmit="return confirm('Delete this file?')">
                                <input type="hidden" name="media_id" value="<?= $item['id'] ?>">
                                <input type="hidden" name="csrf_token" value="<?= \Core\Auth::generateCsrfToken() ?>">
                                <button type="submit" name="delete" class="button is-small is-danger is-light is-fullwidth">
                                    <span class="icon"><i class="fas fa-trash"></i></span>
                                    <span>Delete</span>
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<!-- Upload Modal -->
<div class="modal" id="uploadModal">
    <div class="modal-background" onclick="this.parentElement.classList.remove('is-active')"></div>
    <div class="modal-card">
        <header class="modal-card-head">
            <p class="modal-card-title">Upload Media</p>
            <button class="delete" aria-label="close"
                onclick="this.closest('.modal').classList.remove('is-active')"></button>
        </header>
        <form action="" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="csrf_token" value="<?= \Core\Auth::generateCsrfToken() ?>">
            <section class="modal-card-body">
                <div class="file is-boxed is-centered is-primary">
                    <label class="file-label">
                        <input class="file-input" type="file" name="file" required>
                        <span class="file-cta">
                            <span class="file-icon">
                                <i class="fas fa-upload"></i>
                            </span>
                            <span class="file-label">
                                Choose a file…
                            </span>
                        </span>
                    </label>
                </div>
                <p class="help has-text-centered mt-4">
                    Supported: Images (JPG, PNG, GIF, WebP), PDFs, Documents
                </p>
            </section>
            <footer class="modal-card-foot">
                <button type="submit" name="upload" class="button is-primary">Upload</button>
                <button type="button" class="button"
                    onclick="this.closest('.modal').classList.remove('is-active')">Cancel</button>
            </footer>
        </form>
    </div>
</div>

<style>
    .media-card {
        transition: all 0.2s;
    }

    .media-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    /* Drag & Drop Zone */
    .dropzone {
        border: 2px dashed #dee2e6;
        border-radius: 12px;
        padding: 40px;
        text-align: center;
        transition: all 0.3s;
        background: #f8f9fa;
        cursor: pointer;
        margin-bottom: 1.5rem;
    }

    .dropzone:hover,
    .dropzone.dragover {
        border-color: #3e8ed0;
        background: #e8f4fc;
    }

    .dropzone.dragover {
        transform: scale(1.02);
    }

    .dropzone-icon {
        font-size: 3rem;
        color: #6c757d;
        margin-bottom: 1rem;
    }

    .dropzone.dragover .dropzone-icon {
        color: #3e8ed0;
    }

    .upload-progress {
        display: none;
        margin-top: 1rem;
    }

    .upload-progress.active {
        display: block;
    }
</style>

<script>
    // Drag & Drop Upload
    const dropzone = document.querySelector('.dropzone') || document.body;
    const fileInput = document.querySelector('.file-input');

    // Create dropzone if not exists
    if (!document.querySelector('.dropzone')) {
        const adminCard = document.querySelector('.admin-card');
        const dropzoneHtml = `
            <div class="dropzone" id="dropzone">
                <div class="dropzone-icon"><i class="fas fa-cloud-upload-alt"></i></div>
                <p class="has-text-grey-dark has-text-weight-semibold">Drag & drop files here</p>
                <p class="has-text-grey is-size-7">or click to browse</p>
                <div class="upload-progress">
                    <progress class="progress is-primary" max="100">0%</progress>
                </div>
            </div>
        `;
        adminCard.insertAdjacentHTML('afterbegin', dropzoneHtml);
    }

    const dz = document.getElementById('dropzone');

    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dz?.addEventListener(eventName, (e) => {
            e.preventDefault();
            e.stopPropagation();
        });
    });

    ['dragenter', 'dragover'].forEach(eventName => {
        dz?.addEventListener(eventName, () => dz.classList.add('dragover'));
    });

    ['dragleave', 'drop'].forEach(eventName => {
        dz?.addEventListener(eventName, () => dz.classList.remove('dragover'));
    });

    dz?.addEventListener('click', () => fileInput?.click());

    dz?.addEventListener('drop', (e) => {
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            uploadFile(files[0]);
        }
    });

    function uploadFile(file) {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('upload', '1');

        const progress = dz.querySelector('.upload-progress');
        progress?.classList.add('active');

        fetch('/admin/media.php', {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            body: formData
        })
            .then(res => res.json())
            .then(data => {
                if (data.data) {
                    location.reload();
                } else {
                    alert('Upload failed');
                }
            })
            .catch(err => {
                console.error(err);
                alert('Upload error');
            })
            .finally(() => {
                progress?.classList.remove('active');
            });
    }

    // Copy URL
    document.querySelectorAll('.copy-url').forEach(btn => {
        btn.addEventListener('click', function () {
            const url = window.location.origin + this.dataset.url;
            navigator.clipboard.writeText(url).then(() => {
                const span = this.querySelector('span:last-child');
                span.textContent = 'Copied!';
                setTimeout(() => span.textContent = 'Copy URL', 1500);
            });
        });
    });

    // File input label
    document.querySelector('.file-input')?.addEventListener('change', function () {
        const fileName = this.files[0]?.name;
        if (fileName) {
            document.querySelector('.file-label .file-label').textContent = fileName;
            uploadFile(this.files[0]);
        }
    });
</script>

<?php
$content = ob_get_clean();
include __DIR__ . '/layouts/admin_layout.php';