<?php
namespace Modules\Ecommerce\Controllers;

use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Http\Response;
use Gestoreasy\Core\Tenant\ConnectionManager;
use Gestoreasy\Core\Tenant\TenantContext;
use Gestoreasy\Core\Audit\AuditLogger;

class EcommercePedidosController {
    private function getTenantId(): string {
        return TenantContext::getTenantId();
    }

    public function list(Request $req): Response {
        $pdo = ConnectionManager::forTenant();
        $tenantId = $this->getTenantId();
        
        $page = (int)($req->get('page') ?? 1);
        $perPage = (int)($req->get('per_page') ?? 20);
        $offset = ($page - 1) * $perPage;
        $status = $req->get('status');
        
        $sql = 'SELECT * FROM ecommerce_pedidos WHERE tenant_id = ?';
        $params = [$tenantId];
        
        if ($status) {
            $sql .= ' AND status = ?';
            $params[] = $status;
        }
        
        $sql .= ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
        $params[] = $perPage;
        $params[] = $offset;
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $pedidos = $stmt->fetchAll();
        
        // Buscar itens de cada pedido
        foreach ($pedidos as &$pedido) {
            $stmt = $pdo->prepare('SELECT * FROM ecommerce_pedido_itens WHERE pedido_id = ?');
            $stmt->execute([$pedido['id']]);
            $pedido['itens'] = $stmt->fetchAll();
        }
        
        // Contar total
        $countSql = 'SELECT COUNT(*) as total FROM ecommerce_pedidos WHERE tenant_id = ?';
        $countParams = [$tenantId];
        if ($status) {
            $countSql .= ' AND status = ?';
            $countParams[] = $status;
        }
        $stmt = $pdo->prepare($countSql);
        $stmt->execute($countParams);
        $total = (int)$stmt->fetch()['total'];
        
        return Response::json([
            'data' => $pedidos,
            'page' => $page,
            'per_page' => $perPage,
            'total' => $total,
            'total_pages' => ceil($total / $perPage)
        ]);
    }

    public function getById(Request $req): Response {
        $pdo = ConnectionManager::forTenant();
        $tenantId = $this->getTenantId();
        $id = $req->get('params')[0] ?? null;
        
        if (!$id) {
            return new Response(422, ['error' => ['code' => 'invalid_id', 'message' => 'ID inválido']]);
        }
        
        $stmt = $pdo->prepare('SELECT * FROM ecommerce_pedidos WHERE id = ? AND tenant_id = ? LIMIT 1');
        $stmt->execute([$id, $tenantId]);
        $pedido = $stmt->fetch();
        
        if (!$pedido) {
            return new Response(404, ['error' => ['code' => 'not_found', 'message' => 'Pedido não encontrado']]);
        }
        
        $stmt = $pdo->prepare('SELECT * FROM ecommerce_pedido_itens WHERE pedido_id = ?');
        $stmt->execute([$id]);
        $pedido['itens'] = $stmt->fetchAll();
        
        return Response::json(['data' => $pedido]);
    }

    public function updateStatus(Request $req): Response {
        $pdo = ConnectionManager::forTenant();
        $tenantId = $this->getTenantId();
        $id = $req->get('params')[0] ?? null;
        $status = $req->body['status'] ?? null;
        
        if (!$id) {
            return new Response(422, ['error' => ['code' => 'invalid_id', 'message' => 'ID inválido']]);
        }
        
        $statuses = ['pendente', 'pago', 'processando', 'enviado', 'entregue', 'cancelado'];
        if (!in_array($status, $statuses)) {
            return new Response(422, ['error' => ['code' => 'invalid_status', 'message' => 'Status inválido']]);
        }
        
        try {
            $pdo->beginTransaction();
            
            // Atualizar status
            $stmt = $pdo->prepare('UPDATE ecommerce_pedidos SET status = ? WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$status, $id, $tenantId]);
            
            // Se status mudou para "pago", processar integrações
            if ($status === 'pago') {
                $integrationService = new \Modules\Ecommerce\Services\EcommerceIntegrationService();
                
                // Criar pedido de venda se ainda não existir
                $stmt = $pdo->prepare('SELECT sales_order_id FROM ecommerce_pedidos WHERE id = ? LIMIT 1');
                $stmt->execute([$id]);
                $pedido = $stmt->fetch();
                
                if (empty($pedido['sales_order_id'])) {
                    $integrationService->createSalesOrderFromEcommerce($id);
                }
                
                // Baixar estoque
                $integrationService->baixarEstoque($id, false);
                
                // Criar conta a receber
                $integrationService->createContaReceber($id);
            }
            
            $pdo->commit();
            
            AuditLogger::log('update', 'ecommerce_pedidos', $id, [
                'status' => $status,
                'action' => 'update_status'
            ]);
            
            return Response::json(['message' => 'Status do pedido atualizado']);
        } catch (\Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            error_log("[Ecommerce] Erro ao atualizar status: " . $e->getMessage());
            return new Response(500, ['error' => ['code' => 'update_failed', 'message' => 'Erro ao atualizar status']]);
        }
    }
}

