<?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') {
    $title = trim($_POST['title'] ?? '');
    $category = trim($_POST['category'] ?? '');
    $image = $_FILES['image'] ?? null;
    
    if (!$title || !$category || !$image || $image['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['success' => false, 'message' => 'All fields are required and image must be provided']);
        exit;
    }
    
    // Validate image file
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $max_size = 5 * 1024 * 1024; // 5MB
    
    if (!in_array($image['type'], $allowed_types)) {
        echo json_encode(['success' => false, 'message' => 'Invalid image type. Only JPG, PNG, GIF, and WebP allowed']);
        exit;
    }
    
    if ($image['size'] > $max_size) {
        echo json_encode(['success' => false, 'message' => 'Image size exceeds 5MB limit']);
        exit;
    }
    
    // Create uploads directory if it doesn't exist
    $upload_dir = __DIR__ . '/assets/uploads/gallery';
    if (!is_dir($upload_dir)) {
        @mkdir($upload_dir, 0755, true);
    }
    
    // Generate unique filename
    $ext = strtolower(pathinfo($image['name'], PATHINFO_EXTENSION));
    $filename = time() . '_' . uniqid() . '.' . $ext;
    $upload_path = $upload_dir . '/' . $filename;
    $image_url = 'assets/uploads/gallery/' . $filename;
    
    // Move uploaded file
    if (!move_uploaded_file($image['tmp_name'], $upload_path)) {
        echo json_encode(['success' => false, 'message' => 'Failed to upload image']);
        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);
    
    // Find the next ID by looking at existing gallery items
    preg_match_all('/data-gallery-id=["\'](\d+)["\']/', $content, $id_matches);
    $max_id = 0;
    if (!empty($id_matches[1])) {
        $max_id = max(array_map('intval', $id_matches[1]));
    }
    $new_id = $max_id + 1;
    
    // Create new gallery item HTML
    $new_gallery_item = <<<EOT
                <div class="col-lg-6 col-xl-4 col-xxl-auto filter-item cat1" data-gallery-id="$new_id">
                    <div class="gallery-card">
                        <div class="box-img global-img"><img src="$image_url" alt="$title"> <a href="$image_url" class="icon-btn th-popup-image"><i class="far fa-plus"></i></a>
                            <div class="shape">
                                <div class="dot"></div>
                                <div class="dot"></div>
                                <div class="dot"></div>
                                <div class="dot"></div>
                            </div>
                        </div>
                        <div class="gallery-content">
                            <h2 class="box-title">$title</h2>
                        </div>
                    </div>
                </div>
EOT;
    
    // Find the gallery-row div and insert before the closing </div>
    $pattern = '/(<div class="row gy-4 gallery-row filter-active">.*?)([\s]*<\/div>[\s]*<\/div>[\s]*<\/div>[\s]*<!-- FOOTER -->)/s';
    
    if (preg_match($pattern, $content, $matches)) {
        $replacement = $matches[1] . "\n" . $new_gallery_item . $matches[2];
        $new_content = preg_replace($pattern, $replacement, $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) {
                $php_replacement = $matches[1] . "\n" . $new_gallery_item . $matches[2];
                $new_php_content = preg_replace($pattern, $php_replacement, $php_content);
                
                if (@file_put_contents($gallery_php_file, $new_php_content)) {
                    echo json_encode(['success' => true, 'message' => 'Gallery item added successfully', 'id' => $new_id]);
                } else {
                    echo json_encode(['success' => true, 'message' => 'Gallery item added but PHP file update failed', 'id' => $new_id]);
                }
            } else {
                echo json_encode(['success' => true, 'message' => 'Gallery item added but could not read PHP file', 'id' => $new_id]);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update gallery file']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Could not find gallery section in HTML']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}
?>
