<?php
/**
 * Gallery Management
 */

session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/security.php';
require_once __DIR__ . '/includes/auth.php';

checkAdminAuth();

$pdo = getDBConnection();
$message = '';

// Handle image upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['image'])) {
    $allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
    $maxSize = 5 * 1024 * 1024; // 5MB
    
    if (!in_array($_FILES['image']['type'], $allowedTypes)) {
        $message = 'Invalid file type. Only JPEG, PNG, WebP, and GIF are allowed.';
    } elseif ($_FILES['image']['size'] > $maxSize) {
        $message = 'File size exceeds 5MB limit.';
    } else {
        $uploadDir = __DIR__ . '/../uploads/gallery/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        $extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $filename = uniqid() . '_' . time() . '.' . $extension;
        $filepath = $uploadDir . $filename;
        
        if (move_uploaded_file($_FILES['image']['tmp_name'], $filepath)) {
            $caption = sanitizeInput($_POST['caption'] ?? '');
            $altText = sanitizeInput($_POST['alt_text'] ?? '');
            
            $stmt = $pdo->prepare("
                INSERT INTO gallery_images (filename, original_filename, caption, alt_text, uploaded_by, status)
                VALUES (:filename, :original, :caption, :alt_text, :user_id, 'active')
            ");
            
            $stmt->execute([
                ':filename' => $filename,
                ':original' => $_FILES['image']['name'],
                ':caption' => $caption,
                ':alt_text' => $altText,
                ':user_id' => $_SESSION['admin_user_id']
            ]);
            
            $message = 'Image uploaded successfully!';
        } else {
            $message = 'Failed to upload image.';
        }
    }
}

// Get all gallery images
$images = $pdo->query("
    SELECT id, filename, caption, alt_text, created_at, status
    FROM gallery_images
    ORDER BY created_at DESC
")->fetchAll();
?>
$pageTitle = 'Gallery Management';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - Admin Panel</title>
    <link rel="stylesheet" href="assets/admin-modern.css">
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>
    
    <div class="admin-main">
        <?php include 'includes/header-new.php'; ?>
        
        <div class="admin-container">
            <?php if ($message): ?>
                <div class="message <?php echo strpos($message, 'successfully') !== false ? 'success' : 'error'; ?>">
                    <?php echo htmlspecialchars($message); ?>
                </div>
            <?php endif; ?>
            
            <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 1.5rem;">
                <!-- Upload Form -->
                <div class="card slide-up">
                    <div class="card-header">
                        <h3 class="card-title">Upload New Image</h3>
                    </div>
                    <form method="POST" enctype="multipart/form-data">
                        <div class="form-group">
                            <label class="form-label">Image File *</label>
                            <input type="file" id="image" name="image" accept="image/*" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Caption</label>
                            <input type="text" id="caption" name="caption" class="form-control" placeholder="Optional caption">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Alt Text</label>
                            <input type="text" id="alt_text" name="alt_text" class="form-control" placeholder="Optional alt text for accessibility">
                        </div>
                        <button type="submit" class="btn btn-primary">Upload Image</button>
                    </form>
                </div>
                
                <!-- Gallery Grid -->
                <div class="card slide-up" style="animation-delay: 0.2s">
                    <div class="card-header">
                        <h3 class="card-title">Gallery Images (<?php echo count($images); ?>)</h3>
                    </div>
                    <div class="gallery-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 1rem; max-height: 600px; overflow-y: auto;">
                        <?php foreach ($images as $image): ?>
                        <div style="background: var(--bg-secondary); border-radius: var(--radius-md); overflow: hidden; border: 1px solid var(--border-color); transition: var(--transition);" 
                             onmouseover="this.style.transform='translateY(-4px)'; this.style.boxShadow='var(--shadow-md)'"
                             onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='none'">
                            <img src="../uploads/gallery/<?php echo htmlspecialchars($image['filename']); ?>" 
                                 alt="<?php echo htmlspecialchars($image['alt_text'] ?: $image['caption']); ?>"
                                 style="width: 100%; height: 150px; object-fit: cover;">
                            <div style="padding: 0.75rem;">
                                <p style="font-weight: 600; font-size: 0.875rem; margin: 0 0 0.25rem 0; color: var(--text-primary);">
                                    <?php echo htmlspecialchars($image['caption'] ?: 'No caption'); ?>
                                </p>
                                <p style="font-size: 0.75rem; color: var(--text-secondary); margin: 0 0 0.75rem 0;">
                                    <?php echo date('M d, Y', strtotime($image['created_at'])); ?>
                                </p>
                                <div style="display: flex; gap: 0.5rem;">
                                    <a href="gallery-edit.php?id=<?php echo $image['id']; ?>" 
                                       class="btn btn-sm btn-secondary" style="flex: 1; text-align: center;">Edit</a>
                                    <a href="gallery-delete.php?id=<?php echo $image['id']; ?>" 
                                       class="btn btn-sm btn-danger"
                                       onclick="return confirm('Delete this image?')">Delete</a>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="assets/admin.js"></script>
</body>
</html>

