<?php
namespace Bill\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Bill\Entity\Bill;
use Bill\Form\BillForm;
use Service\Entity\Service;
use User\Entity\User;

/**
 * This controller is responsible for Bill management (adding, editing, 
 * viewing Bills and changing Bill's password).
 */
class BillController extends AbstractActionController 
{
    /**
     * Entity manager.
     * @var Doctrine\ORM\EntityManager
     */
    private $entityManager;
    
    /**
     * Bill manager.
     * @var Bill\Service\BillManager 
     */
    private $billManager;
    
    /**
     * Constructor. 
     */
    public function __construct($entityManager, $billManager)
    {
        $this->entityManager = $entityManager;
        $this->billManager = $billManager;
    }
    
    /**
     * This is the default "index" action of the controller. It displays the 
     * list of Bills.
     */
    public function indexAction() 
    {	
		
		
		$services = $this->entityManager->getRepository(Service::class)
                ->findBy([], ['id'=>'ASC']);
		
		$bills = $this->entityManager->getRepository(Bill::class)
                ->findBy([], ['id'=>'ASC']);
        
        return new ViewModel([
            'bills' => $bills,
			'services' => $services,
        ]);
    } 
    
    /**
     * This action displays a page allowing to add a new Bill.
     */
    public function addAction()
    {
        // Create Bill form
     
		$user = $this->entityManager->getRepository(User::class)
                ->findOneByEmail($this->identity());
        $services = $this->entityManager->getRepository(Service::class)
                ->findBy(['userid' => $user->getId()], ['id'=>'ASC']);
				 $form = new BillForm('create', $this->entityManager, null ,$services);
        
        // Check if Bill has submitted the form
        if ($this->getRequest()->isPost()) {
            
            // Fill in the form with POST data
            $request = $this->getRequest();
			$data = array_merge_recursive(
                $request->getPost()->toArray(),
                $request->getFiles()->toArray()
            );          
			//var_dump($data);exit;
            $form->setData($data);
            
            // Validate form
            if($form->isValid()) {
                
                // Get filtered and validated data
                $data = $form->getData();
                
                // Add Bill.
                $bill = $this->billManager->addBill($data);
                
                // Redirect to "view" page
                return $this->redirect()->toRoute('bills', 
                        ['action'=>'view', 'id'=>$bill->getId()]);                
            }               
        } 
        
        return new ViewModel([
                'form' => $form
            ]);
    }
    
    /**
     * The "view" action displays a page allowing to view Bill's details.
     */
    public function viewAction() 
    {
        $id = (int)$this->params()->fromRoute('id', -1);
        if ($id<1) {
            $this->getResponse()->setStatusCode(404);
            return;
        }
        
        // Find a Bill with such ID.
        $bill = $this->entityManager->getRepository(Bill::class)
                ->find($id);
        
        if ($bill == null) {
            $this->getResponse()->setStatusCode(404);
            return;
        }
		
		$fileName = './data/upload/' . $bill->getName();
                
        return new ViewModel([
            'bill' => $bill,
			'fileName' => $fileName
        ]);
    }
    
    /**
     * The "edit" action displays a page allowing to edit Bill.
     */
    public function editAction() 
    {
        $id = (int)$this->params()->fromRoute('id', -1);
        if ($id<1) {
            $this->getResponse()->setStatusCode(404);
            return;
        }
        
        $bill = $this->entityManager->getRepository(Bill::class)
                ->find($id);
        
        if ($bill == null) {
            $this->getResponse()->setStatusCode(404);
            return;
        }
        
        // Create Bill form
        $user = $this->entityManager->getRepository(User::class)
                ->findOneByEmail($this->identity());
        $services = $this->entityManager->getRepository(Service::class)
                ->findBy(['userid' => $user->getId()], ['id'=>'ASC']);
		$form = new BillForm('update', $this->entityManager, $bill, $services);
        
        // Check if Bill has submitted the form
        if ($this->getRequest()->isPost()) {
            
            // Fill in the form with POST data
            $data = $this->params()->fromPost();            
            
            $form->setData($data);
            
            // Validate form
            if($form->isValid()) {
                
                // Get filtered and validated data
                $data = $form->getData();
                
                // Update the Bill.
                $this->billManager->updateBill($bill, $data);
                
                // Redirect to "view" page
                return $this->redirect()->toRoute('bills', 
                        ['action'=>'view', 'id'=>$bill->getId()]);                
            }               
        } else {
            $form->setData(array(
                    'date'=>$bill->getDate(),
                    'value'=>$bill->getValue(),
					'serviceid'=>$bill->getServiceid(),
                                        
                ));
        }
        
        return new ViewModel(array(
            'bill' => $bill,
            'form' => $form
        ));
    }
  
    /**
     * This action displays a page allowing to change Bill's password.
     */
    
}


