<?php

namespace App\Controller\Admin;

use App\Entity\Model\Customer;
use App\Entity\Model\Empresa;
use App\Entity\Model\Invoice;
use App\Entity\Model\Item;
use App\Entity\Model\ItemPago;
use App\Service\EmFactory;
use App\Util\RestApiFunciones;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Component\Pager\PaginatorInterface;
use Mobile_Detect;
use PDO;
use PDOException;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Contracts\Translation\TranslatorInterface;
 use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use App\Entity\Model\Modulo;
use App\Entity\Model\EmpresaModulo;


/**
 * @Route("/svadmin/cli")
 */
class AdminClientesController extends AbstractController
{
    
    
   

/**
 * @Route("/descargar-firma/{id}", name="admin_descargar_firma")
 */
public function descargarFirma($id, EmFactory $emFactory)
{
    $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');

    $em = $emFactory->getEm();

    /** @var Empresa $empresa */
    $empresa = $em->getRepository(Empresa::class)->find($id);

    if (!$empresa) {
        throw $this->createNotFoundException('Empresa no encontrada');
    }

    $ruc = trim($empresa->getRuc());
    $archivo = 'firma_' . $ruc . '.p12';

    if (!$archivo) {
        throw $this->createNotFoundException('No existe archivo de firma');
    }

    // ⚠️ Ruta base fuera del public_html
    $basePath = '/home/factdmby/documentos';

    // Construcción segura de ruta
    $filePath = $basePath . '/' . $ruc . '/' . $archivo;

    // Validación de existencia
    if (!is_file($filePath)) {
        throw $this->createNotFoundException('Archivo no encontrado en servidor');
    }

    try {
        $response = new BinaryFileResponse($filePath);

        $response->setContentDisposition(
            ResponseHeaderBag::DISPOSITION_ATTACHMENT,
            basename($archivo)
        );

        return $response;

    } catch (\Exception $e) {
        throw $this->createNotFoundException('Error al descargar archivo de firma');
    }
}




    protected $translator;

    /**
     * @Route("", name="admin_cli_index")
     *
     */
   public function indexAction(EmFactory $emFactory, Request $request, PaginatorInterface $paginator, TranslatorInterface $translator)
{
    $this->translator = $translator;
    $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
    $user = $this->getUser();

    $em = $emFactory->getEm();
    $conn = $em->getConnection();  // Obtener conexión directa

    $empresaRepo = $em->getRepository('App\Entity\Model\Empresa');
    $empresaRepo->setPaginator($paginator);

    $limit = 30;

    $formSearch = $this->createForm('App\Form\Admin\SearchEmpresasType', null, [
        'action' => $this->generateUrl('admin_cli_index'),
        'method' => 'GET',
    ]);

    $formSearch->handleRequest($request);
    if ($formSearch->isSubmitted() && $formSearch->isValid()) {
        $emisor = $empresaRepo->paginatedSearch($formSearch->getData(), $limit, $request->query->getInt('page', 1));
    } else {
        $emisor = $empresaRepo->paginatedSearch([], $limit, $request->query->getInt('page', 1));
    }

    $repo = $em->getRepository('App\Entity\Model\Comprobantes');

    $comprobantes = array();

    foreach ($emisor as $item) {
        $total = 0;
        $comprobante = array();
        $comprobante['emisor_id'] = $item->getId();
        $comprobante['razonsocial'] = $item->getRazonSocial();
        $comprobante['ruc'] = $item->getRuc();
        $comprobante['plan'] = $item->getPlan() === null ? '' : $item->getPlan();

        $comprobante['fcaduca'] =  $item->getFechaCaduca() === null ? '' : $item->getFechaCaduca()->format('d/M/Y');

        // Aquí haces consulta directa para obtener fecha_cadfirma
        $sql = 'SELECT fecha_cadfirma FROM empresa WHERE id = :id LIMIT 1';
        $stmt = $conn->prepare($sql);
        $stmt->execute(['id' => $item->getId()]);
        $fechaCadfirma = $stmt->fetchOne();

        if ($fechaCadfirma) {
            $fechaObj = new \DateTime($fechaCadfirma);
            $comprobante['fecha_cadfirma'] = $fechaObj->format('d/m/Y');
        } else {
            $comprobante['fecha_cadfirma'] = '';
        }

        // El resto de tu código para contar facturas, retenciones, etc
        $facturas = $repo->countInvoiceEmitidos($item->getId());
        if ($facturas) {
            $comprobante['facturas'] = $facturas;
            $total += $facturas;
        }

        $retenciones = $repo->countRetencionesEmitidos($item->getId());
        if ($retenciones) {
            $comprobante['retenciones'] = $retenciones;
            $total += $retenciones;
        }

        $liquidaciones = $repo->countLiquidacionEmitidos($item->getId());
        if ($liquidaciones) {
            $comprobante['liquidaciones'] = $liquidaciones;
            $total += $liquidaciones;
        }

        $ncreditos = $repo->countNcreditosEmitidos($item->getId());
        if ($ncreditos) {
            $comprobante['ncreditos'] = $ncreditos;
            $total += $ncreditos;
        }

        $guias = $repo->countGuiasEmitidos($item->getId());
        if ($guias) {
            $comprobante['guias'] = $guias;
            $total += $guias;
        }

        $comprobante['total'] = $total;

        $contratados = $item->getCmpContratados();

        $comprobante['contratado'] = $contratados;
        $disponible = $contratados - $total;

        $comprobante['estado'] = $disponible > 0 ? 'D' : 'A';  // D = DISPONIBLE, A = AGOTADO

        if ($item->getCmpContratados() > 0) {
            $comprobante['disponible'] = $disponible;
        } else {
            $comprobante['disponible'] = '';
            $comprobante['estado'] = '';
            $comprobante['contratado'] = '';
        }

        $comprobantes[] = $comprobante;
    }

    $em->flush();

    return $this->render('Admin\CLI\index.html.twig', [
        'invoices' => $comprobantes,
        'currency' => 'USD',
        'search_form' => $formSearch->createView(),
        'empresas' => $emisor
    ]);
}

    
    
    
   /**
 * @Route("/exportar/excel", name="admin_cli_exportar_excel")
 */
public function exportarExcel(EmFactory $emFactory)
{
    $em = $emFactory->getEm();
    $conn = $em->getConnection();

    // Consulta directa
    $sql = "SELECT razon_social, ruc, fecha_cadfirma, fecha_caduca, cmp_contratados AS contratado, telefono, email FROM empresa";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $results = $stmt->fetchAllAssociative();

    $today = new \DateTime();
    $filename = 'empresas_export_' . date('Ymd_His') . '.csv';

    $response = new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($results, $today) {
        $handle = fopen('php://output', 'w');

        // Cabecera
        fputcsv($handle, [
            'Razon Social',
            'RUC',
            'F. Caduca Firma',
            'Estado Firma',
            'F. Caduca Facturero',
            'Estado Facturero',
            'Contratado',
            'Telefono',
            'Correo'
        ]);

        foreach ($results as $row) {
            // Convertir fechas
            $estadoFirma = '';
            $estadoFact = '';

            $fechaFirma = !empty($row['fecha_cadfirma']) ? new \DateTime($row['fecha_cadfirma']) : null;
            $fechaFact = !empty($row['fecha_caduca']) ? new \DateTime($row['fecha_caduca']) : null;

            // Estado Firma
            if ($fechaFirma) {
                $diasFirma = (int)$today->diff($fechaFirma)->format('%r%a');
                if ($diasFirma > 30) {
                    $estadoFirma = 'VIGENTE';
                } elseif ($diasFirma > 0) {
                    $estadoFirma = 'POR CADUCAR';
                } else {
                    $estadoFirma = 'CADUCADO';
                }
            } else {
                $estadoFirma = 'SIN FECHA';
            }

            // Estado Facturero
            if ($fechaFact) {
                $diasFact = (int)$today->diff($fechaFact)->format('%r%a');
                if ($diasFact > 30) {
                    $estadoFact = 'VIGENTE';
                } elseif ($diasFact > 0) {
                    $estadoFact = 'POR CADUCAR';
                } else {
                    $estadoFact = 'CADUCADO';
                }
            } else {
                $estadoFact = 'SIN FECHA';
            }

            fputcsv($handle, [
                $row['razon_social'],
                $row['ruc'],
                $fechaFirma ? $fechaFirma->format('d/m/Y') : '',
                $estadoFirma,
                $fechaFact ? $fechaFact->format('d/m/Y') : '',
                $estadoFact,
                $row['contratado'],
                $row['telefono'],
                $row['email']
                
            ]);
        }

        fclose($handle);
    });

