<?php

namespace App\Controllers;

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

class KitchenController extends Controller
{
    public function index()
    {
        $this->checkPermission();
        $this->view('kitchen.index');
    }

    public function getOrders()
    {
        $this->checkPermission(true);
        $db = Database::getInstance()->getConnection();
        // Pegar pedidos pendentes ou em preparo
        $stmt = $db->query("SELECT * FROM orders WHERE status IN ('pending', 'preparing') ORDER BY created_at ASC");
        $orders = $stmt->fetchAll();

        // Pegar itens para cada pedido
        foreach ($orders as &$order) {
            $stmtItems = $db->prepare("SELECT * FROM order_items WHERE order_id = ?");
            $stmtItems->execute([$order['id']]);
            $order['items'] = $stmtItems->fetchAll();
        }

        $this->json($orders);
    }

    public function updateStatus()
    {
        $this->checkPermission(true);
        $id = $_POST['id'];
        $status = $_POST['status'];

        $db = Database::getInstance()->getConnection();
        $stmt = $db->prepare("UPDATE orders SET status = ? WHERE id = ?");
        $stmt->execute([$status, $id]);

        $stmtOrder = $db->prepare("SELECT * FROM orders WHERE id = ?");
        $stmtOrder->execute([$id]);
        $order = $stmtOrder->fetch();

        $items = [];
        if ($order) {
            $stmtItems = $db->prepare("SELECT * FROM order_items WHERE order_id = ?");
            $stmtItems->execute([$id]);
            $items = $stmtItems->fetchAll();
        }

        $this->json([
            'success' => true,
            'order' => $order,
            'items' => $items,
        ]);
    }

    public function getProducts()
    {
        $this->checkPermission(true);
        $db = Database::getInstance()->getConnection();
        $products = $db->query("SELECT id, name, base_price FROM products WHERE is_active = 1 ORDER BY name ASC")->fetchAll();
        $this->json($products);
    }

    public function createPosOrder()
    {
        $this->checkPermission(true);
        $input = json_decode(file_get_contents('php://input'), true);
        
        $customerName = $input['customer_name'] ?? 'Cliente Balcão';
        $paymentMethod = $input['payment_method'] ?? 'dinheiro';
        $items = $input['items'] ?? [];
        $total = $input['total'] ?? 0;

        if (empty($items)) {
            $this->json(['success' => false, 'message' => 'Sem itens']);
            return;
        }

        $db = Database::getInstance()->getConnection();
        
        try {
            $db->beginTransaction();
            
            $stmt = $db->prepare("INSERT INTO orders (customer_name, customer_phone, customer_address, total_amount, payment_method, status) VALUES (?, '', '', ?, ?, 'pending')");
            $stmt->execute([$customerName, $total, $paymentMethod]);
            $orderId = $db->lastInsertId();

            $stmtItem = $db->prepare("INSERT INTO order_items (order_id, product_name, quantity, unit_price, total_price, notes) VALUES (?, ?, ?, ?, ?, ?)");
            
            foreach ($items as $item) {
                $stmtItem->execute([
                    $orderId,
                    $item['name'],
                    $item['quantity'],
                    $item['price'],
                    $item['total'],
                    $item['notes'] ?? ''
                ]);
            }

            $db->commit();
            $this->json(['success' => true]);

        } catch (\Exception $e) {
            $db->rollBack();
            $this->json(['success' => false, 'message' => $e->getMessage()]);
        }
    }
}
