<?php

namespace App\Controller\BackendAdmin;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

use Doctrine\ORM\EntityManagerInterface;

use App\Repository\SocieteRepository;
use App\Repository\AnnonceRepository;
use App\Repository\PositionRepository;
use App\Repository\AffichageRepository;
use App\Repository\LigneRepository;

use App\Entity\Affichage;


use App\Service\BackendAdmin\ServiceAnnonce;

#[Route('/backend/admin/annonce/position')]
class AnnoncePositionController extends AbstractController
{

    /**
     * @var PositionRepository $positionRepository
     */
    private $positionRepository;


    /**
     * @var AnnonceRepository $annonceRepository
     */
    private $annonceRepository;

    /**
     * @var LigneRepository $ligneRepository
     */
    private $ligneRepository;

    
    /**
     * @var EntityManagerInterface $em
     */
    private $em;


    /**
     * @var ServiceAnnonce $serviceAnnonce
     */
    private $serviceAnnonce;


    /**
     * @param PositionRepository $positionRepository
     * @param AnnonceRepository $annonceRepository
     * @param EntityManagerInterface $em
     * @param ServiceAnnonce $serviceAnnonce
     * @return $this
     */
    public function __construct(
        PositionRepository $positionRepository,
        AnnonceRepository $annonceRepository,
        LigneRepository $ligneRepository,
        ServiceAnnonce $serviceAnnonce,
        EntityManagerInterface $em
    ){
        $this->positionRepository = $positionRepository;
        $this->annonceRepository = $annonceRepository;
        $this->ligneRepository = $ligneRepository;
        $this->serviceAnnonce = $serviceAnnonce;
        $this->em = $em;
    }

    #[Route('/index', name: 'backend_admin_position_index')]
    public function index(): Response
    {
        $positions = $this->positionRepository->findAll();

        return $this->render('backend_admin/position_affichage/index.html.twig', ['positions'=>$positions]);
    }

    #[Route('/detail', name: 'backend_admin_position_detail')]
    public function detail(Request $request): Response
    {
        $idPosition = $request->get('idPosition');
        
        $position = $this->positionRepository->find($idPosition);

        $lignes = $this->ligneRepository->findAllKeyId();

        $msg = $request->get('msg');
        if($msg == 'add'){
            $this->addFlash('success', ['title'=>'Success', 
                                        'message'=>"La position et l'affichage d'annonce <b>(".$position->getAnnonce()->getTitre().")</b> a été bien enregister."]);
        }
        


        return $this->render('backend_admin/position_affichage/detail.html.twig', ['position'=>$position, 'ligne' => $lignes[$position->getLigne()]]);
    }


    #[Route('/creer', name: 'backend_admin_position_creer')]
    public function creer(Request $request, 
                                SocieteRepository $societeRepository): Response
    {
        $idSociete = $request->get('idSociete');
        if($idSociete){
            $annonces = $this->annonceRepository->findBy(["societe"=>$idSociete], ["id"=>'DESC']);
            $options = '';
            foreach($annonces as $annonce){
                $options .= '<option value="'.$annonce->getId().'" largeur="'.$annonce->getLargeur().'" >'.$annonce->getTitre().'</option>';
            }
            return new Response($options);
        }
        
        return $this->render('backend_admin/position_affichage/creer.html.twig',['societes'=>$societeRepository->findAll()]);
    }


    #[Route('/ligne_detail', name: 'backend_admin_position_ligne_detail')]
    public function ligne_detail(Request $request): Response
    {

        $dimension = $request->get('dimension');

        $lignes = $this->ligneRepository->findAllKeyId();

        $options = '<option value=""></option>';

        foreach($lignes as $ligne){
            $options .= '<option value="'.$ligne->getId().'">('.$ligne->getRang().') '.$ligne->getId().'e ligne à '.$ligne->getPrixByBimension($dimension).' DT</option>';
        }

        return new Response($options);
    }




