<?php

namespace LivraisonParSecteurs\Hook;

use LivraisonParSecteurs\LivraisonParSecteurs;
use LivraisonParSecteurs\Model\Base\LpsAreaCityQuery;
use Propel\Runtime\Exception\PropelException as PropelException;
use Propel\Runtime\Propel;
use Thelia\Core\Event\Hook\HookRenderEvent;
use Thelia\Core\Hook\BaseHook;
use Thelia\Core\Translation\Translator;
use Thelia\Model\AddressQuery;
use Thelia\Module\Exception\DeliveryException;

class FrontHook extends BaseHook
{

    public function onOrderDeliveryExtra(HookRenderEvent $event)
    {
        $con = Propel::getConnection();

        $addressId = $this->getRequest()->getSession()->getOrder()->getChoosenDeliveryAddress();
        $zipcode = AddressQuery::create()->filterById($addressId)->findOne($con)->getZipcode();
        try {
            $areaId = LpsAreaCityQuery::create()->findOneByZipcode($zipcode)->getIdArea();
        }
        catch (PropelException $e) {
            throw new DeliveryException(
                Translator::getInstance()->trans("This module cannot be used on the current cart."));
        }

        $event->add(
            $this->render(
                'order-delivery-extra.html',
                [
                    'module_id' => LivraisonParSecteurs::getModuleId(),
                    'address_id' => $addressId,
                    'area_id' => $areaId
                ]
            )
        );
    }


    public function displayDeliveryDate(HookRenderEvent $event)
    {
        if ((null !== $order = $this->getSession()->getOrder()) && $order->getDeliveryModuleId() == LivraisonParSecteurs::getModuleId())
        {
            $selectedDay = $this->getSession()->get(LivraisonParSecteurs::LPS_DELIVERY_DATE);
            $beginTime = $this->getSession()->get(LivraisonParSecteurs::LPS_DELIVERY_BEGIN_TIME);
            $endTime = $this->getSession()->get(LivraisonParSecteurs::LPS_DELIVERY_END_TIME);

            if ( (null !==  $selectedDay) && (null !==  $beginTime) && (null !==  $endTime) )
            {
                $event->add(
                    $this->render(
                        'delivery-address.html', [
                        'day' => $selectedDay,
                        'begin_time' => $beginTime,
                        'end_time' => $endTime
                    ])
                );
            }
        }
    }

}