    $response->headers->set('Content-Type', 'text/csv; charset=utf-8');
    $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"');

    return $response;
}



    
    

    /**
     * @Route("/contri/", name="admin_contri_index")
     *
     */
    public function indexContribuyentesAction(EmFactory $emFactory, Request $request, PaginatorInterface $paginator, TranslatorInterface $translator)
    {
        $this->translator = $translator;
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $user = $this->getUser();

        $em = $emFactory->getEm();
        $empresaRepo = $em->getRepository('App\Entity\Model\Empresa');
        $empresaRepo->setPaginator($paginator);

        $limit = 50;
        $pageactual =1;

        if($request->query->has('page'))
            $pageactual = $request->query->getInt('page');

        $formSearch = $this->createForm('App\Form\Admin\SearchEmpresasType', null, [
            'action' => $this->generateUrl('admin_contri_index'),
            'method' => 'GET',
        ]);

        $formSearch->handleRequest($request);
        if ($formSearch->isSubmitted() && $formSearch->isValid()) {
            if ($request->isMethod('POST')) {
                $pageactual =$request->request->getInt('pageactual', 1);
                $empresas = $empresaRepo->paginatedSearch([], $limit, $pageactual);
            }
            else
                $empresas = $empresaRepo->paginatedSearch($formSearch->getData(), $limit, $request->query->getInt('page', 1));
        } else {
            if ($request->isMethod('POST')) {
                $pageactual =$request->request->getInt('pageactual', 1);
                $empresas = $empresaRepo->paginatedSearch([], $limit, $pageactual);
            }
            else
                $empresas = $empresaRepo->paginatedSearch([], $limit, $request->query->getInt('page', 1));
        }

        $invoices = [];
        foreach ($empresas->getItems() as $item) {
            //$item = new Empresa();
            $data = [];
            if(!$item->getRimpeLabel())
                $item->setRimpeLabel('CONTRIBUYENTE REGIMEN GENERAL');

            $data['id'] = $item->getId();
            $data['razonsocial'] = $item->getRazonSocial();
            $data['ruc'] = $item->getRuc();
            $data['rimpelabel'] = $item->getRimpeLabel();
            $data['actualizo'] = '';
            $data['anterior'] = '';
            $data['error'] = '';
            $invoices[$item->getId()] = $data;

        }

        if ($request->isMethod('POST')) {

            $error = false;
            $em = $emFactory->getEm();

            foreach ($invoices as $key => $item) {
                try {
                    $emisor = $em->getRepository(Empresa::class)->findOneBy(["id" => $item['id']]);
                    $invoices[$key]['anterior'] = $emisor->getRimpeLabel();
                    $invoices[$key]['actualizo'] = 'NO';
                    //$emisor = new Empresa();
                    $ruc = $emisor->getRuc();
                    $iniruc = substr($ruc,0,10);
                    $finruc = substr($ruc,10,3);

                    if ($finruc != '001' || $finruc !== '001')
                        $finruc = '001';

                    $rucdoc = $iniruc.$finruc;

                    if ($rucdoc) {
                        $url = $this->getParameter('api_portalsri');
                        $resp = RestApiFunciones::consultarContribuyente($error, $url, $rucdoc);
                        if ($error) {
                            $invoices[$key]['error'] = json_encode($resp);
                            $invoices[$key]['anterior']='';
                        } elseif ($resp) {
                            $obj = $resp->message[0];
                            $emisor->setLlevaContabilidad($obj->obligadoLlevarContabilidad === 'SI');
                            $emisor->setAgenteRet($obj->agenteRetencion === 'SI' ? '1' : '');
                            if($obj->contribuyenteEspecial === 'SI')
                                $emisor->setContribuyenteEspecial(trim($obj->contribuyenteEspecial));

                            $regimen = trim($obj->regimen);
                            $categoria = trim($obj->categoria);
                            $emisor->setRazonSocial(trim($obj->razonSocial));
                            if (trim($emisor->getTipoContribuyente()) != trim($obj->tipoContribuyente)) {
                                $emisor->setTipoContribuyente(trim($obj->tipoContribuyente));
                                $invoices[$key]['actualizo'] = 'SI';
                            }
                            if (trim($emisor->getRegimen()) != $regimen) {
                                $emisor->setRegimen($regimen);
                                $invoices[$key]['actualizo'] = 'SI';
                            }
                            if (trim($emisor->getCategoria()) != $categoria) {
                                $emisor->setCategoria($categoria);
                                $invoices[$key]['actualizo'] = 'SI';
                            }
                            if ($regimen === 'RIMPE' && $invoices[$key]['actualizo'] === 'SI') {
                                $emisor->setRimpe(true);
                                if ($categoria  === 'NEGOCIO POPULAR')
                                    $emisor->setRimpeLabel('CONTRIBUYENTE NEGOCIO POPULAR - RÉGIMEN RIMPE');
                                elseif ($categoria === 'EMPRENDEDOR')
                                    $emisor->setRimpeLabel('CONTRIBUYENTE RÉGIMEN RIMPE');

                            } elseif ($regimen === 'GENERAL') {
                                $emisor->setRimpeLabel('CONTRIBUYENTE RÉGIMEN GENERAL');
                            }

                            if($invoices[$key]['actualizo'] === 'SI')
                                $invoices[$key]['rimpelabel'] = $emisor->getRimpeLabel();
                            else
                                $invoices[$key]['anterior']='';

                            $em->persist($emisor);
                        } else {
                            $this->addTranslatedMessage($resp, 'danger');
                        }
                    }
                }
                catch(\Exception $ex){
                    $invoices[$key]['error'] = json_encode($ex->getMessage());
                    $invoices[$key]['anterior']='';
                }
            }
            $em->flush();
        }

        return $this->render('Admin\CONTRI\index.html.twig',
            array(
                'currency' => 'USD',
                'search_form' => $formSearch->createView(),
                'invoices' => $invoices,
                //'list_form' => $listForm->createView(),
                'empresas' => $empresas,
                'pageactual' => $pageactual,
            ));
    }

    /**
     * @Route("/show/{slug}cli{id}", name="admin_cliente_show")
     *
     */
    public function clienteShowAction($id, EmFactory $emFactory, $slug, TranslatorInterface $translator, Request $request, LoggerInterface $logger)
    {
        $this->logger = $logger;
        $this->translator = $translator;
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $user = $this->getUser();

        $emdefault = $this->getDoctrine()->getManager('default');
        $parambase = $emdefault->getConnection()->getParams();
        $em = $emFactory->getEm();
        $empresaRepo = $em->getRepository('App\Entity\Model\Empresa');
        $emisor = $empresaRepo->findOneById($id);

        $planori = 0;
        if($emisor->getPlan())
            $planori = $emisor->getPlan()->getId();

        if (!$emisor) {
            throw $this->createNotFoundException('Unable to find Emisor entity.');
        }

        if($emisor->getPlan())
            $emisor->setPlan($emisor->getPlan()->getId());

        $planesRepo = $em->getRepository('App\Entity\Model\Planes');
        $planes = $planesRepo->findAll();

        $plan = [];
        foreach ($planes as $item){
            $plan[strtoupper($item->getName())]=$item->getId() ;
        }

        //$form = $this->createForm(ClienteType::class, $emisor);

        $form = $this->createForm('App\Form\Admin\ClienteType', $emisor, [
            'planes' => $plan,
        ]);

        $form->handleRequest($request);

        if ($form->isSubmitted()) {
            // data is an array with "name", "email", and "message" keys
            //$data = $form->getData();
            //$emisor->setEnabled($data["enabled"] === null ? true : $data["enabled"]);

            $repo = $em->getRepository('App\Entity\Model\Planes');
            $plan = $repo->findById($emisor->getPlan());

            $emisor->setPlan($plan);

            if($planori > 0){
                if($planori !== $plan->getId())
                    $emisor->setCmpContratados(-1);
            }








// ==========================================
// ACTUALIZAR PASSWORD EN API FACTURAS
// ==========================================

$nuevaPassword = trim($request->request->get('nueva_password_api'));

if (!empty($nuevaPassword)) {

    try {

        $ruc = trim($emisor->getRuc());

        $connApi = new \PDO(
            "mysql:host=127.0.0.1;dbname=factdmby_api_erp;charset=utf8",
            "factdmby_dws",
            "SiervosICRF123*.*"
        );

        $connApi->setAttribute(
            \PDO::ATTR_ERRMODE,
            \PDO::ERRMODE_EXCEPTION
        );

        // HASH ARGON2ID
        $passwordHash = password_hash(
            $nuevaPassword,
            PASSWORD_ARGON2ID
        );

        // UPDATE
        $stmtPass = $connApi->prepare("
            UPDATE user
            SET password = :password
            WHERE ruc = :ruc
            LIMIT 1
        ");

        $stmtPass->execute([
            'password' => $passwordHash,
            'ruc'      => $ruc
        ]);

        $this->addFlash(
            'success',
            'Contraseña API actualizada correctamente'
        );

    } catch (\Exception $e) {

        die($e->getMessage());

    }
}







            $em->persist($emisor);
            $em->flush();
            $this->addTranslatedMessage('Registro Actualizado');

            $dbParams = $this->getDoctrine()->getConnection()->getParams();

            try {
                $conn = new PDO("mysql:host=" . $dbParams['host'] . ";dbname=".$parambase['dbname'].";charset=utf8", $dbParams['user'], $dbParams['password']);
                // set the PDO error mode to exception
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $enabled = $emisor->isEnabled() == true ? 1 : 0;
                $sql = "update user set enabled =" . $enabled . ", mensaje='" . $emisor->getMensaje() . "' where ruc='" . $emisor->getRuc()."'";
                $statement = $conn->prepare($sql);
                //$statement = $this->bindAllValues($statement, $data);

                $statement->execute();
            } catch (PDOException $exception) {
                exit($exception->getMessage());

            } finally {
                $conn = null;
                $statement = null;
            }
        }

        /*if (!$entity->isClosed()) {
            // When the invoice is open send to the edit form by default.
            return $this->redirect($this->generateUrl('invoice_edit', array('id' => $id)));
        }
        */
        
        
// 🔥 OBTENER USERNAME DESDE LA OTRA BD (api_facturas)
$usernameCliente = null;
$ruc = trim($emisor->getRuc());

try {

    $connApi = new \PDO(
        "mysql:host=127.0.0.1;dbname=factdmby_facturaselectronicas;charset=utf8",
        "factdmby_dws",
        "SiervosICRF123*.*"
    );

    $connApi->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

    if (!empty($ruc)) {

        $stmt = $connApi->prepare("
            SELECT username 
            FROM user 
            WHERE ruc = :ruc 
            ORDER BY id DESC 
            LIMIT 1
        ");

        $stmt->execute(['ruc' => $ruc]);
        $data = $stmt->fetch(\PDO::FETCH_ASSOC);

        if ($data && isset($data['username'])) {
            $usernameCliente = $data['username'];
        } else {
            $usernameCliente = 'NO ENCONTRADO';
        }

    } else {
        $usernameCliente = 'SIN RUC';
    }

} catch (\PDOException $e) {
    $usernameCliente = 'ERROR BD';
}




// ==========================================
// DATOS FIRMA ELECTRONICA
// ==========================================

$rutaFirma = null;
$passFirma = null;
$nombreFirma = null;

try {

    $connFirma = $em->getConnection();

    $sqlFirma = "
        SELECT ruta_firma, pass_firma
        FROM empresa
        WHERE id = :id
        LIMIT 1
    ";

    $stmtFirma = $connFirma->prepare($sqlFirma);
    $stmtFirma->execute([
        'id' => $emisor->getId()
    ]);

    $firmaData = $stmtFirma->fetchAssociative();

    if ($firmaData) {

        $rutaFirma = $firmaData['ruta_firma'];
        $passFirma = $firmaData['pass_firma'];

        if (!empty($rutaFirma)) {
            $nombreFirma = basename($rutaFirma);
        }
    }

} catch (\Exception $e) {

    $rutaFirma = null;
    $passFirma = null;

}






// ============================================================
// MODULOS DEL ERP
// ============================================================

$moduloRepository = $em->getRepository(Modulo::class);
$empresaModuloRepository = $em->getRepository(EmpresaModulo::class);

// Obtener solamente los módulos que están disponibles en el sistema
$modulosDisponibles = $moduloRepository->findBy(
    ['activo' => true],
    ['orden' => 'ASC']
);

// Obtener los módulos contratados/activados para esta empresa
$empresaModulos = $empresaModuloRepository->findBy([
    'empresa' => $emisor
]);

// Preparar la información para Twig
$modulos = [];

foreach ($modulosDisponibles as $modulo) {

    $activo = false;

    foreach ($empresaModulos as $empresaModulo) {

        if (
            $empresaModulo->getModulo()->getId() == $modulo->getId()
            && $empresaModulo->isActivo()
        ) {
            $activo = true;
            break;
        }
    }

    $modulos[] = [
        'modulo' => $modulo,
        'activo' => $activo,
    ];
}







      return $this->render('Admin\CLI\show.html.twig',
    array(
        'entity' => $emisor,
        'form' => $form->createView(),
        'currency' => $emisor == null ? 'USD' : $emisor->getCurrency(),
        'usernameCliente' => $usernameCliente, // 👈 IMPORTANTE
        'rutaFirma' => $rutaFirma,
        'passFirma' => $passFirma,
        'nombreFirma' => $nombreFirma,
        'modulos' => $modulos
    ));
    
    
    
    }
    
    
    
    
    /**
 * @Route("/modulos/{id}", name="admin_cliente_modulos", methods={"POST"})
 */
public function clienteModulosAction(
    $id,
    EmFactory $emFactory,
    Request $request
) {
    $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');

    $em = $emFactory->getEm();

    $empresaRepository = $em->getRepository(Empresa::class);

    $emisor = $empresaRepository->find($id);

    if (!$emisor) {
        throw $this->createNotFoundException('Empresa no encontrada.');
    }

    // Validar CSRF
    if (!$this->isCsrfTokenValid(
        'empresa_modulos_' . $id,
        $request->request->get('_token')
    )) {
        throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException(
            'Token CSRF inválido.'
        );
    }

    // Módulos disponibles en el sistema
    $moduloRepository = $em->getRepository(Modulo::class);

    $modulos = $moduloRepository->findBy(
        ['activo' => true],
        ['orden' => 'ASC']
    );

    // Módulos actualmente asignados a la empresa
    $empresaModuloRepository = $em->getRepository(EmpresaModulo::class);

    // Lo que llegó marcado desde el formulario
    $seleccionados = $request->request->get('modulos', []);

    if (!is_array($seleccionados)) {
        $seleccionados = [];
    }

    foreach ($modulos as $modulo) {

        $codigo = $modulo->getCodigo();

        $empresaModulo = $empresaModuloRepository->findOneBy([
            'empresa' => $emisor,
            'modulo' => $modulo,
        ]);

        $debeEstarActivo = isset($seleccionados[$codigo])
            && $seleccionados[$codigo] == '1';

        // ====================================================
        // ACTIVAR MODULO
        // ====================================================

        if ($debeEstarActivo) {

            if (!$empresaModulo) {

                // No existe todavía: se crea solamente al activar
                $empresaModulo = new EmpresaModulo();

                $empresaModulo->setEmpresa($emisor);
                $empresaModulo->setModulo($modulo);
                $empresaModulo->setActivo(true);
                $empresaModulo->setFechaActivacion(new \DateTime());
                $empresaModulo->setFechaDesactivacion(null);

                $em->persist($empresaModulo);

            } else {

                // Ya existe pero estaba desactivado
                if (!$empresaModulo->isActivo()) {
                    $empresaModulo->setFechaActivacion(new \DateTime());
                }

                $empresaModulo->setActivo(true);
                $empresaModulo->setFechaDesactivacion(null);
            }

        // ====================================================
        // DESACTIVAR MODULO
        // ====================================================

        } else {

            if ($empresaModulo && $empresaModulo->isActivo()) {

                $empresaModulo->setActivo(false);
                $empresaModulo->setFechaDesactivacion(new \DateTime());
            }
        }
    }

    $em->flush();

    $this->addFlash(
        'success',
        'Los módulos de la empresa fueron actualizados correctamente.'
    );

    return $this->redirectToRoute('admin_cliente_show', [
        'id' => $id,
        'slug' => $id,
    ]);
}




    /**
     * @Route("/show/{slug}inv{id}", name="admin_fa_show")
     *
     */
    public function showAction($id, EmFactory $emFactory, $slug, TranslatorInterface $translator, Request $request, LoggerInterface $logger)
    {
        $this->logger = $logger;
        $this->translator = $translator;
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $user = $this->getUser();

        $em = $emFactory->getEm();
        $empresaRepo = $em->getRepository('App\Entity\Model\Empresa');
        $emisor = $empresaRepo->findOneByUser($user->getRuc());

        $entity = $em->getRepository('App\Entity\Model\Invoice')->findBySlug($slug, $id);
        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Invoice entity.');
        }

        $defaultData = ['slug' => $slug, 'id'=>$id, 'customerEmail' => $entity->getCustomerEmail()];

        $form = $this->createFormBuilder($defaultData)
            ->add('slug', HiddenType::class)
            ->add('id', HiddenType::class)
            ->add('customerEmail')
            ->setAction($this->generateUrl('invoice_show', ['id' => $id, 'slug'=>$slug]))
            ->getForm();

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // data is an array with "name", "email", and "message" keys
            $data = $form->getData();

            if ($request->request->has('Form-pdf')) {
                $this->generarPdf($entity);
            } elseif ($request->request->has('Form-email')) {
                if (isset($data['customerEmail'])) {
                    $email = $data['customerEmail'];
                    $this->enviarMail($email, $entity);
                } else
                    $this->addTranslatedMessage('Email del cliente nulo o en blanco', 'warning');
            } elseif ($request->request->has('Form-edit')) {
                if ($entity->getAutorizado() === false)
                    return $this->redirect($this->generateUrl('invoice_edit', ['id' => $entity->getId(), 'slug' => $slug]));
            } elseif ($request->request->has('Form-delete')) {
                $error = $this->delete($entity);
                if ($error)
                    return $this->redirect($this->generateUrl('invoice_index'));
            } elseif ($request->request->has('Form-anular')) {
                $entity->setAnulado(true);
                $em->persist($entity);
                $em->flush();
            } elseif ($request->request->has('Form-enviar')) {
                $this->enviarSriOnline($entity);
            } elseif ($request->request->has('Form-auto')) {
                if ($entity->getAutorizado() === false) {
                    $resp = $this->consultarAutorizacion($entity);
                    if ($resp != null)
                        $this->addTranslatedMessage($resp, 'danger');
                }

            }
        }

        if ($entity->getMensajeError()) {
            $this->addTranslatedMessage($entity->getMensajeError(), 'danger');
        }

        /*if (!$entity->isClosed()) {
            // When the invoice is open send to the edit form by default.
            return $this->redirect($this->generateUrl('invoice_edit', array('id' => $id)));
        }
        */

      return $this->render('Invoice\show.html.twig',
            array(
                'entity' => $entity,
                'form' => $form->createView(),
                //'currency' => $em->getRepository('SiwappConfigBundle:Property')->get('currency', 'EUR'),
                'currency' => $emisor == null ? 'USD' : $emisor->getCurrency(),
                
            ));
    }

    /**
     * @Route("/new", name="invoice_add")
     *
     */
    public function newAction(EmFactory $emFactory, Request $request, TranslatorInterface $translator)
    {
        //require_once "Mobile_Detect.php";
        $detect = new Mobile_Detect;


        $this->translator = $translator;
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $user = $this->getUser();

        $em = $emFactory->getEm();
        $empresaRepo = $em->getRepository('App\Entity\Model\Empresa');
        $empresa = $empresaRepo->findOneByUser($user->getRuc());

        // Check for mobile environment.
        $movil = false;
        if ($detect->isMobile()) {
            // Your code here.
            $movil = true;
        }

        $invoice = new Invoice();
        $newItem = new Item();

        $tax = $em->getRepository('App\Entity\Model\Tax')->findTaxDefault($empresa->getId());
        $newItem->setTaxes($tax);
        $invoice->addItem($newItem);

        $itemPago = new ItemPago();
        $itemPago->setPlazo(0);
        $invoice->addPago($itemPago);

        /*if ($request->isMethod('GET') || $request->isMethod('get')) {
            $consfinal = $em->getRepository('App\Entity\Model\Customer')->findConsumidorFinal($empresa->getId());
            if ($consfinal) {
                //$consfinal = new Customer();
                $invoice->setCustomer($consfinal);
                $invoice->setCustomerIdentification($consfinal->getIdentification());
                $invoice->setCustomerName($consfinal->getName());
                $invoice->setInvoicingAddress($consfinal->getInvoicingAddress());
                $invoice->setCustomerEmail($consfinal->getEmail());
            }
        }*/

        $form = $this->createForm('App\Form\InvoiceType', $invoice, [
            'action' => $this->generateUrl('invoice_add'),
        ]);

        /*if ($request->isMethod('POST')) {

            $taxRepo = $em->getRepository('SiwappCoreBundle:Tax');

            $all = $request->request->all();

            $aux= $all['invoice']['items'];
            if ( $aux != null) {

                foreach ($aux as $clave=>$Item) {
                    if ($Item['taxes'] == "S") {
                        $tax = $taxRepo->find(1);
                        if (!$tax) {
                            continue;
                        }
                        $Item['taxes'] = array(1);
                    } else {
                        $tax = $taxRepo->find(2);
                        if (!$tax) {
                            continue;
                        }
                        $Item['taxes'] = array(2);
                    }
                    $aux[$clave]= $Item;

                }

                $all['invoice']['items'] = $aux;
                $request->request->replace($all);
            }
            $form->handleRequest($request);
        }
        else*/

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            if ($request->request->has('save_draft')) {
                $invoice->setStatus(Invoice::DRAFT);
            } else {
                // Any save action transforms this to opened.
                $invoice->setStatus(Invoice::OPENED);
            }

            //if ($invoice->getCustomer() == null && $invoice->getCustomerIdentification() != '9999999999999') {
            //    $this->addTranslatedMessage('Cliente no se encuentra registrado', 'danger');
            //} else {
                //$invoice->setNumber(null);
                $serie = $invoice->getSeries()->getValue();
                $invoice->setSerie($serie);
                $this->cargarImpuestos($invoice);
                $invoice->setEmpresa($empresa);
                $invoice->setUsuario($user->getId());
                $invoice->setAmbiente($empresa->getTipoAmbiente());

                $em->persist($invoice);
                $em->flush();
                //$this->addTranslatedMessage('flash.added');

                $invoice_id = $invoice->getId();

                $invoice = $this->generarXml($invoice);

                if ($empresa->getEnvioAutomatico()) {

                    if ($invoice !== null) {
                        $app_url = $this->getParameter('cola_url');

                        $error = false;

                        $resp = RestApiFunciones::enviarComprobanteCola($error,
                            $invoice->getCustomerName(),
                            $invoice->getCustomerEmail(),
                            $user->getId(),
                            $invoice->getXml(),
                            $invoice->getClaveAcceso(),
                            $app_url,
                            'invoice'
                        );

                        if ($error) {
                            $this->addTranslatedMessage($resp, 'danger');
                            $invoice->setMensajeError($resp);
                        }

                        $em->persist($invoice);
                        $em->flush();

                    }

                    return $this->redirect($this->generateUrl('invoice_index'));

                }
                return $this->redirect($this->generateUrl('invoice_show', ['id' => $invoice_id, 'slug' => $invoice->getSlug()]));
            //}
        }

        $customer = new Customer();

        $formcustomer = $this->createForm('App\Form\CustomerType', $customer, [
            'action' => $this->generateUrl('rest_customer_add'),
        ]);
        $formcustomer->handleRequest($request);

        return $this->render('Invoice\edit.html.twig',
            array(
                'form' => $form->createView(),
                'movil' => $movil,
                'formcustomer' => $formcustomer->createView(),
                'customer' => $customer,
                'entity' => $invoice,
                //'currency' => $em->getRepository('SiwappConfigBundle:Property')->get('currency', 'EUR'),
                'currency' => $empresa == null ? 'USD' : $empresa->getCurrency(),
            ));
    }


    /**
     * @Route("/edit/{slug}inv{id}", name="invoice_edit")
     *
     */
    public function editAction($id, EmFactory $emFactory, Request $request, $slug, TranslatorInterface $translator)
    {
        $this->translator = $translator;
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $user = $this->getUser();

        $em = $emFactory->getEm();
        $empresaRepo = $em->getRepository('App\Entity\Model\Empresa');
        $empresa = $empresaRepo->findOneByUser($user->getRuc());

        $entity = $em->getRepository('App\Entity\Model\Invoice')->findBySlug($slug, $id);
        if (!$entity && $entity->getEmpresa() != $empresa) {
            throw $this->createNotFoundException('Unable to find Invoice entity.');
        }

        if($entity->getAutorizado()){
            return $this->redirect($this->generateUrl('invoice_show', ['id' => $id, 'slug' => $slug]));
        }

        $form = $this->createForm('App\Form\InvoiceType', $entity, [
            'action' => $this->generateUrl('invoice_edit', ['id' => $id, 'slug' => $slug]),
        ]);
        $form->handleRequest($request);

        $entity->setEmpresa($empresa);

        if ($form->isSubmitted() && $form->isValid()) {
            $redirectRoute = 'invoice_show';

            $serie = $entity->getSeries()->getValue();
            $entity->setSerie($serie);
            $entity->setUsuario($user->getId());
            $this->cargarImpuestos($entity);

            if ($request->request->has('save_draft')) {
                $entity->setStatus(Invoice::DRAFT);
            } elseif ($request->request->has('save_close')) {
                $entity->setForcefullyClosed(true);
            } elseif ($entity->isDraft()) {
                // Any save action transforms this to opened.
                $entity->setStatus(Invoice::OPENED);
            }

            /*
            // See if one of PDF/Print buttons was clicked.
            if ($request->request->has('save_pdf')) {
                $redirectRoute = 'invoice_show_pdf';
            } elseif ($request->request->has('save_print')) {
                $this->get('session')->set('invoice_auto_print', $id);
            }

            */

            // Save.
            $em->persist($entity);
            $em->flush();
            //$this->addTranslatedMessage('flash.updated');

            $entity = $this->generarXml($entity);

            return $this->redirect($this->generateUrl($redirectRoute, ['id' => $id, 'slug' => $slug]));
        }

        return $this->render('Invoice\edit.html.twig',
            array(
                'entity' => $entity,
                'form' => $form->createView(),
                //'currency' => $em->getRepository('SiwappConfigBundle:Property')->get('currency', 'EUR'),
                'currency' => $empresa == null ? 'USD' : $empresa->getCurrency(),
            ));
    }











    public function enviarSriOnline(Invoice $invoice)
    {
        $invoice = $this->generarXml($invoice);
        $em = $this->getDoctrine()->getManager();

        if($invoice !== null) {
            $app_url = $this->getParameter('api_url');

            $error = false;
            $resp = RestApiFunciones::enviarComprobante($error, $invoice->getXml(), $invoice->getClaveAcceso(), $app_url);

            if ($error)
                $this->addTranslatedMessage($resp->message, 'danger');
            else {
                if ($resp->estado === 'recibido') {
                    $resp = $this->consultarAutorizacion($invoice);

                    if ($resp !== null)
                        $this->addTranslatedMessage($resp, 'danger');
                } else {
                    $invoice->setMensajeError($resp->message);
                    $this->addTranslatedMessage($resp->message, 'danger');
                    $em->persist($invoice);
                    $em->flush();
                }
            }

        }
    }

    /**
     * @Route("/payments/{slug}inv{id}", name="invoice_payments")
     *
     */
    public function paymentsAction(Request $request, $slug, EmFactory $emFactory, TranslatorInterface $translator)
    {
        $this->translator = $translator;

        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $user = $this->getUser();

        $em = $emFactory->getEm();
        $empresaRepo = $em->getRepository('App\Entity\Model\Empresa');
        $empresa = $empresaRepo->findOneByUser($user->getRuc());

        // Return all payments
        $invoice = $em->getRepository('App\Entity\Model\Invoice')->findBySlug($slug);
        if (!$invoice) {
            throw $this->createNotFoundException('Unable to find Invoice entity.');
        }

        $payment = new Payment;
        $addForm = $this->createForm('App\Form\PaymentType', $payment, [
            'action' => $this->generateUrl('invoice_payments', ['id' => $invoice->getId(), 'slug' => $slug]),
        ]);
        $addForm->handleRequest($request);
        if ($addForm->isSubmitted() && $addForm->isValid()) {
            $invoice->addPayment($payment);
            $em->persist($invoice);
            $em->flush();
            $this->addTranslatedMessage('payment.flash.added');

            // Rebuild the query, since we have new objects now.
            return $this->redirect($this->generateUrl('invoice_index'));
        }

        $listForm = $this->createForm('App\Form\ListInvoicePaymentType', $invoice->getPayments()->getValues(), [
            'action' => $this->generateUrl('invoice_payments', ['id' => $invoice->getId(), 'slug' => $slug]),
        ]);
        $listForm->handleRequest($request);

        if ($listForm->isSubmitted() && $listForm->isValid()) {
            $data = $listForm->getData();
            foreach ($data['payments'] as $payment) {
                $invoice->removePayment($payment);
                $em->persist($invoice);
                $em->flush();
            }
            $this->addTranslatedMessage('payment.flash.bulk_deleted');

            // Rebuild the query, since some objects are now missing.
            return $this->redirect($this->generateUrl('invoice_index'));
        }

        return $this->render('Payment\list.html.twig',
            [
                'invoiceId' => $invoiceId,
                'add_form' => $addForm->createView(),
                'list_form' => $listForm->createView(),
                //'currency' => $em->getRepository('SiwappConfigBundle:Property')->get('currency', 'EUR'),
                'currency' => $emisor == null ? 'USD' : $emisor->getCurrency(),
            ]);
    }

    /**
     * @Route("/form-totals", name="invoice_form_totals")
     */
    public function getInvoiceFormTotals(EmFactory $emFactory, Request $request)
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $user = $this->getUser();

        $em = $emFactory->getEm();

        $post = $request->request->get('invoice');
        if (!$post) {
            throw new NotFoundHttpException;
        }

        $response = $this->getInvoiceTotalsFromPost($post, new Invoice, $request->getLocale());

        return new JsonResponse($response);
    }


    /**
     * @Route("/pdfpreview/{slug}inv{id}", name="invoice_show_pdf_preview")
     *
     */
    public function showOnlinePdfAction($id,  $slug, EmFactory $emFactory, TranslatorInterface $translator, Request $request, LoggerInterface $logger)
    {
        $this->logger = $logger;
        $this->translator = $translator;
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $user = $this->getUser();

        $em = $emFactory->getEm();
        $empresaRepo = $em->getRepository('App\Entity\Model\Empresa');
        $empresa = $empresaRepo->findOneByUser($user->getRuc());

        $invoice = $em->getRepository('App\Entity\Model\Invoice')->findBySlug($slug, $id);
        if (!$invoice) {
            throw $this->createNotFoundException('Unable to find Invoice entity.');
        }

        $filename = 'FAC_' . $invoice->getSerie() . "-" . str_pad($invoice->getNumber(), 9, '0', STR_PAD_LEFT) . '.pdf';

        if ($invoice->getAutorizado())
            $xml = $invoice->getXmlAutorizado();
        else
            $xml = $invoice->getXml();

        $app_url = $this->getParameter('api_url').'facturaride.php';

        $error = false;
        $mensaje = "";
        $docPdf = RestApiFunciones::getPdf($error, $app_url, $invoice->getClaveAcceso(), $xml, $mensaje,$empresa->getRuc());

        if ($error) {
            $this->addTranslatedMessage('ERRROR AL GENERAR EL PDF, ' . $mensaje, 'danger');
        } else {
            file_put_contents($filename, $docPdf);

            $pdf = base64_encode(file_get_contents($filename));

            $response = new Response($pdf);
            $response->headers->set('Content-Type', 'application/octet-stream');
            $response->headers->set('Content-Description', 'File Transfer');
            $response->headers->set('Content-Disposition', 'attachment; filename="'.$filename.'"');
            // $response->headers->set('Expires', '0');
            // $response->headers->set('Content-Transfer-Encoding', 'binary');
            $response->headers->set('Content-length', strlen($pdf));
            $response->headers->set('Cache-Control', 'no-cache private');
            // $response->headers->set('Pragma', 'public');
            // Send headers before outputting anything
            $response->sendHeaders();



            try {
                unlink($filename);
            } catch (\Exception $ex) {

            }
            return $response;
        }
    }


    protected function bulkAutorizar(array $invoices)
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');

        $em = $this->getDoctrine()->getManager();

        foreach ($invoices as $invoice) {
            if($invoice !== null) {
                $app_url = $this->getParameter('api_url');

                $error = false;
                $resp = RestApiFunciones::enviarComprobante($error, $invoice->getXml(), $invoice->getClaveAcceso(), $app_url);

                if ($error)
                    $this->addTranslatedMessage($resp->message, 'danger');
                else {
                    if ($resp->estado === 'recibido') {
                        $resp = $this->consultarAutorizacion($invoice);

                        if ($resp !== null)
                            $this->addTranslatedMessage($resp, 'danger');
                    } else {
                        $invoice->setMensajeError($resp->message);
                        $this->addTranslatedMessage($resp->message, 'danger');
                        $em->persist($invoice);
                        $em->flush();
                    }
                }

            }
        }

        //return $this->redirect($this->generateUrl('admin_cmp_index'));
    }



    protected function consultarAutorizacion(Invoice $invoice)
    {
        $respuesta = null;
        try {
            $em = $this->getDoctrine()->getManager();

            $app_url = $this->getParameter('api_url');

            $error = false;

            $resp = RestApiFunciones::consultarAutoComprobante($error, $app_url, $invoice->getClaveAcceso());

            if ($error) {
                $this->addTranslatedMessage($resp, 'danger');
                $invoice->setSinrespuesta(true);
                $invoice->setMensajeError($resp);
                $em->persist($invoice);
                $em->flush();

            } else {
                if ($resp->autorizado) {
                    $this->addTranslatedMessage('Comprobante autorizado, fecha: ' . $resp->fecha);
                    $invoice->setAutorizado(true);
                    $invoice->setSinrespuesta(false);
                    $invoice->setMensajeError("");
                    $invoice->setFechaAutorizacion($resp->fecha);
                    $invoice->setXmlAutorizado($resp->comprobante);
                    $invoice->setStatus(Invoice::CLOSED);
                    $invoice->setForcefullyClosed(true);
                    $em->persist($invoice);
                    $em->flush();

                } else {
                    $this->addTranslatedMessage($resp, 'danger');
                }
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }

        return $respuesta;
    }

    protected function addTranslatedMessage($message, $status = 'success')
    {
        $this->get('session')
            ->getFlashBag()
            ->add($status, $this->translator->trans($message, [], 'invoice'));
    }

}
