<?php

namespace App\Controller;

use App\Entity\Assetregister;
use App\Entity\Group;
use App\Entity\Unit;
use App\Entity\Assetdisposal;
use App\Form\AssetregisterType;
use App\Form\AssetdisposalType;
use App\Repository\AssetregisterRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\String\Slugger\SluggerInterface;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Filesystem\Filesystem;

/**
 * @Route("/assetregister")
 */
class AssetregisterController extends AbstractController
{    
    /**
     * @Route("/{page<[1-9]\d*>}", defaults={"page"=1}, name="assetregister_index")
     */
    public function index(Request $request, int $page)
    {
        $data = $request->request->get('form');
        if(isset($data['search']))
        {
            $filter = $data['search'];
        }
        else
        {
            $filter = '';
        }

        $assetregister = $this->getDoctrine()
                         ->getRepository(Assetregister::class)
                         ->getAllAssetregisters($page, $filter);

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


    /**
     * @Route("/new", name="assetregister_new", methods={"GET","POST"})
     */
    public function new(Request $request, SluggerInterface $slugger): Response
    {
        $assetregister = new Assetregister();
        $form = $this->createForm(AssetregisterType::class, $assetregister);
        $form->remove('serialno');
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            dd($assetregister->getAcquisitiondate());
            //Start Reference no Generate
            $assetRegisterLastObj = $this->getDoctrine()
                        ->getRepository(Assetregister::class)
                        ->findLastObjAssetRegister();

            $entityManager = $this->getDoctrine()->getManager();
            $groupObj = $entityManager->getRepository(Group::class)->find($assetregister->getGroups()->getId());

            $now = new \DateTime('now');
            $month = $now->format('m');
            $year = $now->format('Y');
            $refNO = "";
            $serialNo = "";
            if(null !== $assetRegisterLastObj)
               $refYear = substr($assetRegisterLastObj->getSerialno(),-7,4);
            else
                $refYear = 2020;
            if($assetRegisterLastObj == null)
            {
                $refNO = $groupObj->getCode()."/".$year."/".$month."/00001";
            }
            // else if($year != $refYear)
            // {
            //     $refNO = "UEL-ENQ-".$month."/".$year."-0001";
            // }
            else
            {
                $serialNo = substr($assetRegisterLastObj->getSerialno(),-5);
                $serialNo += 1;
                $serialNo = str_pad($serialNo,5,"0",STR_PAD_LEFT);
                $refNO = $groupObj->getCode()."/".$year."/".$month."/".$serialNo;
               
            }
            //End Reference no Generate
           // dd($refNO);
            $assetregister->setSerialno($refNO);

             
            /* @var UploadedFile document */
            $docFile = $form->get('docpath')->getData();

            // this condition is needed because the 'brochure' field is not required
            // so the PDF file must be processed only when a file is uploaded
            if ($docFile) {
                $originalFilename = pathinfo($docFile->getClientOriginalName(), PATHINFO_FILENAME);
                // this is needed to safely include the file name as part of the URL
                $safeFilename = $slugger->slug($originalFilename);
                $newFilename = $safeFilename.'-'.uniqid().'.'.$docFile->guessExtension();

                // Move the file to the directory where brochures are stored
                try {
                    $docFile->move(
                        $this->getParameter('docfiledocument_directory'),
                        $newFilename
                    );
                } catch (FileException $e) {
                    // ... handle exception if something happens during file upload
                }

                // updates the 'brochureFilename' property to store the PDF file name
                // instead of its contents
                $assetregister->setDocpath($newFilename);
            }

            // ... persist the $product variable or any other work
                       
            $assetregister->setDepreciationrate($groupObj->getDepreciationrate());
            $assetregister->setTotaldepdays(round(((100/$groupObj->getDepreciationrate()) * 364),0));
            //dd(date_add(new \DateTime($assetregister->getAcquisitiondate()->format('Y-m-d')) , date_interval_create_from_date_string(round(((100/$groupObj->getDepreciationrate()) * 364),0).' days')));
            $assetregister->setLastdepdate(date_add(new \DateTime($assetregister->getAcquisitiondate()->format('Y-m-d')) , date_interval_create_from_date_string(round(((100/$groupObj->getDepreciationrate()) * 364),0).' days')));
           // dd($assetregister);
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($assetregister);
            $entityManager->flush();

            return $this->redirectToRoute('assetregister_index', [], Response::HTTP_SEE_OTHER);
        }

        return $this->renderForm('assetregister/new.html.twig', [
            'assetregister' => $assetregister,
            'form' => $form,
        ]);
    }

