<?php
session_start();

if (!isset($_SESSION['admin_logged_in'])) {
    header('Location: admin_login.php');
    exit;
}

$category = $_GET['category'] ?? '';
if (empty($category)) {
    header('Location: admin.php?error=Invalid category');
    exit;
}

$categoryPath = "uploads/projects/" . $category;
if (!is_dir($categoryPath)) {
    header('Location: admin.php?error=Category not found');
    exit;
}

// Handle file upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['media_files'])) {
    $uploadedCount = 0;
    $errors = [];
    
    $allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/webp', 'video/mp4'];
    $maxFileSize = 20 * 1024 * 1024; // 20MB
    
    foreach ($_FILES['media_files']['tmp_name'] as $key => $tmpName) {
        if ($_FILES['media_files']['error'][$key] === UPLOAD_ERR_OK) {
            $fileType = $_FILES['media_files']['type'][$key];
            $fileSize = $_FILES['media_files']['size'][$key];
            $fileName = $_FILES['media_files']['name'][$key];
            
            // Validate file type
            if (!in_array($fileType, $allowedTypes)) {
                $errors[] = "$fileName: Invalid file type";
                continue;
            }
            
            // Validate file size
            if ($fileSize > $maxFileSize) {
                $errors[] = "$fileName: File too large (max 20MB)";
                continue;
            }
            
            // Generate unique filename
            $ext = pathinfo($fileName, PATHINFO_EXTENSION);
            $newFileName = uniqid() . '_' . time() . '.' . $ext;
            $destination = "$categoryPath/$newFileName";
            
            if (move_uploaded_file($tmpName, $destination)) {
                // Optimize image if it's an image
                if (str_starts_with($fileType, 'image/')) {
                    optimizeImage($destination, $fileType);
                }
                $uploadedCount++;
            } else {
                $errors[] = "$fileName: Upload failed";
            }
        }
    }
    
    if ($uploadedCount > 0) {
        $message = "$uploadedCount file(s) uploaded successfully!";
        if (!empty($errors)) {
            $message .= " " . count($errors) . " failed.";
        }
        header("Location: manage_media.php?category=$category&success=" . urlencode($message));
        exit;
    } elseif (!empty($errors)) {
        header("Location: manage_media.php?category=$category&error=" . urlencode(implode(', ', $errors)));
        exit;
    }
}

// Function to optimize images
function optimizeImage($filePath, $mimeType) {
    $maxWidth = 1920;
    $maxHeight = 1920;
    $quality = 85;
    
    list($width, $height) = getimagesize($filePath);
    
    // Check if resizing is needed
    if ($width <= $maxWidth && $height <= $maxHeight) {
        return; // No optimization needed
    }
    
    // Calculate new dimensions
    $ratio = min($maxWidth / $width, $maxHeight / $height);
    $newWidth = round($width * $ratio);
    $newHeight = round($height * $ratio);
    
    // Create image resource
    switch ($mimeType) {
        case 'image/jpeg':
        case 'image/jpg':
            $source = imagecreatefromjpeg($filePath);
            break;
        case 'image/png':
            $source = imagecreatefrompng($filePath);
            break;
        case 'image/webp':
            $source = imagecreatefromwebp($filePath);
            break;
        default:
            return;
    }
    
    if (!$source) return;
    
    // Create resized image
    $dest = imagecreatetruecolor($newWidth, $newHeight);
    
    // Preserve transparency for PNG
    if ($mimeType === 'image/png') {
        imagealphablending($dest, false);
        imagesavealpha($dest, true);
    }
    
    imagecopyresampled($dest, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    
    // Save optimized image
    switch ($mimeType) {
        case 'image/jpeg':
        case 'image/jpg':
            imagejpeg($dest, $filePath, $quality);
            break;
        case 'image/png':
            imagepng($dest, $filePath, 8);
            break;
        case 'image/webp':
            imagewebp($dest, $filePath, $quality);
            break;
    }
    
    imagedestroy($source);
    imagedestroy($dest);
}

// Get all media files
$files = glob("$categoryPath/*.{jpg,jpeg,png,mp4,webp}", GLOB_BRACE);

include "head.php";
?>

<style>
.admin-container {
    max-width: 1400px;
    margin: 80px auto;
    padding: 20px;
}
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32px;
    padding-bottom: 20px;
    border-bottom: 2px solid #e0e0e0;
}
.page-header h1 {
    font-size: 2rem;
    color: #333;
}
.breadcrumb {
    color: #666;
    font-size: 14px;
    margin-top: 8px;
}
.breadcrumb a {
    color: #0d6efd;
    text-decoration: none;
}
.upload-section {
    background: white;
    border-radius: 12px;
    padding: 32px;
    margin-bottom: 32px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
.upload-zone {
    border: 3px dashed #d0d0d0;
    border-radius: 12px;
    padding: 48px 32px;
    text-align: center;
    transition: all 0.3s;
    cursor: pointer;
}
.upload-zone:hover {
    border-color: #0d6efd;
    background: #f8f9ff;
}
.upload-zone.dragover {
    border-color: #0d6efd;
    background: #e7f1ff;
}
.upload-icon {
    font-size: 48px;
    margin-bottom: 16px;
}
.file-input {
    display: none;
}
.btn {
    padding: 12px 24px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 600;
    text-decoration: none;
    display: inline-block;
    transition: all 0.3s;
}
.btn-primary {
    background: #0d6efd;
    color: white;
}
.btn-secondary {
    background: #6c757d;
    color: white;
}
.media-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 24px;
}
.media-item {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    transition: transform 0.3s;
    position: relative;
}
.media-item:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 20px rgba(0,0,0,0.15);
}
.media-preview {
    width: 100%;
    height: 240px;
    object-fit: cover;
    background: #f5f5f5;
}
.media-info {
    padding: 16px;
}
.media-filename {
    font-size: 13px;
    color: #666;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-bottom: 12px;
}
.media-actions {
    display: flex;
    gap: 8px;
}
.btn-delete {
    flex: 1;
    background: #dc3545;
    color: white;
    padding: 8px 12px;
    text-align: center;
}
.btn-delete:hover {
    background: #bb2d3b;
}
.alert {
    padding: 16px 20px;
    border-radius: 8px;
    margin-bottom: 24px;
}
.alert-success {
    background: #d1e7dd;
    color: #0f5132;
}
.alert-error {
    background: #f8d7da;
    color: #842029;
}
.empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #999;
}
@media(max-width: 768px) {
    .page-header {
        flex-direction: column;
        gap: 16px;
        align-items: flex-start;
    }
    .media-grid {
        grid-template-columns: 1fr;
    }
}
</style>

