<?php

namespace Modules\Integracoes\Correios\Controllers;

use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Http\Response;
use Modules\Integracoes\Correios\Services\CorreiosAPIService;

class CorreiosController {
    public function calcularFrete(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $body = is_array($req->body) ? $req->body : [];

            $service = new CorreiosAPIService($tenantId);
            $resultados = $service->calcularFrete($body);

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

    public function rastrear(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $body = is_array($req->body) ? $req->body : [];
            $codigo = $body['codigo_rastreamento'] ?? '';

            if (empty($codigo)) {
                return new Response(422, ['error' => ['code' => 'validation_error', 'message' => 'codigo_rastreamento é obrigatório']]);
            }

            $service = new CorreiosAPIService($tenantId);
            $resultado = $service->rastrear($codigo);

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

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

            $service = new CorreiosAPIService($tenantId);
            $resultado = $service->gerarEtiqueta($body);

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

    public function listEtiquetas(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $pdo = \Gestoreasy\Core\Tenant\ConnectionManager::forTenant();
            
            $limit = (int)($req->query['limit'] ?? 50);
            $offset = (int)($req->query['offset'] ?? 0);
            $status = $req->query['status'] ?? null;
            
            $sql = '
                SELECT 
                    ce.*,
                    so.numero as sales_order_numero
                FROM correios_etiquetas ce
                LEFT JOIN sales_orders so ON so.id = ce.sales_order_id
                WHERE ce.tenant_id = ?
            ';
            
            $params = [$tenantId];
            
            if ($status) {
                $sql .= ' AND ce.status = ?';
                $params[] = $status;
            }
            
            $sql .= ' ORDER BY ce.created_at DESC LIMIT ? OFFSET ?';
            $params[] = $limit;
            $params[] = $offset;
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $etiquetas = $stmt->fetchAll(\PDO::FETCH_ASSOC);

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

    public function downloadPDF(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $etiquetaId = (int)($req->get('params')[0] ?? 0);
            
            if (!$etiquetaId) {
                return new Response(422, ['error' => ['code' => 'validation_error', 'message' => 'etiqueta_id é obrigatório']]);
            }

            $pdo = \Gestoreasy\Core\Tenant\ConnectionManager::forTenant();
            $stmt = $pdo->prepare('SELECT pdf_path, codigo_etiqueta FROM correios_etiquetas WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$etiquetaId, $tenantId]);
            $etiqueta = $stmt->fetch(\PDO::FETCH_ASSOC);

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

            if (empty($etiqueta['pdf_path']) || !file_exists($etiqueta['pdf_path'])) {
                return new Response(404, ['error' => ['code' => 'pdf_not_found', 'message' => 'PDF da etiqueta não encontrado']]);
            }

            // Retornar PDF
            header('Content-Type: application/pdf');
            header('Content-Disposition: attachment; filename="etiqueta_' . $etiqueta['codigo_etiqueta'] . '.pdf"');
            readfile($etiqueta['pdf_path']);
            exit;
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }
}