    /**
     * @Route("/{id}/show", name="assetregister_show", methods={"GET"})
     */
    public function show(Assetregister $assetregister): Response
    {
        return $this->render('assetregister/show.html.twig', [
            'assetregister' => $assetregister,
        ]);
    }

    /**
     * @Route("/{id}/edit", name="assetregister_edit", methods={"GET","POST"})
     */
    public function edit(Request $request, Assetregister $assetregister, SluggerInterface $slugger): Response
    {
        $form = $this->createForm(AssetregisterType::class, $assetregister);
        $form->remove('serialno');
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            $filesystem = new Filesystem();
            /* @var UploadedFile Brand Image */
            $docFile = $form->get('docpath')->getData();

            // this condition is needed because the 'brochure' field is not required
            // so the PDF file must be processed only when a file is uploaded
            if ($docFile) {

                // Delete previous image
                $docFileName = $assetregister->getDocpath();
                
                if(null !== $docFileName)
                {
                    $viewFilepath = 'admin/docuploads/'.$docFileName;
                    $filesystem->remove($viewFilepath);
                }             
                // End Delete previous image

                $originalFilename = pathinfo($docFile->getClientOriginalName(), PATHINFO_FILENAME);
                // this is needed to safely include the file name as part of the URL
                $safeFilename = $slugger->slug($originalFilename);
                $newFilename = $safeFilename.'-'.uniqid().'.'.$docFile->guessExtension();
    
                // Move the file to the directory where brochures are stored
                try {
                    $docFile->move(
                        $this->getParameter('docfiledocument_directory'),
                        $newFilename
                    );
                } catch (FileException $e) {
                    // ... handle exception if something happens during file upload
                }
    
                // updates the 'brochureFilename' property to store the PDF file name
                // instead of its contents
                $assetregister->setDocpath($newFilename);
            }
    
            // ... persist the $product variable or any other work

            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('assetregister_index', [], Response::HTTP_SEE_OTHER);
        }

        return $this->renderForm('assetregister/edit.html.twig', [
            'assetregister' => $assetregister,
            'form' => $form,
        ]);
    }

    /**
     * @Route("/{id}/delete", name="assetregister_delete", methods={"POST"})
     */
    public function delete(Request $request, Assetregister $assetregister): Response
    {
        if ($this->isCsrfTokenValid('delete'.$assetregister->getId(), $request->request->get('_token'))) {
            // Delete previous image
            $filesystem = new Filesystem();
            $docFileName = $assetregister->getDocpath();
                
            if(null !== $docFileName)
            {
                $viewFilepath = 'admin/docuploads/'.$docFileName;
                $filesystem->remove($viewFilepath);
            }             
            // End Delete previous image
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->remove($assetregister);
            $entityManager->flush();
        }

        return $this->redirectToRoute('assetregister_index', [], Response::HTTP_SEE_OTHER);
    }

    /**
     * @Route("/searchBar", name="assetregister_searchBar")
     */
    public function SearchBar()
    {
        $form = $this->createFormBuilder(null)
                     ->add('search', TextType::class, array(
                            'attr' => [
                                'class' => 'search-input',
                                'placeholder' => 'Search by any value'
                            ],
                            'label'=>false,
                        ))
                     ->getForm();

        return $this->render('assetregister/searchBar.html.twig', [
            'form' => $form->createView()
        ]);
    }

    /**
     * @Route("/{id}/disposal", name="assetregister_disposal", methods={"GET","POST"})
     */
    public function disposal(Request $request, $id): Response
    {
        $assetdisposal = new Assetdisposal();
        $form = $this->createForm(AssetdisposalType::class, $assetdisposal);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            $entityManager = $this->getDoctrine()->getManager();
            $assetregisterObj = $entityManager->getRepository(Assetregister::class)->find($id);

            $assetdisposal -> setAssetregister($assetregisterObj);
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($assetdisposal);
            $entityManager->flush();

            $this->addFlash('notice', 'Location Created successfully!');

            return $this->redirectToRoute('assetregister_show', ['id' => $id], Response::HTTP_SEE_OTHER);
        }

        return $this->render('assetregister/disposal.html.twig', [
            'assetdisposal' => $assetdisposal,
            'form' => $form->createView(),
        ]);
    }
}
