<?php
namespace App\Controller;
use App\Entity\Entreprise;
use App\Entity\ElectricMeter;
use App\Form\ElectricMeterType;
use App\Repository\ElectricMeterRepository;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Dompdf\Dompdf;
class ElectricMeterController extends AbstractController
{
/**
* @Route("/entreprise/electric_meter/add/{id}", name="app_electric_meter_add")
*/
public function add(int $id, Request $request, EntityManagerInterface $entityManager): Response
{
$electric_meters = new ElectricMeter();
$electric_meters->setEntrepriseId($id);
$form = $this->createForm(ElectricMeterType::class, $electric_meters);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->persist($electric_meters);
$entityManager->flush();
// Redirect to the new contract page
return $this->redirectToRoute('app_entreprise_new_contrat', [
'id' => $id,
'meterId' => $electric_meters->getId(),
'meterType' => 'electric'
]);
}
return $this->render('entreprise/electric_meter/add.html.twig', [
'electric_meterForm' => $form->createView(),
'entreprise_id' => $id
]);
}
/**
* @Route("/entreprise/electric_meter/edit/{id}", name="app_electric_meter_edit")
*/
public function edit(int $id, Request $request, EntityManagerInterface $entityManager, ManagerRegistry $doctrine): Response
{
$electric_meter = $doctrine->getRepository(ElectricMeter::class)->findOneBy(['id' => $id]);
if (!$electric_meter) {
throw $this->createNotFoundException('Electric meter not found');
}
$form = $this->createForm(ElectricMeterType::class, $electric_meter);
$form->handleRequest($request);
$electric_meter_entity = [
'adresse_compteur' => $electric_meter->getAdresseCompteur(),
'PDL' => $electric_meter->getPDL(),
'date_debut' => $electric_meter->getDateDebut() ? date_format($electric_meter->getDateDebut(),"Y-m-d") : "",
'date_fin' => $electric_meter->getDateFin() ? date_format($electric_meter->getDateFin(),"Y-m-d") : "",
'PS' => $electric_meter->getPS(),
'Profil' => $electric_meter->getProfil(),
'CAR' => $electric_meter->getCAR(),
'fournisseur' => $electric_meter->getFournisseur(),
'prix' => $electric_meter->getPrix(),
];
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->flush();
return $this->redirectToRoute('app_entreprise_details',['id' => $electric_meter->getEntrepriseId()]);
}
return $this->render('entreprise/electric_meter/edit.html.twig', [
'electric_meterForm' => $form->createView(),
'electric_meter' => $electric_meter_entity,
'entreprise_id' => $electric_meter->getEntrepriseId()
]);
}
/**
* @Route("/entreprise/electric_meter/suppr/{id}", name="app_electric_meter_suppr")
*/
public function suppr(int $id, Request $request, EntityManagerInterface $entityManager, ManagerRegistry $doctrine): Response
{
$electric_meter = $doctrine->getRepository(ElectricMeter::class)->findOneBy(['id' => $id]);
if (!$electric_meter) {
throw $this->createNotFoundException('Electric meter not found');
}
$entreprise_id = $electric_meter->getEntrepriseId();
$entityManager->remove($electric_meter);
$entityManager->flush();
return $this->redirectToRoute('app_entreprise_details',['id' => $entreprise_id]);
}
/**
* @Route("/entreprise/electric_meter/check_pdl/{pdl}", name="app_electric_meter_check_pdl")
*/
public function checkPDL($pdl, ManagerRegistry $doctrine): Response
{
$electric_meter = $doctrine->getRepository(ElectricMeter::class)->findOneBy(['PDL' => $pdl]);
if($electric_meter){
return new Response("exist");
}
return new Response("available");
}
/**
* @Route("/entreprise/electric_meter/generate_study/{pdl}/{type}", name="app_electric_meter_generate_study")
*/
public function generateStudy(string $pdl=null, string $type=null, ManagerRegistry $doctrine): Response
{
if (!in_array($type, ['C5', 'C4'])) {
throw new \Exception('Type d\'étude non supporté: ' . $type);
}
$electric_meter = $doctrine->getRepository(ElectricMeter::class)->findOneBy(['PDL' => $pdl]);
if (!$electric_meter) {
throw $this->createNotFoundException('Electric meter not found');
}
$entreprise = $doctrine->getRepository(Entreprise::class)->findOneBy(['id' => $electric_meter->getEntrepriseId()]);
if (!$entreprise) {
throw $this->createNotFoundException('Entreprise not found');
}
// Use template based on requested type
if ($type === 'C5') {
$templatePath = $this->getParameter('kernel.project_dir') . '/assets/templates/Résultat d\'étude C5 4 Index.xlsx';
$studyType = 'C5';
} else {
$templatePath = $this->getParameter('kernel.project_dir') . '/assets/templates/Résultat d\'étude C4_C3_C2 5 Index.xlsx';
$studyType = 'C4_C3_C2';
}
// Process address
$address = $electric_meter->getAdresseCompteur() ?? '';
$address_with_no_postal_code_and_city = '';
$postal_code = '';
$city = '';
if ($address) {
if (preg_match('/\b\d{5}\b/', $address, $matches)) {
$postal_code = $matches[0];
$postal_code_position = strpos($address, $postal_code);
$city = trim(substr($address, $postal_code_position + strlen($postal_code)));
$address_with_no_postal_code_and_city = trim(substr($address, 0, $postal_code_position));
}
}
// Create temporary file and copy template
$tempFile = tempnam(sys_get_temp_dir(), 'excel');
copy($templatePath, $tempFile);
// Load the copy with specific settings
$reader = IOFactory::createReader('Xlsx');
$reader->setReadDataOnly(false);
$reader->setIncludeCharts(true);
$spreadsheet = $reader->load($tempFile);
// Get active sheet
$sheet = $spreadsheet->getActiveSheet();
// Set values based on study type
if ($type === 'C4') {
$sheet->setCellValue('B2', $entreprise->getRaisonSociale() ?? '');
$sheet->setCellValue('C5', $entreprise->getSIRET() ?? '');
$sheet->setCellValue('C6', $electric_meter->getPDL() ?? '');
foreach (['C7', 'D7', 'E7', 'F7', 'G7'] as $cell) {
$sheet->setCellValue($cell, $electric_meter->getPS() ?? '');
}
$sheet->setCellValue('C8', $electric_meter->getProfil() ?? '');
$sheet->setCellValue('C11', $address_with_no_postal_code_and_city);
$sheet->setCellValue('C12', ($postal_code && $city) ? $postal_code . ' ' . $city : '');
$sheet->setCellValue('H5', $entreprise->getNaf() ?? '');
$naf = $entreprise->getNaf() ?? '';
$nafNumeric = preg_replace('/[^0-9]/', '', $naf);
$sheet->setCellValue('K6', intval($nafNumeric) > 4500 ? 'Oui' : 'Non');
$sheet->setCellValue('K8', $electric_meter->getDateFin() ? date_format($electric_meter->getDateFin(),"d/m/Y") : "");
} else {
$sheet->setCellValue('B2', $entreprise->getRaisonSociale() ?? '');
$sheet->setCellValue('C5', $entreprise->getSIRET() ?? '');
$sheet->setCellValue('C6', $electric_meter->getPDL() ?? '');
$sheet->setCellValue('C7', $electric_meter->getPS() ?? '');
$sheet->setCellValue('C8', $electric_meter->getProfil() ?? '');
$sheet->setCellValue('C11', $address_with_no_postal_code_and_city);
$sheet->setCellValue('C12', ($postal_code && $city) ? $postal_code . ' ' . $city : '');
$sheet->setCellValue('H5', $entreprise->getNaf() ?? '');
// Handle NAF condition (K6)
$naf = $entreprise->getNaf() ?? '';
$nafNumeric = preg_replace('/[^0-9]/', '', $naf);
$sheet->setCellValue('K6', intval($nafNumeric) > 4500 ? 'Oui' : 'Non');
$sheet->setCellValue('K8', $electric_meter->getDateFin() ? date_format($electric_meter->getDateFin(),"d/m/Y") : "");
}
// Create response
$response = new Response();
// Save with specific settings to preserve formulas
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->setOffice2003Compatibility(false);
$writer->setPreCalculateFormulas(false); // Let Excel calculate formulas
$writer->setIncludeCharts(true);
// Save directly to the original temp file
$writer->save($tempFile);
// Read the file and clean up
$excelData = file_get_contents($tempFile);
unlink($tempFile);
// Set response headers
$RaisonSociale = str_replace(' ', '_', $entreprise->getRaisonSociale() ?? 'unknown');
$pdl_last_4_digits = substr($electric_meter->getPDL() ?? '', -4);
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', 'attachment;filename="Etude_'.$pdl_last_4_digits.'_'.$RaisonSociale.'-'.time().'.xlsx"');
$response->headers->set('Cache-Control', 'max-age=0');
$response->headers->set('Pragma', 'public');
// Set content and return
$response->setContent($excelData);
return $response;
}
}