<?php

namespace Modules\PCP\Controllers;

use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Http\Response;
use Gestoreasy\Core\Tenant\ConnectionManager;
use PDO;

class RoutingController {
    public function list(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $pdo = ConnectionManager::forTenant();
            
            $page = max(1, (int)($req->query['page'] ?? 1));
            $per = min(100, max(1, (int)($req->query['per_page'] ?? 20)));
            $offset = ($page - 1) * $per;

            $where = ['tenant_id = ?'];
            $params = [$tenantId];

            if (!empty($req->query['product_id'])) {
                $where[] = 'product_id = ?';
                $params[] = $req->query['product_id'];
            }

            $whereSql = implode(' AND ', $where);

            $sql = "SELECT r.*, p.codigo as produto_codigo, p.nome as produto_nome
                    FROM production_routing r
                    INNER JOIN products p ON r.product_id = p.id
                    WHERE {$whereSql}
                    ORDER BY r.created_at DESC
                    LIMIT ? OFFSET ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute(array_merge($params, [$per, $offset]));
            $roteiros = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Total
            $countSql = "SELECT COUNT(*) FROM production_routing WHERE {$whereSql}";
            $countStmt = $pdo->prepare($countSql);
            $countStmt->execute($params);
            $total = (int)$countStmt->fetchColumn();

            return Response::json([
                'data' => $roteiros,
                'pagination' => [
                    'page' => $page,
                    'per_page' => $per,
                    'total' => $total,
                    'total_pages' => (int)ceil($total / $per)
                ]
            ]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }

    public function get(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $pdo = ConnectionManager::forTenant();
            $id = (int)($req->get('params')[0] ?? 0);

            $stmt = $pdo->prepare('
                SELECT r.*, p.codigo as produto_codigo, p.nome as produto_nome
                FROM production_routing r
                INNER JOIN products p ON r.product_id = p.id
                WHERE r.id = ? AND r.tenant_id = ?
            ');
            $stmt->execute([$id, $tenantId]);
            $roteiro = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$roteiro) {
                return new Response(404, ['error' => ['code' => 'not_found', 'message' => 'Roteiro não encontrado']]);
            }

            // Buscar operações
            $stmt = $pdo->prepare('
                SELECT * FROM routing_operations
                WHERE routing_id = ? AND tenant_id = ?
                ORDER BY sequencia ASC
            ');
            $stmt->execute([$id, $tenantId]);
            $roteiro['operacoes'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

            return Response::json(['data' => $roteiro]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }

    public function create(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $pdo = ConnectionManager::forTenant();
            $body = is_array($req->body) ? $req->body : [];

            $stmt = $pdo->prepare('
                INSERT INTO production_routing (
                    tenant_id, product_id, nome, descricao, versao,
                    tempo_setup_minutos, tempo_processamento_minutos
                ) VALUES (?, ?, ?, ?, ?, ?, ?)
            ');
            $stmt->execute([
                $tenantId,
                $body['product_id'],
                $body['nome'],
                $body['descricao'] ?? null,
                $body['versao'] ?? '1.0',
                $body['tempo_setup_minutos'] ?? 0,
                $body['tempo_processamento_minutos'] ?? 0,
            ]);

            $routingId = (int)$pdo->lastInsertId();

            // Adicionar operações se fornecidas
            if (!empty($body['operacoes']) && is_array($body['operacoes'])) {
                foreach ($body['operacoes'] as $operacao) {
                    $stmt = $pdo->prepare('
                        INSERT INTO routing_operations (
                            tenant_id, routing_id, nome, descricao, sequencia,
                            centro_trabalho_id, maquina_id,
                            tempo_setup_minutos, tempo_processamento_minutos,
                            operadores_necessarios
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ');
                    $stmt->execute([
                        $tenantId,
                        $routingId,
                        $operacao['nome'],
                        $operacao['descricao'] ?? null,
                        $operacao['sequencia'] ?? 1,
                        $operacao['centro_trabalho_id'] ?? null,
                        $operacao['maquina_id'] ?? null,
                        $operacao['tempo_setup_minutos'] ?? 0,
                        $operacao['tempo_processamento_minutos'] ?? 0,
                        $operacao['operadores_necessarios'] ?? 1,
                    ]);
                }
            }

            return Response::json(['data' => ['id' => $routingId]], 201);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }

    public function update(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $pdo = ConnectionManager::forTenant();
            $id = (int)($req->get('params')[0] ?? 0);
            $body = is_array($req->body) ? $req->body : [];

            $allowedFields = ['nome', 'descricao', 'tempo_setup_minutos', 'tempo_processamento_minutos', 'status'];
            $updates = [];
            $params = [];

            foreach ($allowedFields as $field) {
                if (isset($body[$field])) {
                    $updates[] = "{$field} = ?";
                    $params[] = $body[$field];
                }
            }

            if (empty($updates)) {
                return new Response(422, ['error' => ['code' => 'validation_error', 'message' => 'Nenhum campo para atualizar']]);
            }

            $params[] = $id;
            $params[] = $tenantId;

            $sql = 'UPDATE production_routing SET ' . implode(', ', $updates) . ' WHERE id = ? AND tenant_id = ?';
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);

            return Response::json(['data' => ['success' => true]]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }

    public function delete(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $pdo = ConnectionManager::forTenant();
            $id = (int)($req->get('params')[0] ?? 0);

            $stmt = $pdo->prepare('DELETE FROM production_routing WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$id, $tenantId]);

            if ($stmt->rowCount() === 0) {
                return new Response(404, ['error' => ['code' => 'not_found', 'message' => 'Roteiro não encontrado']]);
            }

            return Response::json(['data' => ['success' => true]]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }
}