    #[Route('/disponibilite', name: 'backend_admin_position_disponibilite')]
    public function disponibilite(Request $request, 
                                AffichageRepository $affichageRepository): Response
    {
        $id_annonce = $request->get('id_annonce');
        $id_ligne = $request->get('id_ligne');
        $date_debut = $request->get('date_debut');
        $date_fin = $request->get('date_fin');
        
        $annonce = $this->annonceRepository->find($id_annonce);

        $arrAffichages = $this->serviceAnnonce->getAnnoncePosition($annonce, $date_debut, $date_fin, $id_ligne);

        $totalPrix = $nbrDates = $nbrDispo = 0;

        $body = "";

        foreach($arrAffichages as $val) 
        {

            $totalPrix += $val['prix'];

            $nbrDates++;

            if($val['dispo']){
                if($id_ligne == $val['ligne']->getId()){
                    $nbrDispo ++;
                    $body .= '<li class="list-group-item d-flex justify-content-between lh-sm">
                            <div>
                                <h6 class="my-0"> '.$val['date']->format("d/m/Y").'</h6>
                                <small class="text-muted">Disponible</small>
                            </div>
                            <small class="text-muted">Ligne '.$val['ligne']->getRang().'</small>
                            <span class="text-muted">'.$val['prix'].' DT</span>
                        </li>';

                }else{
                    $body .= '<li class="list-group-item d-flex justify-content-between lh-sm">
                            <div>
                                <h6 class="my-0 ">'.$val['date']->format("d/m/Y").'</h6>
                                <small class="text-warning">Disponible sur une autre ligne</small>
                            </div>
                            <small class="text-muted">Ligne '.$val['ligne']->getRang().'</small>    
                            <span class="text-muted">'.$val['prix'].' DT</span>
                        </li>';
                }
            }else{
                $body .= '<li class="list-group-item d-flex justify-content-between lh-sm">
                            <div>
                                <h6 class="my-0 ">'.$val['date']->format("d/m/Y").'</h6>
                                <small class="text-danger">Ligne Suivante Disponible</small>
                            </div>
                            <small class="text-muted">Ligne '.$val['ligne']->getRang().'</small>    
                            <span class="text-muted">'.$val['prix'].' DT</span>
                        </li>';
            }

        }

        $result = ' <div class="col-md-12 col-lg-12 order-md-last" style="display:">
                        <h4 class="d-flex justify-content-between align-items-center mb-3">
                            <span class="text-muted">Disponibilité annonce sur la Ligne </span>
                            <span class="badge bg-secondary rounded-pill"> '.$nbrDispo.'/'.$nbrDates.'</span>
                        </h4>
                        <div class="overflow-scroll p-3 bg-light" style="height: 400px;">
                            <ul class="list-group mb-3" >'.$body ; 

        $result .= '</ul>
                        </div>
                        <br>
                        <p class="fs-5">
                            Nombre des jours: <strong>'.$nbrDates.'</strong><br><br>
                            Prix Total d\'annonce: <strong>'.$totalPrix.' DT</strong>
                        </p>
                    </div>';

        return new Response($result);
    }


    #[Route('/save', name: 'backend_admin_position_save')]
    public function save(Request $request): Response
    {
        $id_annonce = $request->get('id_annonce');
        $id_ligne =$request->get('id_ligne');
        $date_debut = $request->get('date_debut');
        $date_fin = $request->get('date_fin');

        $annonce = $this->annonceRepository->find($id_annonce);

        $position = $this->positionRepository->addPosition($annonce, $date_debut, $date_fin, $id_ligne, $this->getUser());

        $arrAffichages = $this->serviceAnnonce->getAnnoncePosition($annonce, $date_debut, $date_fin, $id_ligne);
        
        foreach($arrAffichages as $value){
            if($value['dispo']){
                $affichage = new Affichage();
                $affichage->setAnnonce($annonce);
                $affichage->setDateShow($value['date']);
                $affichage->setLigne($value['ligne']->getId());
                $affichage->setPosition($position);
                $affichage->setPrix($value['prix']);
                $this->em->persist($affichage);
            }
        }
        $this->em->flush();

        return new Response($position->getId());
    }

   
}


//datatable.html.twig