<?php
session_start();

// Check if user is logged in and is admin
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('HTTP/1.0 403 Forbidden');
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $gallery_id = intval($_POST['gallery_id'] ?? 0);
    
    if (!$gallery_id) {
        echo json_encode(['success' => false, 'message' => 'Gallery ID is required']);
        exit;
    }
    
    // Read gallery.html
    $gallery_file = __DIR__ . '/gallery.html';
    $gallery_php_file = __DIR__ . '/gallery.php';
    $content = @file_get_contents($gallery_file);
    
    if ($content === false) {
        echo json_encode(['success' => false, 'message' => 'Failed to read gallery file']);
        exit;
    }
    
    // Check if gallery.php exists
    if (!file_exists($gallery_php_file)) {
        echo json_encode(['success' => false, 'message' => 'Gallery PHP file not found']);
        exit;
    }
    
    // Create backup
    $backup_file = $gallery_file . '.bak.' . date('Y-m-d_H-i-s');
    @copy($gallery_file, $backup_file);
    
    // Method 1: Try to find the exact gallery item with proper class and data-gallery-id
    // Match from <div class="col-lg-6 col-xl-4 col-xxl-auto filter-item" ... data-gallery-id="X">
    // through the complete closing structure </div></div></div>
    $pattern = '/<div\s+class="col-lg-6\s+col-xl-4\s+col-xxl-auto\s+filter-item[^>]*?\bdata-gallery-id="' . $gallery_id . '"[^>]*?>[\s\S]*?<\/div>\s*<\/div>\s*<\/div>/i';
    
    if (preg_match($pattern, $content, $matches)) {
        // Remove the matched item with proper whitespace cleanup
        $new_content = preg_replace($pattern, '', $content);
        // Clean up any leftover multiple newlines
        $new_content = preg_replace('/\n\s*\n\s*\n/', "\n", $new_content);
        
        if (@file_put_contents($gallery_file, $new_content)) {
            // Also update gallery.php
            $php_content = @file_get_contents($gallery_php_file);
            if ($php_content !== false) {
                $new_php_content = preg_replace($pattern, '', $php_content);
                $new_php_content = preg_replace('/\n\s*\n\s*\n/', "\n", $new_php_content);
                
                if (@file_put_contents($gallery_php_file, $new_php_content)) {
                    echo json_encode(['success' => true, 'message' => 'Gallery item deleted successfully']);
                } else {
                    echo json_encode(['success' => true, 'message' => 'Gallery item deleted but PHP file update failed']);
                }
            } else {
                echo json_encode(['success' => true, 'message' => 'Gallery item deleted but could not read PHP file']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update gallery file']);
        }
    } else {
        // Method 2: More aggressive fallback - look for data-gallery-id anywhere in a div
        $fallback_pattern = '/<div[^>]*?\bdata-gallery-id="' . $gallery_id . '"[^>]*?>[\s\S]*?(?:<\/div>){3}/i';
        
        if (preg_match($fallback_pattern, $content, $matches)) {
            $new_content = preg_replace($fallback_pattern, '', $content);
            $new_content = preg_replace('/\n\s*\n\s*\n/', "\n", $new_content);
            
            if (@file_put_contents($gallery_file, $new_content)) {
                // Also update gallery.php
                $php_content = @file_get_contents($gallery_php_file);
                if ($php_content !== false) {
                    $new_php_content = preg_replace($fallback_pattern, '', $php_content);
                    $new_php_content = preg_replace('/\n\s*\n\s*\n/', "\n", $new_php_content);
                    
                    if (@file_put_contents($gallery_php_file, $new_php_content)) {
                        echo json_encode(['success' => true, 'message' => 'Gallery item deleted successfully']);
                    } else {
                        echo json_encode(['success' => true, 'message' => 'Gallery item deleted but PHP file update failed']);
                    }
                } else {
                    echo json_encode(['success' => true, 'message' => 'Gallery item deleted but could not read PHP file']);
                }
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to update gallery file']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Gallery item not found']);
        }
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}
?>
