<?php
// Gallery API for managing categories and photos
session_start();
header('Content-Type: application/json');

include 'config.php';

// Get action from query parameter
$action = isset($_GET['action']) ? $_GET['action'] : null;

try {
    if (!$action) {
        throw new Exception('No action specified');
    }

    // Handle image upload
    if ($action === 'upload_image') {
        handleImageUpload();
        return;
    }

    // Category operations
    if ($action === 'create_category') {
        createCategory();
    } elseif ($action === 'get_categories') {
        getCategories();
    } elseif ($action === 'get_category') {
        getCategory();
    } elseif ($action === 'update_category') {
        updateCategory();
    } elseif ($action === 'delete_category') {
        deleteCategory();
    }
    // Photo operations
    elseif ($action === 'create_photo') {
        createPhoto();
    } elseif ($action === 'get_photos') {
        getPhotos();
    } elseif ($action === 'get_photo') {
        getPhoto();
    } elseif ($action === 'update_photo') {
        updatePhoto();
    } elseif ($action === 'delete_photo') {
        deletePhoto();
    }
    // Public client-side endpoints
    elseif ($action === 'get_all') {
        getAllPhotosForClient();
    } elseif ($action === 'get_filters') {
        getAllCategoriesForClient();
    } else {
        throw new Exception('Invalid action');
    }

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

// ==================== FUNCTIONS ====================

// Create category
function createCategory() {
    global $conn;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (empty($data['name'])) {
        throw new Exception('Category name is required');
    }

    $name = htmlspecialchars($data['name']);
    $description = isset($data['description']) ? htmlspecialchars($data['description']) : '';

    $query = "INSERT INTO gallery_categories (name, description, created_at) 
              VALUES (?, ?, NOW())";
    $stmt = $conn->prepare($query);
    
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('ss', $name, $description);
    
    if ($stmt->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'Category created successfully',
            'data' => [
                'id' => $stmt->insert_id,
                'name' => $name,
                'description' => $description
            ]
        ]);
    } else {
        throw new Exception('Failed to create category: ' . $stmt->error);
    }
    
    $stmt->close();
}

// Get all categories
function getCategories() {
    global $conn;
    
    $query = "SELECT id, name, description, created_at FROM gallery_categories 
              ORDER BY created_at DESC";
    $result = $conn->query($query);
    
    if (!$result) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $categories = [];
    while ($row = $result->fetch_assoc()) {
        $categories[] = $row;
    }

    echo json_encode([
        'success' => true,
        'data' => $categories
    ]);
}

// Get single category
function getCategory() {
    global $conn;
    
    $id = isset($_GET['id']) ? intval($_GET['id']) : null;
    
    if (!$id) {
        throw new Exception('Category ID is required');
    }

    $query = "SELECT id, name, description FROM gallery_categories WHERE id = ?";
    $stmt = $conn->prepare($query);
    
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        throw new Exception('Category not found');
    }

    $category = $result->fetch_assoc();
    
    echo json_encode([
        'success' => true,
        'data' => $category
    ]);
    
    $stmt->close();
}

// Update category
function updateCategory() {
    global $conn;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (empty($data['id']) || empty($data['name'])) {
        throw new Exception('Category ID and name are required');
    }

    $id = intval($data['id']);
    $name = htmlspecialchars($data['name']);
    $description = isset($data['description']) ? htmlspecialchars($data['description']) : '';

    $query = "UPDATE gallery_categories SET name = ?, description = ?, updated_at = NOW() 
              WHERE id = ?";
    $stmt = $conn->prepare($query);
    
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('ssi', $name, $description, $id);
    
    if ($stmt->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'Category updated successfully'
        ]);
    } else {
        throw new Exception('Failed to update category: ' . $stmt->error);
    }
    
    $stmt->close();
}

// Delete category
function deleteCategory() {
    global $conn;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (empty($data['id'])) {
        throw new Exception('Category ID is required');
    }

    $id = intval($data['id']);

    $query = "DELETE FROM gallery_categories WHERE id = ?";
    $stmt = $conn->prepare($query);
    
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('i', $id);
    
    if ($stmt->execute()) {
        // Reset category_id to NULL for photos in this category
        $resetQuery = "UPDATE gallery_photos SET category_id = NULL WHERE category_id = ?";
        $resetStmt = $conn->prepare($resetQuery);
        if ($resetStmt) {
            $resetStmt->bind_param('i', $id);
            $resetStmt->execute();
            $resetStmt->close();
        }

        echo json_encode([
            'success' => true,
            'message' => 'Category deleted successfully'
        ]);
    } else {
        throw new Exception('Failed to delete category: ' . $stmt->error);
    }
    
    $stmt->close();
}

