<?php
session_start();
require_once '../config/database.php';

// Check if user is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

header('Content-Type: application/json');

$action = $_POST['action'] ?? '';
$categoryTable = $tables['categories']; // Get table name from config

try {
    switch ($action) {
        case 'add_category':
            $categoryName = trim($_POST['category_name'] ?? '');
            
            if (empty($categoryName)) {
                echo json_encode(['success' => false, 'message' => 'Category name is required']);
                break;
            }
            
            // Check if category already exists
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM {$categoryTable} WHERE Category = ?");
            $stmt->execute([$categoryName]);
            
            if ($stmt->fetchColumn() > 0) {
                echo json_encode(['success' => false, 'message' => 'Category already exists']);
                break;
            }
            
            // Insert new category
            $stmt = $pdo->prepare("INSERT INTO {$categoryTable} (Category, SubCategory) VALUES (?, '')");
            $stmt->execute([$categoryName]);
            
            echo json_encode(['success' => true, 'message' => 'Category added successfully']);
            break;
            
        case 'edit_category':
            $categoryName = trim($_POST['category_name'] ?? '');
            $originalCategory = trim($_POST['original_category'] ?? '');
            
            if (empty($categoryName) || empty($originalCategory)) {
                echo json_encode(['success' => false, 'message' => 'Category name is required']);
                break;
            }
            
            // Check if new category name already exists (excluding current category)
            if ($categoryName !== $originalCategory) {
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM {$categoryTable} WHERE Category = ?");
                $stmt->execute([$categoryName]);
                
                if ($stmt->fetchColumn() > 0) {
                    echo json_encode(['success' => false, 'message' => 'Category name already exists']);
                    break;
                }
            }
            
            // Update category name
            $stmt = $pdo->prepare("UPDATE {$categoryTable} SET Category = ? WHERE Category = ?");
            $stmt->execute([$categoryName, $originalCategory]);
            
            echo json_encode(['success' => true, 'message' => 'Category updated successfully']);
            break;
            
        case 'delete_category':
            $categoryName = trim($_POST['category_name'] ?? '');
            
            if (empty($categoryName)) {
                echo json_encode(['success' => false, 'message' => 'Category name is required']);
                break;
            }
            
            // Delete all entries for this category
            $stmt = $pdo->prepare("DELETE FROM {$categoryTable} WHERE Category = ?");
            $stmt->execute([$categoryName]);
            
            $deletedRows = $stmt->rowCount();
            
            if ($deletedRows > 0) {
                echo json_encode(['success' => true, 'message' => "Category and {$deletedRows} associated entries deleted successfully"]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Category not found']);
            }
            break;
            
        case 'add_subcategory':
            $parentCategory = trim($_POST['parent_category'] ?? '');
            $subcategoryName = trim($_POST['subcategory_name'] ?? '');
            
            if (empty($parentCategory) || empty($subcategoryName)) {
                echo json_encode(['success' => false, 'message' => 'Both category and subcategory names are required']);
                break;
            }
            
            // Check if subcategory already exists in this category
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM {$categoryTable} WHERE Category = ? AND SubCategory = ?");
            $stmt->execute([$parentCategory, $subcategoryName]);
            
            if ($stmt->fetchColumn() > 0) {
                echo json_encode(['success' => false, 'message' => 'Subcategory already exists in this category']);
                break;
            }
            
            // Insert new subcategory
            $stmt = $pdo->prepare("INSERT INTO {$categoryTable} (Category, SubCategory) VALUES (?, ?)");
            $stmt->execute([$parentCategory, $subcategoryName]);
            
            echo json_encode(['success' => true, 'message' => 'Subcategory added successfully']);
            break;
            
        case 'edit_subcategory':
            $subcategoryId = $_POST['subcategory_id'] ?? '';
            $parentCategory = trim($_POST['parent_category'] ?? '');
            $subcategoryName = trim($_POST['subcategory_name'] ?? '');
            
            if (empty($subcategoryId) || empty($parentCategory) || empty($subcategoryName)) {
                echo json_encode(['success' => false, 'message' => 'All fields are required']);
                break;
            }
            
            // Get current subcategory info
            $stmt = $pdo->prepare("SELECT Category, SubCategory FROM {$categoryTable} WHERE ID = ?");
            $stmt->execute([$subcategoryId]);
            $current = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$current) {
                echo json_encode(['success' => false, 'message' => 'Subcategory not found']);
                break;
            }
            
            // Check if new combination already exists (excluding current record)
            if ($parentCategory !== $current['Category'] || $subcategoryName !== $current['SubCategory']) {
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM {$categoryTable} WHERE Category = ? AND SubCategory = ? AND ID != ?");
                $stmt->execute([$parentCategory, $subcategoryName, $subcategoryId]);
                
                if ($stmt->fetchColumn() > 0) {
                    echo json_encode(['success' => false, 'message' => 'This subcategory already exists in the selected category']);
                    break;
                }
            }
            
            // Update subcategory
            $stmt = $pdo->prepare("UPDATE {$categoryTable} SET Category = ?, SubCategory = ? WHERE ID = ?");
            $stmt->execute([$parentCategory, $subcategoryName, $subcategoryId]);
            
            echo json_encode(['success' => true, 'message' => 'Subcategory updated successfully']);
            break;
            
        case 'delete_subcategory':
            $subcategoryId = $_POST['subcategory_id'] ?? '';
            
            if (empty($subcategoryId)) {
                echo json_encode(['success' => false, 'message' => 'Subcategory ID is required']);
                break;
            }
            
            // Delete subcategory
            $stmt = $pdo->prepare("DELETE FROM {$categoryTable} WHERE ID = ?");
            $stmt->execute([$subcategoryId]);
            
            if ($stmt->rowCount() > 0) {
                echo json_encode(['success' => true, 'message' => 'Subcategory deleted successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Subcategory not found']);
            }
            break;
            
        case 'preview_bulk':
            $parentCategory = trim($_POST['parent_category'] ?? '');
            $subcategoriesJson = $_POST['subcategories'] ?? '';
            
            if (empty($parentCategory) || empty($subcategoriesJson)) {
                echo json_encode(['success' => false, 'message' => 'Category and subcategories are required']);
                break;
            }
            
            $subcategories = json_decode($subcategoriesJson, true);
            if (!is_array($subcategories)) {
                echo json_encode(['success' => false, 'message' => 'Invalid subcategories format']);
                break;
            }
            
            // Get existing subcategories for this category
            $stmt = $pdo->prepare("SELECT SubCategory FROM {$categoryTable} WHERE Category = ? AND SubCategory != '' AND SubCategory IS NOT NULL");
            $stmt->execute([$parentCategory]);
            $existingSubcategories = array_column($stmt->fetchAll(PDO::FETCH_ASSOC), 'SubCategory');
            $existingSubcategoriesLower = array_map('strtolower', $existingSubcategories);
            
            $valid = [];
            $duplicates = [];
            $invalid = [];
            
            foreach ($subcategories as $subcategory) {
                $subcategory = trim($subcategory);
                
                // Check if empty or too short
                if (empty($subcategory) || strlen($subcategory) < 2) {
                    if (!empty($subcategory)) {
                        $invalid[] = $subcategory;
                    }
                    continue;
                }
                
                // Check if duplicate (case insensitive)
                if (in_array(strtolower($subcategory), $existingSubcategoriesLower)) {
                    $duplicates[] = $subcategory;
                    continue;
                }
                
                // Check if already in valid array (avoid duplicates in input)
                $validLower = array_map('strtolower', $valid);
                if (in_array(strtolower($subcategory), $validLower)) {
                    $duplicates[] = $subcategory;
                    continue;
                }
                
                $valid[] = $subcategory;
            }
            
            echo json_encode([
                'success' => true,
                'preview' => [
                    'total' => count($subcategories),
                    'valid' => $valid,
                    'duplicates' => $duplicates,
                    'invalid' => $invalid
                ]
            ]);
            break;
            
        case 'bulk_add_subcategories':
            $parentCategory = trim($_POST['parent_category'] ?? '');
            $subcategoriesJson = $_POST['subcategories'] ?? '';
            
            if (empty($parentCategory) || empty($subcategoriesJson)) {
                echo json_encode(['success' => false, 'message' => 'Category and subcategories are required']);
                break;
            }
            
            $subcategories = json_decode($subcategoriesJson, true);
            if (!is_array($subcategories)) {
                echo json_encode(['success' => false, 'message' => 'Invalid subcategories format']);
                break;
            }
            
            // Get existing subcategories for this category
            $stmt = $pdo->prepare("SELECT SubCategory FROM {$categoryTable} WHERE Category = ? AND SubCategory != '' AND SubCategory IS NOT NULL");
            $stmt->execute([$parentCategory]);
            $existingSubcategories = array_column($stmt->fetchAll(PDO::FETCH_ASSOC), 'SubCategory');
            $existingSubcategoriesLower = array_map('strtolower', $existingSubcategories);
            
            $addedCount = 0;
            $skippedCount = 0;
            $validSubcategories = [];
            
            foreach ($subcategories as $subcategory) {
                $subcategory = trim($subcategory);
                
                // Skip empty or too short
                if (empty($subcategory) || strlen($subcategory) < 2) {
                    $skippedCount++;
                    continue;
                }
                
                // Skip duplicates (case insensitive)
                if (in_array(strtolower($subcategory), $existingSubcategoriesLower)) {
                    $skippedCount++;
                    continue;
                }
                
                // Skip if already in valid array (avoid duplicates in input)
                $validLower = array_map('strtolower', $validSubcategories);
                if (in_array(strtolower($subcategory), $validLower)) {
                    $skippedCount++;
                    continue;
                }
                
                $validSubcategories[] = $subcategory;
            }
            
            // Insert valid subcategories
            if (!empty($validSubcategories)) {
                $stmt = $pdo->prepare("INSERT INTO {$categoryTable} (Category, SubCategory) VALUES (?, ?)");
                
                foreach ($validSubcategories as $subcategory) {
                    try {
                        $stmt->execute([$parentCategory, $subcategory]);
                        $addedCount++;
                        // Add to existing array to prevent duplicates in same batch
                        $existingSubcategoriesLower[] = strtolower($subcategory);
                    } catch (Exception $e) {
                        $skippedCount++;
                    }
                }
            }
            
            $message = "Bulk add completed. Added: {$addedCount} subcategories";
            if ($skippedCount > 0) {
                $message .= ", Skipped: {$skippedCount} items";
            }
            
            echo json_encode(['success' => true, 'message' => $message, 'added' => $addedCount, 'skipped' => $skippedCount]);
            break;
            
        case 'preview_bulk_categories':
            $categoriesJson = $_POST['categories'] ?? '';
            
            if (empty($categoriesJson)) {
                echo json_encode(['success' => false, 'message' => 'Categories are required']);
                break;
            }
            
            $categories = json_decode($categoriesJson, true);
            if (!is_array($categories)) {
                echo json_encode(['success' => false, 'message' => 'Invalid categories format']);
                break;
            }
            
            // Get existing categories
            $stmt = $pdo->prepare("SELECT DISTINCT Category FROM {$categoryTable} WHERE Category != '' AND Category IS NOT NULL");
            $stmt->execute();
            $existingCategories = array_column($stmt->fetchAll(PDO::FETCH_ASSOC), 'Category');
            $existingCategoriesLower = array_map('strtolower', $existingCategories);
            
            $valid = [];
            $duplicates = [];
            $invalid = [];
            
            foreach ($categories as $category) {
                $category = trim($category);
                
                // Check if empty or too short
                if (empty($category) || strlen($category) < 2) {
                    if (!empty($category)) {
                        $invalid[] = $category;
                    }
                    continue;
                }
                
                // Check if duplicate (case insensitive)
                if (in_array(strtolower($category), $existingCategoriesLower)) {
                    $duplicates[] = $category;
                    continue;
                }
                
                // Check if already in valid array (avoid duplicates in input)
                $validLower = array_map('strtolower', $valid);
                if (in_array(strtolower($category), $validLower)) {
                    $duplicates[] = $category;
                    continue;
                }
                
                $valid[] = $category;
            }
            
            echo json_encode([
                'success' => true,
                'preview' => [
                    'total' => count($categories),
                    'valid' => $valid,
                    'duplicates' => $duplicates,
                    'invalid' => $invalid
                ]
            ]);
            break;
            
        case 'bulk_add_categories':
            $categoriesJson = $_POST['categories'] ?? '';
            
            if (empty($categoriesJson)) {
                echo json_encode(['success' => false, 'message' => 'Categories are required']);
                break;
            }
            
            $categories = json_decode($categoriesJson, true);
            if (!is_array($categories)) {
                echo json_encode(['success' => false, 'message' => 'Invalid categories format']);
                break;
            }
            
            // Get existing categories
            $stmt = $pdo->prepare("SELECT DISTINCT Category FROM {$categoryTable} WHERE Category != '' AND Category IS NOT NULL");
            $stmt->execute();
            $existingCategories = array_column($stmt->fetchAll(PDO::FETCH_ASSOC), 'Category');
            $existingCategoriesLower = array_map('strtolower', $existingCategories);
            
            $addedCount = 0;
            $skippedCount = 0;
            $validCategories = [];
            
            foreach ($categories as $category) {
                $category = trim($category);
                
                // Skip empty or too short
                if (empty($category) || strlen($category) < 2) {
                    $skippedCount++;
                    continue;
                }
                
                // Skip duplicates (case insensitive)
                if (in_array(strtolower($category), $existingCategoriesLower)) {
                    $skippedCount++;
                    continue;
                }
                
                // Skip if already in valid array (avoid duplicates in input)
                $validLower = array_map('strtolower', $validCategories);
                if (in_array(strtolower($category), $validLower)) {
                    $skippedCount++;
                    continue;
                }
                
                $validCategories[] = $category;
            }
            
            // Insert valid categories
            if (!empty($validCategories)) {
                $stmt = $pdo->prepare("INSERT INTO {$categoryTable} (Category, SubCategory) VALUES (?, '')");
                
                foreach ($validCategories as $category) {
                    try {
                        $stmt->execute([$category]);
                        $addedCount++;
                        // Add to existing array to prevent duplicates in same batch
                        $existingCategoriesLower[] = strtolower($category);
                    } catch (Exception $e) {
                        $skippedCount++;
                    }
                }
            }
            
            $message = "Bulk add completed. Added: {$addedCount} categories";
            if ($skippedCount > 0) {
                $message .= ", Skipped: {$skippedCount} items";
            }
            
            echo json_encode(['success' => true, 'message' => $message, 'added' => $addedCount, 'skipped' => $skippedCount]);
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
            break;
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?> 