<?php

namespace App\Controllers;

use App\Database;
use App\Models\Category;

class CategoryController
{
    // Renders the full layout for categories page load
    public static function index()
    {
        global $twig;
        echo $twig->render('layout.twig', ['active_page' => 'categories']);
    }

    // Show category with items (AJAX)
    public function showCategory($categoryId)
    {
        global $twig;
        try {
            $db = Database::getInstance();
            $category = Category::getById($db, $categoryId);
            if (!$category) {
                echo '<div class="alert alert-danger">Category not found</div>';
                return;
            }
            
            // Get items in this category
            $items = \App\Models\Item::getAllFiltered($db, '', $categoryId);
            
            echo $twig->render('partials/category_detail.twig', [
                'category' => $category,
                'items' => $items
            ]);
        } catch (Exception $e) {
            echo '<div class="alert alert-danger">Error loading category: ' . htmlspecialchars($e->getMessage()) . '</div>';
        }
    }



    // Get single category (JSON)
    public static function getCategory($id) {
        header('Content-Type: application/json');
        try {
            $db = Database::getInstance();
            $category = Category::getById($db, $id);
            if ($category) {
                echo json_encode($category);
            } else {
                http_response_code(404);
                global $translator;
                echo json_encode(['error' => $translator->trans('Category not found')]);
            }
        } catch (Exception $e) {
            error_log('Error in getCategory: ' . $e->getMessage());
            http_response_code(500);
            global $translator;
            echo json_encode(['error' => $translator->trans('Server error')]);
        }
    }

    // Returns JSON list of categories
    public static function listCategoriesJson() {
        header('Content-Type: application/json');
        try {
            $db = Database::getInstance();
            $categories = Category::getAll($db);
            echo json_encode($categories);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => $e->getMessage()]);
        }
    }

    // Returns the HTML content for the categories page (used by AJAX)
    public static function listCategories()
    {
        global $twig;
        try {
            $db = Database::getInstance();
            $categories = Category::getAll($db);

            // Render only the content block
            echo $twig->render('categories.twig', [
                'categories' => $categories,
            ]);
        } catch (\Exception $e) {
            http_response_code(500);
            error_log("Error fetching categories: " . $e->getMessage());
            echo "Error: " . $e->getMessage();
        }
    }

    // CRUD operations (returns JSON)
    public static function create() {
        header('Content-Type: application/json');
        try {
            $db = Database::getInstance();
            $data = $_POST;

            $name = trim($data['new_category_name'] ?? '');
            $parentId = !empty($data['parent_category_id']) ? (int)$data['parent_category_id'] : null;

            if (empty($name)) {
                http_response_code(400);
                global $translator;
                echo json_encode(['error' => $translator->trans('Category name is required')]);
                return;
            }

            $category = new Category($db, null, $name, $parentId);
            if ($category->save()) {
                echo json_encode(['success' => true, 'message' => 'Category added successfully', 'id' => $category->getId()]);
            } else {
                throw new Exception('Failed to save category');
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => $e->getMessage()]);
        }
    }

    public static function update($id) {
        header('Content-Type: application/json');
        try {
            $db = Database::getInstance();
            $data = json_decode(file_get_contents('php://input'), true) ?? $_POST;

            $existing = Category::getById($db, $id);
            if (!$existing) {
                http_response_code(404);
                global $translator;
                echo json_encode(['error' => $translator->trans('Category not found')]);
                return;
            }

            $name = trim($data['category_name'] ?? $existing['name']);
            $parentId = !empty($data['parent_category_id']) ? (int)$data['parent_category_id'] : null;

            if (empty($name)) {
                http_response_code(400);
                global $translator;
                echo json_encode(['error' => $translator->trans('Category name is required')]);
                return;
            }

            // Prevent circular references
            if ($parentId !== null) {
                if ($parentId == $id) {
                    http_response_code(400);
                    global $translator;
                    echo json_encode(['error' => $translator->trans('A category cannot be its own parent')]);
                    return;
                }
                $descendants = Category::getDescendantIds($db, $id);
                if (in_array($parentId, $descendants)) {
                    http_response_code(400);
                    global $translator;
                    echo json_encode(['error' => $translator->trans('Cannot set a descendant as parent (circular reference)')]);
                    return;
                }
            }

            $category = new Category($db, $id, $name, $parentId);
            if ($category->save()) {
                echo json_encode(['success' => true, 'message' => 'Category updated successfully']);
            } else {
                throw new Exception('Failed to update category');
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => $e->getMessage()]);
        }
    }

    public static function delete($id) {
        header('Content-Type: application/json');
        try {
            $db = Database::getInstance();
            if (Category::delete($db, $id)) {
                echo json_encode(['success' => true, 'message' => 'Category deleted successfully']);
            } else {
                http_response_code(404);
                global $translator;
                echo json_encode(['error' => $translator->trans('Category not found')]);
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => $e->getMessage()]);
        }
    }
}
