<?php
/**
 * Simple Categories API
 * Methods: GET, POST, PUT, DELETE
 */

// Start session
session_start();

// Include database connection
require_once '../controlls/functions.php';

// Set response headers
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

/**
 * Send JSON response
 */
function sendResponse($success, $message, $data = null) {
    $response = array(
        'success' => (bool)$success,
        'message' => $message
    );
    
    if ($data !== null) {
        $response['data'] = $data;
    }
    
    echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit();
}

/**
 * Check if user is logged in
 */
function checkAuth() {
    if (!isset($_SESSION['user_login'])) {
        sendResponse(false, 'Authentication required');
    }
    return $_SESSION['user_login'];
}

/**
 * Generate slug from text
 */
function generateSlug($text) {
    $text = strtolower($text);
    $text = preg_replace('/[^a-z0-9-]/', '-', $text);
    $text = preg_replace('/-+/', '-', $text);
    return trim($text, '-');
}

// Get request method
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($method) {
        
        // ==================== GET - Retrieve Categories ====================
        case 'GET':
            if (isset($_GET['id'])) {
                // Get single category
                $category_id = intval($_GET['id']);
                
                $stmt = $conn->prepare("SELECT * FROM categories WHERE id = :id LIMIT 1");
                $stmt->bindParam(':id', $category_id, PDO::PARAM_INT);
                $stmt->execute();
                $category = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($category) {
                    sendResponse(true, 'Category retrieved successfully', $category);
                } else {
                    sendResponse(false, 'Category not found');
                }
                
            } else {
                // Get all categories
                $where = array();
                $params = array();
                
                // Filter by parent_id
                if (isset($_GET['parent_id'])) {
                    if ($_GET['parent_id'] === '0' || $_GET['parent_id'] === 'null') {
                        $where[] = "parent_id IS NULL";
                    } else {
                        $where[] = "parent_id = :parent_id";
                        $params[':parent_id'] = intval($_GET['parent_id']);
                    }
                }
                
                // Filter by status
                if (isset($_GET['status']) && !empty($_GET['status'])) {
                    $where[] = "status = :status";
                    $params[':status'] = $_GET['status'];
                }
                
                $where_sql = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';
                
                $sql = "SELECT * FROM categories $where_sql ORDER BY sort_order ASC, name ASC";
                $stmt = $conn->prepare($sql);
                foreach ($params as $key => $value) {
                    $stmt->bindValue($key, $value);
                }
                $stmt->execute();
                $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                sendResponse(true, 'Categories retrieved successfully', array(
                    'categories' => $categories,
                    'total' => count($categories)
                ));
            }
            break;
        
        // ==================== POST - Create Category ====================
        case 'POST':
            $user = checkAuth();
            
            // Get JSON data
            $json_input = file_get_contents('php://input');
            $input = json_decode($json_input, true);
            
            // Support form data as fallback
            if (empty($input)) {
                $input = $_POST;
            }
            
            // Validate required fields
            if (!isset($input['name']) || empty($input['name'])) {
                sendResponse(false, 'Category name is required');
            }
            
            // Generate slug
            $slug = generateSlug($input['name']);
            
            // Check if slug already exists
            $check_slug = $conn->prepare("SELECT id FROM categories WHERE slug = :slug");
            $check_slug->execute([':slug' => $slug]);
            if ($check_slug->rowCount() > 0) {
                // Add random number to slug
                $slug .= '-' . rand(100, 999);
            }
            
            // Insert category
            $sql = "INSERT INTO categories (
                name, slug, description, parent_id, icon, color, sort_order, status
            ) VALUES (
                :name, :slug, :description, :parent_id, :icon, :color, :sort_order, :status
            )";
            
            $stmt = $conn->prepare($sql);
            
            $stmt->bindValue(':name', $input['name']);
            $stmt->bindValue(':slug', $slug);
            $stmt->bindValue(':description', isset($input['description']) ? $input['description'] : '');
            $stmt->bindValue(':parent_id', isset($input['parent_id']) ? $input['parent_id'] : null);
            $stmt->bindValue(':icon', isset($input['icon']) ? $input['icon'] : '');
            $stmt->bindValue(':color', isset($input['color']) ? $input['color'] : '');
            $stmt->bindValue(':sort_order', isset($input['sort_order']) ? $input['sort_order'] : 0);
            $stmt->bindValue(':status', isset($input['status']) ? $input['status'] : 'active');
            
            if ($stmt->execute()) {
                $category_id = $conn->lastInsertId();
                sendResponse(true, 'Category created successfully', array('category_id' => $category_id));
            } else {
                sendResponse(false, 'Failed to create category');
            }
            break;
        
        // ==================== PUT - Update Category ====================
        case 'PUT':
            $user = checkAuth();
            
            if (!isset($_GET['id'])) {
                sendResponse(false, 'Category ID is required');
            }
            
            $category_id = intval($_GET['id']);
            
            // Check if category exists
            $check = $conn->prepare("SELECT id FROM categories WHERE id = :id");
            $check->execute([':id' => $category_id]);
            
            if ($check->rowCount() === 0) {
                sendResponse(false, 'Category not found');
            }
            
            // Get JSON data
            $json_input = file_get_contents('php://input');
            $input = json_decode($json_input, true);
            
            // Build update query dynamically
            $update_fields = array();
            $params = array(':id' => $category_id);
            
            $allowed_fields = array('name', 'description', 'parent_id', 'icon', 'color', 'sort_order', 'status');
            
            foreach ($allowed_fields as $field) {
                if (isset($input[$field])) {
                    $update_fields[] = "$field = :$field";
                    $params[":$field"] = $input[$field];
                }
            }
            
            // Update slug if name changed
            if (isset($input['name'])) {
                $slug = generateSlug($input['name']);
                
                // Check if slug exists (excluding current category)
                $check_slug = $conn->prepare("SELECT id FROM categories WHERE slug = :slug AND id != :id");
                $check_slug->execute([':slug' => $slug, ':id' => $category_id]);
                if ($check_slug->rowCount() > 0) {
                    $slug .= '-' . rand(100, 999);
                }
                
                $update_fields[] = "slug = :slug";
                $params[':slug'] = $slug;
            }
            
            if (empty($update_fields)) {
                sendResponse(false, 'No fields to update');
            }
            
            $sql = "UPDATE categories SET " . implode(', ', $update_fields) . " WHERE id = :id";
            $stmt = $conn->prepare($sql);
            
            foreach ($params as $key => $value) {
                $stmt->bindValue($key, $value);
            }
            
            if ($stmt->execute()) {
                sendResponse(true, 'Category updated successfully', array('category_id' => $category_id));
            } else {
                sendResponse(false, 'Failed to update category');
            }
            break;
        
        // ==================== DELETE - Delete Category ====================
        case 'DELETE':
            $user = checkAuth();
            
            if (!isset($_GET['id'])) {
                sendResponse(false, 'Category ID is required');
            }
            
            $category_id = intval($_GET['id']);
            
            // Check if category has subcategories
            $check_sub = $conn->prepare("SELECT COUNT(*) as count FROM categories WHERE parent_id = :id");
            $check_sub->execute([':id' => $category_id]);
            $sub_count = $check_sub->fetch(PDO::FETCH_ASSOC)['count'];
            
            if ($sub_count > 0) {
                sendResponse(false, 'Cannot delete category with subcategories');
            }
            
            // Check if category has products
            $check_cat = $conn->prepare("SELECT slug FROM categories WHERE id = :id");
            $check_cat->execute([':id' => $category_id]);
            $category = $check_cat->fetch(PDO::FETCH_ASSOC);
            
            if ($category) {
                $check_products = $conn->prepare("SELECT COUNT(*) as count FROM products WHERE category = :slug");
                $check_products->execute([':slug' => $category['slug']]);
                $prod_count = $check_products->fetch(PDO::FETCH_ASSOC)['count'];
                
                if ($prod_count > 0) {
                    sendResponse(false, 'Cannot delete category with products');
                }
            }
            
            // Delete category
            $stmt = $conn->prepare("DELETE FROM categories WHERE id = :id");
            $stmt->execute([':id' => $category_id]);
            
            if ($stmt->rowCount() > 0) {
                sendResponse(true, 'Category deleted successfully');
            } else {
                sendResponse(false, 'Category not found');
            }
            break;
        
        default:
            sendResponse(false, 'Method not allowed');
            break;
    }
    
} catch (PDOException $e) {
    sendResponse(false, 'Database error: ' . $e->getMessage());
} catch (Exception $e) {
    sendResponse(false, 'Server error: ' . $e->getMessage());
}