// Upload image
function handleImageUpload() {
    if (!isset($_FILES['image'])) {
        echo json_encode([
            'success' => false,
            'message' => 'No image file provided'
        ]);
        return;
    }

    $file = $_FILES['image'];
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    
    if (!in_array($file['type'], $allowed_types)) {
        echo json_encode([
            'success' => false,
            'message' => 'Invalid image format. Allowed: JPG, PNG, GIF, WebP'
        ]);
        return;
    }

    $max_size = 5 * 1024 * 1024; // 5MB
    if ($file['size'] > $max_size) {
        echo json_encode([
            'success' => false,
            'message' => 'Image size exceeds 5MB limit'
        ]);
        return;
    }

    // Create upload directory if it doesn't exist
    $upload_dir = '../assets/uploads/gallery/';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }

    // Generate unique filename
    $file_ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $file_name = 'gallery_' . time() . '_' . uniqid() . '.' . $file_ext;
    $file_path = $upload_dir . $file_name;

    if (move_uploaded_file($file['tmp_name'], $file_path)) {
        echo json_encode([
            'success' => true,
            'data' => [
                'path' => 'assets/uploads/gallery/' . $file_name,
                'name' => $file_name
            ]
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Failed to upload image'
        ]);
    }
}

// Create photo
function createPhoto() {
    global $conn;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (empty($data['name']) || empty($data['image_path'])) {
        throw new Exception('Photo name and image are required');
    }

    $name = htmlspecialchars($data['name']);
    $image_path = htmlspecialchars($data['image_path']);
    $category_id = !empty($data['category_id']) ? intval($data['category_id']) : null;

    $query = "INSERT INTO gallery_photos (category_id, name, image_path, created_at) 
              VALUES (?, ?, ?, NOW())";
    $stmt = $conn->prepare($query);
    
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('iss', $category_id, $name, $image_path);
    
    if ($stmt->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'Photo uploaded successfully',
            'data' => [
                'id' => $stmt->insert_id,
                'name' => $name,
                'image_path' => $image_path
            ]
        ]);
    } else {
        throw new Exception('Failed to upload photo: ' . $stmt->error);
    }
    
    $stmt->close();
}

// Get all photos
function getPhotos() {
    global $conn;
    
    $category_id = isset($_GET['category_id']) ? intval($_GET['category_id']) : null;

    if ($category_id) {
        $query = "SELECT p.id, p.name, p.image_path, p.category_id, c.name as category_name 
                  FROM gallery_photos p 
                  LEFT JOIN gallery_categories c ON p.category_id = c.id 
                  WHERE p.category_id = ? 
                  ORDER BY p.created_at DESC";
        $stmt = $conn->prepare($query);
        if (!$stmt) {
            throw new Exception('Database error: ' . $conn->error);
        }
        $stmt->bind_param('i', $category_id);
        $stmt->execute();
        $result = $stmt->get_result();
    } else {
        $query = "SELECT p.id, p.name, p.image_path, p.category_id, c.name as category_name 
                  FROM gallery_photos p 
                  LEFT JOIN gallery_categories c ON p.category_id = c.id 
                  ORDER BY p.created_at DESC";
        $result = $conn->query($query);
        if (!$result) {
            throw new Exception('Database error: ' . $conn->error);
        }
    }

    $photos = [];
    while ($row = $result->fetch_assoc()) {
        $photos[] = $row;
    }

    // Get all categories for the form dropdown
    $categories_query = "SELECT id, name FROM gallery_categories ORDER BY name ASC";
    $categories_result = $conn->query($categories_query);
    $categories = [];
    while ($row = $categories_result->fetch_assoc()) {
        $categories[] = $row;
    }

    echo json_encode([
        'success' => true,
        'data' => $photos,
        'categories' => $categories
    ]);

    if (isset($stmt)) {
        $stmt->close();
    }
}