<div class="admin-container">
    <div class="page-header">
        <div>
            <h1>📸 Manage Media</h1>
            <div class="breadcrumb">
                <a href="admin.php">← Back to Categories</a> / 
                <?= ucwords(str_replace('-', ' ', $category)) ?>
            </div>
        </div>
    </div>

    <?php if (isset($_GET['success'])): ?>
        <div class="alert alert-success">
            <?= htmlspecialchars($_GET['success']) ?>
        </div>
    <?php endif; ?>

    <?php if (isset($_GET['error'])): ?>
        <div class="alert alert-error">
            <?= htmlspecialchars($_GET['error']) ?>
        </div>
    <?php endif; ?>

    <!-- Upload Section -->
    <div class="upload-section">
        <h2 style="margin-bottom: 20px;">Upload New Media</h2>
        <form method="POST" enctype="multipart/form-data" id="uploadForm">
            <div class="upload-zone" id="uploadZone">
                <div class="upload-icon">📁</div>
                <h3>Drag & Drop Files Here</h3>
                <p style="color: #666; margin: 12px 0;">or click to browse</p>
                <p style="font-size: 13px; color: #999;">
                    Supported: JPG, PNG, WEBP, MP4 • Max 20MB per file
                </p>
                <input 
                    type="file" 
                    name="media_files[]" 
                    id="fileInput" 
                    class="file-input"
                    accept="image/jpeg,image/jpg,image/png,image/webp,video/mp4"
                    multiple
                >
            </div>
            <div id="fileList" style="margin-top: 20px;"></div>
            <button type="submit" class="btn btn-primary" id="uploadBtn" style="margin-top: 20px; display: none;">
                Upload Files
            </button>
        </form>
    </div>

    <!-- Media Grid -->
    <h2 style="margin-bottom: 20px;">📂 Current Media (<?= count($files) ?>)</h2>
    
    <?php if (empty($files)): ?>
        <div class="empty-state">
            <h3>No media files yet</h3>
            <p>Upload your first image or video to get started!</p>
        </div>
    <?php else: ?>
        <div class="media-grid">
            <?php foreach($files as $file): 
                $filename = basename($file);
                $isVideo = str_ends_with($file, '.mp4');
            ?>
                <div class="media-item">
                    <?php if ($isVideo): ?>
                        <video class="media-preview" controls>
                            <source src="<?= $file ?>" type="video/mp4">
                        </video>
                    <?php else: ?>
                        <img src="<?= $file ?>" class="media-preview" alt="<?= $filename ?>">
                    <?php endif; ?>
                    
                    <div class="media-info">
                        <div class="media-filename" title="<?= $filename ?>">
                            <?= $isVideo ? '🎥' : '🖼️' ?> <?= $filename ?>
                        </div>
                        <div class="media-actions">
                            <a href="delete_media.php?category=<?= urlencode($category) ?>&file=<?= urlencode($filename) ?>" 
                               class="btn btn-delete"
                               onclick="return confirm('Delete this file? This cannot be undone!')">
                                Delete
                            </a>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<script>
// Drag and drop functionality
const uploadZone = document.getElementById('uploadZone');
const fileInput = document.getElementById('fileInput');
const fileList = document.getElementById('fileList');
const uploadBtn = document.getElementById('uploadBtn');

uploadZone.addEventListener('click', () => fileInput.click());

uploadZone.addEventListener('dragover', (e) => {
    e.preventDefault();
    uploadZone.classList.add('dragover');
});

uploadZone.addEventListener('dragleave', () => {
    uploadZone.classList.remove('dragover');
});

uploadZone.addEventListener('drop', (e) => {
    e.preventDefault();
    uploadZone.classList.remove('dragover');
    fileInput.files = e.dataTransfer.files;
    displayFiles();
});

fileInput.addEventListener('change', displayFiles);

function displayFiles() {
    const files = fileInput.files;
    if (files.length === 0) {
        fileList.innerHTML = '';
        uploadBtn.style.display = 'none';
        return;
    }
    
    let html = '<div style="background: #f8f9fa; padding: 16px; border-radius: 8px;"><strong>Selected files:</strong><ul style="margin: 8px 0 0 20px;">';
    for (let file of files) {
        html += `<li>${file.name} (${(file.size / 1024 / 1024).toFixed(2)} MB)</li>`;
    }
    html += '</ul></div>';
    
    fileList.innerHTML = html;
    uploadBtn.style.display = 'inline-block';
}
</script>

<?php include "footer.php"; ?>
