<?php
/**
 * Edit Gallery Image
 */

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

checkAdminAuth();

$id = intval($_GET['id'] ?? 0);
$pdo = getDBConnection();
$message = '';

// Get image data
$stmt = $pdo->prepare("SELECT * FROM gallery_images WHERE id = :id");
$stmt->execute([':id' => $id]);
$image = $stmt->fetch();

if (!$image) {
    header('Location: gallery.php');
    exit;
}

// Handle update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $caption = sanitizeInput($_POST['caption'] ?? '');
    $altText = sanitizeInput($_POST['alt_text'] ?? '');
    $status = sanitizeInput($_POST['status'] ?? 'active');
    
    // Handle image replacement if new file uploaded
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $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/';
            $extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $filename = uniqid() . '_' . time() . '.' . $extension;
            $filepath = $uploadDir . $filename;
            
            if (move_uploaded_file($_FILES['image']['tmp_name'], $filepath)) {
                // Delete old file
                $oldFile = $uploadDir . $image['filename'];
                if (file_exists($oldFile)) {
                    unlink($oldFile);
                }
                
                // Update with new filename
                $updateStmt = $pdo->prepare("
                    UPDATE gallery_images 
                    SET filename = :filename, original_filename = :original, 
                        caption = :caption, alt_text = :alt_text, status = :status
                    WHERE id = :id
                ");
                
                $updateStmt->execute([
                    ':filename' => $filename,
                    ':original' => $_FILES['image']['name'],
                    ':caption' => $caption,
                    ':alt_text' => $altText,
                    ':status' => $status,
                    ':id' => $id
                ]);
                
                $message = 'Image updated successfully!';
                // Refresh image data
                $stmt = $pdo->prepare("SELECT * FROM gallery_images WHERE id = :id");
                $stmt->execute([':id' => $id]);
                $image = $stmt->fetch();
            } else {
                $message = 'Failed to upload new image.';
            }
        }
    } else {
        // Just update metadata
        $updateStmt = $pdo->prepare("
            UPDATE gallery_images 
            SET caption = :caption, alt_text = :alt_text, status = :status
            WHERE id = :id
        ");
        
        $updateStmt->execute([
            ':caption' => $caption,
            ':alt_text' => $altText,
            ':status' => $status,
            ':id' => $id
        ]);
        
        $message = 'Image details updated successfully!';
        // Refresh image data
        $stmt = $pdo->prepare("SELECT * FROM gallery_images WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $image = $stmt->fetch();
    }
}
?>
$pageTitle = 'Edit Gallery Image';
?>
<!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 class="card slide-up">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 2rem; margin-bottom: 2rem;">
                <div>
                    <h3>Current Image</h3>
                    <img src="../uploads/gallery/<?php echo htmlspecialchars($image['filename']); ?>" 
                         alt="<?php echo htmlspecialchars($image['alt_text'] ?: $image['caption']); ?>"
                         style="max-width: 100%; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                </div>
                <div>
                    <h3>Image Details</h3>
                    <p><strong>Filename:</strong> <?php echo htmlspecialchars($image['filename']); ?></p>
                    <p><strong>Original:</strong> <?php echo htmlspecialchars($image['original_filename']); ?></p>
                    <p><strong>Uploaded:</strong> <?php echo date('F d, Y', strtotime($image['created_at'])); ?></p>
                </div>
            </div>
            
            <form method="POST" enctype="multipart/form-data" class="upload-form">
                <div class="form-group">
                    <label for="image">Replace Image (optional)</label>
                    <input type="file" id="image" name="image" accept="image/*">
                    <small style="color: #64748B; display: block; margin-top: 0.5rem;">
                        Leave empty to keep current image. Only upload if you want to replace it.
                    </small>
                </div>
                <div class="form-group">
                    <label for="caption">Caption</label>
                    <input type="text" id="caption" name="caption" 
                           value="<?php echo htmlspecialchars($image['caption']); ?>" 
                           placeholder="Optional caption">
                </div>
                <div class="form-group">
                    <label for="alt_text">Alt Text</label>
                    <input type="text" id="alt_text" name="alt_text" 
                           value="<?php echo htmlspecialchars($image['alt_text']); ?>" 
                           placeholder="Optional alt text for accessibility">
                </div>
                <div class="form-group">
                    <label for="status">Status</label>
                    <select id="status" name="status">
                        <option value="active" <?php echo $image['status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                        <option value="inactive" <?php echo $image['status'] === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>
                        <div style="display: flex; gap: 1rem;">
                            <button type="submit" class="btn btn-primary">Update Image</button>
                            <a href="gallery.php" class="btn btn-secondary">Cancel</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <script src="assets/admin.js"></script>
</body>
</html>