// Get single photo
function getPhoto() {
    global $conn;
    
    $id = isset($_GET['id']) ? intval($_GET['id']) : null;
    
    if (!$id) {
        throw new Exception('Photo ID is required');
    }

    $query = "SELECT id, name, image_path, category_id FROM gallery_photos WHERE id = ?";
    $stmt = $conn->prepare($query);
    
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        throw new Exception('Photo not found');
    }

    $photo = $result->fetch_assoc();
    
    echo json_encode([
        'success' => true,
        'data' => $photo
    ]);
    
    $stmt->close();
}

// Update photo
function updatePhoto() {
    global $conn;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (empty($data['id']) || empty($data['name'])) {
        throw new Exception('Photo ID and name are required');
    }

    $id = intval($data['id']);
    $name = htmlspecialchars($data['name']);
    $category_id = !empty($data['category_id']) ? intval($data['category_id']) : null;
    $image_path = isset($data['image_path']) ? htmlspecialchars($data['image_path']) : null;

    if ($image_path) {
        $query = "UPDATE gallery_photos SET name = ?, category_id = ?, image_path = ?, updated_at = NOW() 
                  WHERE id = ?";
        $stmt = $conn->prepare($query);
        if (!$stmt) {
            throw new Exception('Database error: ' . $conn->error);
        }
        $stmt->bind_param('sisi', $name, $category_id, $image_path, $id);
    } else {
        $query = "UPDATE gallery_photos SET name = ?, category_id = ?, updated_at = NOW() 
                  WHERE id = ?";
        $stmt = $conn->prepare($query);
        if (!$stmt) {
            throw new Exception('Database error: ' . $conn->error);
        }
        $stmt->bind_param('sii', $name, $category_id, $id);
    }
    
    if ($stmt->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'Photo updated successfully'
        ]);
    } else {
        throw new Exception('Failed to update photo: ' . $stmt->error);
    }
    
    $stmt->close();
}

// Delete photo
function deletePhoto() {
    global $conn;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (empty($data['id'])) {
        throw new Exception('Photo ID is required');
    }

    $id = intval($data['id']);

    // Get photo to delete file
    $query = "SELECT image_path FROM gallery_photos WHERE id = ?";
    $stmt = $conn->prepare($query);
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $file_path = '../' . $row['image_path'];
        
        // Delete file from server
        if (file_exists($file_path)) {
            unlink($file_path);
        }
    }
    $stmt->close();

    // Delete from database
    $delete_query = "DELETE FROM gallery_photos WHERE id = ?";
    $delete_stmt = $conn->prepare($delete_query);
    
    if (!$delete_stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $delete_stmt->bind_param('i', $id);
    
    if ($delete_stmt->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'Photo deleted successfully'
        ]);
    } else {
        throw new Exception('Failed to delete photo: ' . $delete_stmt->error);
    }
    
    $delete_stmt->close();
}

// Get all photos for client-side gallery
function getAllPhotosForClient() {
    global $conn;
    
    $query = "SELECT p.id, p.name as title, p.image_path, c.name as category_name, c.id as category_id
              FROM gallery_photos p 
              LEFT JOIN gallery_categories c ON p.category_id = c.id 
              ORDER BY p.created_at DESC";
    $result = $conn->query($query);
    
    if (!$result) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $photos = [];
    while ($row = $result->fetch_assoc()) {
        // Create filter class from category
        $filter_category = !empty($row['category_id']) ? 'filter-cat-' . $row['category_id'] : 'filter-all';
        
        $photos[] = [
            'id' => $row['id'],
            'title' => $row['title'],
            'image_path' => $row['image_path'],
            'category_name' => $row['category_name'] ?: 'Uncategorized',
            'category_id' => $row['category_id'],
            'filter_category' => $filter_category,
            'display_order' => $row['id']
        ];
    }

    echo json_encode([
        'success' => true,
        'data' => $photos
    ]);
}

// Get all categories for client-side filters
function getAllCategoriesForClient() {
    global $conn;
    
    $query = "SELECT id, name FROM gallery_categories ORDER BY created_at ASC";
    $result = $conn->query($query);
    
    if (!$result) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $categories = [];
    while ($row = $result->fetch_assoc()) {
        $categories[] = [
            'id' => $row['id'],
            'filter_name' => $row['name'],
            'filter_key' => 'filter-cat-' . $row['id'],
            'filter_icon' => 'fas fa-image',
            'display_order' => $row['id']
        ];
    }

    echo json_encode([
        'success' => true,
        'data' => $categories
    ]);
}

?>
