<?php
namespace App\Controller\Admin;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Entity\Quotes;
use App\Entity\QuoteItems;
use App\Entity\QuoteLines;
use App\Entity\Attachment;
use App\Service\Settings;
use App\Entity\PdfFiles;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\IdField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextEditorField;
use EasyCorp\Bundle\EasyAdminBundle\Field\MoneyField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IntegerField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateField;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\CollectionField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ArrayField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ChoiceField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TelephoneField;
use EasyCorp\Bundle\EasyAdminBundle\Field\NumberField;
use EasyCorp\Bundle\EasyAdminBundle\Field\EmailField;
use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Field\FormField;
use App\Form\Type\QuoteItemType;
use App\Form\Type\QuoteWorkItemType;
use App\Form\Type\AttachmentType;
use App\Field\FilesField;
use App\Field\ListField;
use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Config\KeyValueStore;
use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use Symfony\Component\Form\FormInterface;
use EasyCorp\Bundle\EasyAdminBundle\Config\Filters;
use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
use Knp\Snappy\Pdf;
use Twig\Environment;
class QuotesCrudController extends AbstractCrudController
{
public $files_download_path;
private $pdf;
private $params;
private $settings;
private $twig;
public static function getEntityFqcn(): string
{
return Quotes::class;
}
public function __construct(ContainerBagInterface $params,Pdf $knpSnappyPdf, Settings $settings, Environment $twig)
{
$this->files_download_path = $params->get('app.files.download.path');
$this->pdf= $knpSnappyPdf;
$this->settings = $settings;
$this->params = $params;
$this->twig = $twig;
}
/**
* Called before rendering create entity form
* modify entity and call parent method
*/
public function createNewForm(EntityDto $entityDto, KeyValueStore $formOptions, AdminContext $context): FormInterface
{
//$tax = $this->settings->get('tax')*100;
$tax = 27;
$entityDto->getInstance()->setTax($tax);
if(isset($_GET['plateNumber'])){
$car = $this->getDoctrine()->getRepository('App:Cars')->findOneBy(['plateNumber'=>$_GET['plateNumber']]);
$entityDto->getInstance()->setCar($car);
}
return parent::createNewForm($entityDto,$formOptions,$context);
}
public function configureFields(string $pageName): iterable
{
$req = $this->get('request_stack');
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$quote = $em->getRepository(Quotes::class)->findOneBy(['id'=>$req->getCurrentRequest()->query->get('entityId')]);
$this->quote = $quote;
if(!$quote){
$quote = new Quotes();
}
yield FormField::addPanel('Alapadatok')->addCssClass('col-sm-6');
//yield AssociationField::new('customer');
yield TextField::new('customerName','Ajánlatkérő neve');
yield DateField::new('created','Létrehozva')->hideOnForm();
yield TextField::new('customerAddress','Ajánlatkérő címe');
yield TelephoneField::new('customerPhone','Ajánlatkérő telefonszám');
yield EmailField::new('customerMail','Ajánlatkérő email');
yield ChoiceField::new('discovery', 'Kapcsolatfelvétel')->setChoices(array_flip(Quotes::$discoveries));
yield ChoiceField::new('status')->setChoices(array_flip(Quotes::$statuses));
yield FormField::addPanel('Összesen')->addCssClass('col-sm-6');
yield MoneyField::new('price_sum','Nettó összeg')->setCssClass('font-bold')->setCurrency('HUF')->setNumDecimals(0)->setStoredAsCents(false);
yield TextField::new('tax')->hideOnIndex()->setCssClass('font-bold');
yield MoneyField::new('price_sum_br','Bruttó összeg')->setCssClass('font-bold')->setCurrency('HUF')->setNumDecimals(0)->setStoredAsCents(false);
yield FormField::addPanel('Adatok')->addCssClass('col-sm-12');
yield TextField::new('title','Ajánlat tárgya');
if($pageName == Crud::PAGE_DETAIL){
yield TextField::new('originalText','Eredeti szöveg')->hideOnIndex()->renderAsHtml();
}else{
yield TextEditorField::new('originalText','Eredeti szöveg')->hideOnIndex();
}
yield TextEditorField::new('shortDesc','Munka összefoglaló');
if($pageName == Crud::PAGE_DETAIL){
yield TextField::new('sentMail','Küldött levél')->hideOnIndex()->renderAsHtml();
}else{
yield TextEditorField::new('sentMail','Küldött levél')->hideOnIndex();
}
yield TextEditorField::new('note');
yield FormField::addPanel('Munkák/javítások')->addCssClass('col-sm-6');
if($pageName == Crud::PAGE_DETAIL){
yield ListField::new('quoteBodyguardItems','Lakatos munka')->hideOnIndex();
}else{
yield MoneyField::new('price_bodyguard','Lakatos óradíj')->setCurrency('HUF')->setNumDecimals(0)->setStoredAsCents(false)->hideOnIndex();
yield CollectionField::new('quoteBodyguardItems','Lakatos munka')->onlyOnForms()->setEntryType(QuoteWorkItemType::class)->addCssClass('hide-legend');
}
yield FormField::addPanel('Egyéb költségek/anyagköltség')->addCssClass('col-sm-6');;
if($pageName == Crud::PAGE_DETAIL){
yield ListField::new('quoteOtherItems','Alkatrész/egyéb','material')->hideOnIndex();
}else{
yield CollectionField::new('quoteOtherItems','Alkatrész/egyéb')->onlyOnForms()->setEntryType(QuoteItemType::class)->addJsFiles('js/collection.js')->addCssClass('hide-legend');
}
}
public function configureActions(Actions $actions): Actions
{
$actions->add(Crud::PAGE_INDEX, Action::DETAIL);
$actions->add(Crud::PAGE_EDIT, Action::DETAIL);
//$actions->remove(Crud::PAGE_INDEX, Action::DELETE);
$actionReportPrint = Action::new('ReportPrint', 'Nyomtatás', 'fa fa-print')->linkToCrudAction('actionReportPrint')->setHtmlAttributes(['target'=>'_blank'])->addCssClass('btn btn-primary');
$actionReportPrintSave = Action::new('ReportPrintSave', 'PDF Mentés', 'fa fa-file-pdf')->linkToCrudAction('actionReportPrintSave')->setHtmlAttributes(['target'=>'_blank'])->addCssClass('btn btn-primary');
$actions->add(Crud::PAGE_DETAIL, $actionReportPrint);
$actions->add(Crud::PAGE_DETAIL, $actionReportPrintSave);
$actionMakeQuote = Action::new('MakeQuote', 'Ajánlat készítése', 'fa fa-edit')->linkToCrudAction('actionMakeQuote')->setHtmlAttributes(['target'=>'_blank'])->addCssClass('');
$actions->add(Crud::PAGE_DETAIL, $actionMakeQuote);
$actions->add(Crud::PAGE_INDEX, $actionMakeQuote);
return $actions;
}
/**
* Init crud
*/
public function configureCrud(Crud $crud): Crud
{
return $crud
->setEntityLabelInSingular('Quote')
->setDefaultSort(['id' => 'DESC', 'created'=>'DESC'])
// ->setSearchFields(['car.plateNumber', 'car.manufacturer', 'car.type'])
//->setPaginatorPageSize($this->settings->get('pageSize')?$this->settings->get('pageSize'):20)
;
}
public function updateEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
$now = new \DateTime();
$sum = 0;
foreach ($entityInstance->getQuoteItems() as $key => $value) {
$sum += $value->getPriceSum();
}
$entityInstance->setPriceSum($sum);
if($entityInstance->getTax() == null){
$tax = 27;
}else{
$tax = $entityInstance->getTax();
}
$tx = (intval($tax) / 100 )+1;
foreach ($entityInstance->getQuoteItems()->getValues() as $key => $value) {
switch ($value->getType()) {
case QuoteItems::PAINT:
$price = $entityInstance->getPricePaint();
$value->setPriceQty($price);
break;
case QuoteItems::BODYGUARD:
$price = $entityInstance->getPriceBodyguard();
$value->setPriceQty($price);
break;
case QuoteItems::ASSEMBLY:
$price = $entityInstance->getPriceAssembly();
$value->setPriceQty($price);
break;
}
}
$entityInstance->setPriceSumBr(intval($sum*$tx));
$entityManager->persist($entityInstance);
$entityManager->flush();
}
/**
* configure filter fields
*/
public function configureFilters(Filters $filters): Filters
{
return $filters
// ->add('car')
// ->add('note')
;
}
public function actionMakeQuote(Request $request){
$quote = $this->getDoctrine()->getRepository(Quotes::class)->findOneBy(['id'=>$request->query->get('entityId')]);
$quoteLines = $this->getDoctrine()->getRepository(QuoteLines::class)->findAll();
if(isset($_POST['quote'])){
$quote->setSentMail($_POST['quote']);
$em = $this->getDoctrine()->getManager();
$em->persist($quote);
$em->flush();
}
if(isset($_POST['sendMail']) && $_POST['sendMail'] == 'true'){
$this->sendQuoteMail($quote);
}
return $this->render('quote/make.html.twig',[
'quote'=>$quote,
'quoteLines' => $quoteLines,
]);
}
public function sendQuoteMail($quote){
if($this->params->get('app.mailer')){
$transport = new \Swift_SmtpTransport('mail.gortech.hu', 465)->setStreamOptions([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true,
],
]);
//$transport = new \Swift_SmtpTransport($this->params->get('app.mailer.host'), $this->params->get('app.mailer.port'));
$transport->setUsername($this->params->get('app.mailer.user'))->setPassword($this->params->get('app.mailer.pass'))->setEncryption($this->params->get('app.mailer.sec'));
//dd($transport);
$mailer = new \Swift_Mailer($transport);
$message = (new \Swift_Message('Ajánlat '));
$message->setFrom('info@gortech.hu');
$message->setTo($quote->getCustomerMail());
//$message->setTo('info@microservice.hu');
$message->setBody(
$this->twig->render('emails/quote_mail.html.twig',[
'quote' => $quote,
])
,'text/html'
);
if($mailer->send($message)){
$quote->setUpdated(new \DateTime());
$quote->setSentDate(new \DateTime());
$quote->setSentMail($_POST['quote']);
$quote->setStatus(2);
$em = $this->getDoctrine()->getManager();
$em->persist($quote);
$em->flush();
}
}
}
public function actionReportPrintSave(Request $request){
$em = $this->getDoctrine()->getManager();
$repair = $this->getDoctrine()->getRepository(Quotes::class)->findOneBy(['id'=>$request->query->get('entityId')]);
$html = $this->renderView('quote/quote_pdf.html.twig',[
'type'=>'pdf',
'entity' => $repair,
'settings' => $this->settings,
'base_dir' => $this->params->get('kernel.project_dir').'/public',
'base_image_dir' => $this->params->get('kernel.project_dir').$this->params->get('app.files.download.path')
]);
$name = $repair->getCar()->getPlateNumber()."-".$repair->getId()."-".time().".pdf";
$this->pdf->generateFromHtml($html,'pdf/'.$name);
$pdfFile = new PdfFiles();
$pdfFile->setCar($repair->getCar());
$pdfFile->setFilepath($name);
$pdfFile->setType('Munkalap');
$em->persist($pdfFile);
$em->flush();
return new PdfResponse(
$this->pdf->getOutputFromHtml($html),
$name
);
}
public function actionReportPrint(Request $request){
$em = $this->getDoctrine()->getManager();
$repair = $this->getDoctrine()->getRepository(Quotes::class)->findOneBy(['id'=>$request->query->get('entityId')]);
// $t = $this->getDoctrine()->getRepository(Settings::class)->findOneBy(['name'=>'company']);
$html = $this->renderView('quote/quote_pdf.html.twig',[
'type'=>'pdf',
'entity' => $repair,
'settings' => $this->settings,
'base_dir' => $this->params->get('kernel.project_dir').'/public',
'base_image_dir' => $this->params->get('kernel.project_dir').$this->params->get('app.files.download.path')
]);
$name = $repair->getCar()->getPlateNumber()."-".$repair->getId()."-".time().".pdf";
//return $this->render('repair/report_pdf.html.twig',['type'=>'pdf','entity' => $repair, 'settings' => $this->settings, 'base_dir' => __DIR__.'/../../../public'] );
$this->pdf->generateFromHtml($html,'pdf/'.$name);
return $this->render('page/show_pdf.html.twig',[
'path' => 'pdf/'.$name,
'base_dir' => $this->params->get('kernel.project_dir').'/public',
'type'=>'pdf'
]);
}
}