<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;

class AdminMenuController extends Controller
{
    public function index()
    {
        $this->checkPermission();
        $db = Database::getInstance()->getConnection();
        $products = $db->query("SELECT p.*, c.name as category_name FROM products p LEFT JOIN categories c ON p.category_id = c.id ORDER BY p.category_id, p.name")->fetchAll();
        
        $this->view('admin.menu_config', ['products' => $products]);
    }

    public function create()
    {
        $this->checkPermission('menu');
        $db = Database::getInstance()->getConnection();
        $products = $db->query("SELECT p.*, c.name as category_name FROM products p LEFT JOIN categories c ON p.category_id = c.id ORDER BY p.category_id, p.name")->fetchAll();
        $categories = $db->query("SELECT * FROM categories ORDER BY sort_order, name")->fetchAll();

        $this->view('admin.menu_config', [
            'products' => $products,
            'categories' => $categories,
            'formMode' => 'create',
        ]);
    }

    public function store()
    {
        $this->checkPermission('menu');
        $db = Database::getInstance()->getConnection();

        $name = trim($_POST['name'] ?? '');
        $categoryId = !empty($_POST['category_id']) ? (int) $_POST['category_id'] : null;
        $description = $_POST['description'] ?? '';
        $basePriceInput = $_POST['base_price'] ?? '';
        $basePriceInput = str_replace(['R$', ' '], '', $basePriceInput);
        $basePriceInput = str_replace('.', '', $basePriceInput);
        $basePriceInput = str_replace(',', '.', $basePriceInput);
        $basePrice = (float) $basePriceInput;
        $isActive = isset($_POST['is_active']) ? 1 : 0;

        if ($name === '' || !$categoryId || $basePrice <= 0) {
            $this->redirect('/admin/cardapio/novo');
        }

        $slugBase = $this->slugify($name);
        $slug = $this->generateUniqueSlug($db, $slugBase);

        $imageUrl = null;
        if (!empty($_FILES['image']['name'] ?? null)) {
            $imageUrl = $this->handleImageUpload($_FILES['image']);
        }

        $stmt = $db->prepare("INSERT INTO products (category_id, name, slug, description, base_price, image_url, is_active) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$categoryId, $name, $slug, $description, $basePrice, $imageUrl, $isActive]);

        $this->redirect('/admin/cardapio');
    }

    public function edit($id)
    {
        $this->checkPermission();
        $db = Database::getInstance()->getConnection();

        $products = $db->query("SELECT p.*, c.name as category_name FROM products p LEFT JOIN categories c ON p.category_id = c.id ORDER BY p.category_id, p.name")->fetchAll();
        $categories = $db->query("SELECT * FROM categories ORDER BY sort_order, name")->fetchAll();

        $stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
        $stmt->execute([(int) $id]);
        $product = $stmt->fetch();

        if (!$product) {
            $this->redirect('/admin/cardapio');
        }

        $this->view('admin.menu_config', [
            'products' => $products,
            'categories' => $categories,
            'formMode' => 'edit',
            'product' => $product,
        ]);
    }

    public function update($id)
    {
        $this->checkPermission('menu');
        $db = Database::getInstance()->getConnection();

        $stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
        $stmt->execute([(int) $id]);
        $product = $stmt->fetch();

        if (!$product) {
            $this->redirect('/admin/cardapio');
        }

        $name = trim($_POST['name'] ?? '');
        $categoryId = !empty($_POST['category_id']) ? (int) $_POST['category_id'] : null;
        $description = $_POST['description'] ?? '';
        $basePriceInput = $_POST['base_price'] ?? '';
        $basePriceInput = str_replace(['R$', ' '], '', $basePriceInput);
        $basePriceInput = str_replace('.', '', $basePriceInput);
        $basePriceInput = str_replace(',', '.', $basePriceInput);
        $basePrice = (float) $basePriceInput;
        $isActive = isset($_POST['is_active']) ? 1 : 0;

        if ($name === '' || !$categoryId || $basePrice <= 0) {
            $this->redirect('/admin/cardapio/' . (int) $id . '/editar');
        }

        $slugBase = $this->slugify($name);
        $slug = $this->generateUniqueSlug($db, $slugBase, (int) $id);

        $imageUrl = $product['image_url'];
        if (!empty($_FILES['image']['name'] ?? null)) {
            $newImage = $this->handleImageUpload($_FILES['image']);
            if ($newImage) {
                $imageUrl = $newImage;
            }
        }

        $stmtUpdate = $db->prepare("UPDATE products SET category_id = ?, name = ?, slug = ?, description = ?, base_price = ?, image_url = ?, is_active = ? WHERE id = ?");
        $stmtUpdate->execute([$categoryId, $name, $slug, $description, $basePrice, $imageUrl, $isActive, (int) $id]);

        $this->redirect('/admin/cardapio');
    }

    public function delete($id)
    {
        $this->checkPermission('menu');
        $db = Database::getInstance()->getConnection();
        $id = (int) $id;

        $stmt = $db->prepare("DELETE FROM product_options WHERE product_id = ?");
        $stmt->execute([$id]);

        $stmt = $db->prepare("DELETE FROM product_ingredients WHERE product_id = ?");
        $stmt->execute([$id]);

        $stmt = $db->prepare("DELETE FROM products WHERE id = ?");
        $stmt->execute([$id]);

        $this->redirect('/admin/cardapio');
    }

    public function options($id)
    {
        $this->checkPermission('menu');
        $db = Database::getInstance()->getConnection();
        $id = (int) $id;

        $stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
        $stmt->execute([$id]);
        $product = $stmt->fetch();

        if (!$product) {
            $this->redirect('/admin/cardapio');
        }

        $stmtOptions = $db->prepare("SELECT * FROM product_options WHERE product_id = ? ORDER BY additional_price ASC, name ASC");
        $stmtOptions->execute([$id]);
        $options = $stmtOptions->fetchAll();

        $this->view('admin.product_addons', [
            'product' => $product,
            'options' => $options
        ]);
    }

    public function optionsStore($id)
    {
        $this->checkPermission();
        $db = Database::getInstance()->getConnection();
        $id = (int) $id;

        $name = trim($_POST['name'] ?? '');
        $priceInput = $_POST['price'] ?? '0';
        $priceInput = str_replace(['R$', ' '], '', $priceInput);
        $priceInput = str_replace('.', '', $priceInput);
        $priceInput = str_replace(',', '.', $priceInput);
        $price = (float) $priceInput;

        if ($name !== '') {
            $stmt = $db->prepare("INSERT INTO product_options (product_id, name, additional_price) VALUES (?, ?, ?)");
            $stmt->execute([$id, $name, $price]);
        }

        $this->redirect("/admin/cardapio/$id/adicionais");
    }

    public function optionsDelete($id, $optId)
    {
        $this->checkPermission();
        $db = Database::getInstance()->getConnection();
        
        $stmt = $db->prepare("DELETE FROM product_options WHERE id = ? AND product_id = ?");
        $stmt->execute([(int) $optId, (int) $id]);

        $this->redirect('/admin/cardapio/' . (int) $id . '/adicionais');
    }

    public function ingredients($id)
    {
        $this->checkPermission();
        $db = Database::getInstance()->getConnection();

        // Produto
        $stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
        $stmt->execute([(int) $id]);
        $product = $stmt->fetch();
        if (!$product) $this->redirect('/admin/cardapio');

        // Ingredientes Vinculados
        $stmt = $db->prepare("
            SELECT i.*, pi.quantity as required_quantity 
            FROM ingredients i 
            JOIN product_ingredients pi ON i.id = pi.ingredient_id 
            WHERE pi.product_id = ?
        ");
        $stmt->execute([(int) $id]);
        $linkedIngredients = $stmt->fetchAll();

        // Todos os Ingredientes
        $allIngredients = $db->query("SELECT * FROM ingredients ORDER BY name")->fetchAll();

        $this->view('admin.product_ingredients', [
            'product' => $product,
            'linkedIngredients' => $linkedIngredients,
            'allIngredients' => $allIngredients
        ]);
    }

    public function ingredientsStore($id)
    {
        $this->checkPermission();
        $db = Database::getInstance()->getConnection();

        $ingredientId = (int) $_POST['ingredient_id'];
        $quantity = (float) str_replace(',', '.', $_POST['quantity']);

        if ($ingredientId && $quantity > 0) {
            // Check se já existe
            $stmt = $db->prepare("SELECT * FROM product_ingredients WHERE product_id = ? AND ingredient_id = ?");
            $stmt->execute([(int) $id, $ingredientId]);
            if ($stmt->fetch()) {
                // Update
                $stmt = $db->prepare("UPDATE product_ingredients SET quantity = ? WHERE product_id = ? AND ingredient_id = ?");
                $stmt->execute([$quantity, (int) $id, $ingredientId]);
            } else {
                // Insert
                $stmt = $db->prepare("INSERT INTO product_ingredients (product_id, ingredient_id, quantity) VALUES (?, ?, ?)");
                $stmt->execute([(int) $id, $ingredientId, $quantity]);
            }
        }
        
        $this->redirect("/admin/cardapio/$id/ingredientes");
    }

    public function ingredientsDelete($id, $ingId)
    {
        $this->checkPermission();
        $db = Database::getInstance()->getConnection();
        
        $stmt = $db->prepare("DELETE FROM product_ingredients WHERE product_id = ? AND ingredient_id = ?");
        $stmt->execute([(int) $id, (int) $ingId]);

        $this->redirect("/admin/cardapio/$id/ingredientes");
    }

    private function slugify($text)
    {
        $text = iconv('UTF-8', 'ASCII//TRANSLIT', $text);
        $text = preg_replace('~[^\\pL\\d]+~u', '-', $text);
        $text = trim($text, '-');
        $text = strtolower($text);
        $text = preg_replace('~[^-a-z0-9]+~', '', $text);
        if ($text === '') {
            $text = 'produto';
        }
        return $text;
    }

    private function generateUniqueSlug($db, $baseSlug, $ignoreId = null)
    {
        $slug = $baseSlug;
        $i = 1;
        while (true) {
            if ($ignoreId) {
                $stmt = $db->prepare("SELECT id FROM products WHERE slug = ? AND id != ?");
                $stmt->execute([$slug, $ignoreId]);
            } else {
                $stmt = $db->prepare("SELECT id FROM products WHERE slug = ?");
                $stmt->execute([$slug]);
            }
            $existing = $stmt->fetch();
            if (!$existing) {
                return $slug;
            }
            $i++;
            $slug = $baseSlug . '-' . $i;
        }
    }

    private function handleImageUpload($file)
    {
        if (empty($file['tmp_name']) || ($file['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) {
            return null;
        }

        // Caminho absoluto para a pasta public/assets/img/products
        // Assumindo que este arquivo está em app/Controllers
        $uploadDir = dirname(__DIR__, 2) . '/public/assets/img/products';
        
        if (!is_dir($uploadDir)) {
            if (!mkdir($uploadDir, 0777, true)) {
                return null;
            }
        }

        $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        if (!in_array($extension, $allowed)) {
            return null;
        }

        $filename = uniqid('prod_', true) . '.' . $extension;
        $targetPath = $uploadDir . '/' . $filename;

        // Converter barras invertidas para normais para consistência
        $targetPath = str_replace('\\', '/', $targetPath);

        if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
            return null;
        }

        return 'assets/img/products/' . $filename;
    }
}
