<?php

namespace PointRetrait\Controller\backOffice;

use LivraisonParSecteurs\LivraisonParSecteurs;
use LivraisonParSecteurs\Model\LpsAreaSchedule;
use LivraisonParSecteurs\Model\LpsAreaScheduleQuery;
use PointRetrait\Model\PdrPlacesQuery;
use PointRetrait\Model\PdrSchedule;
use PointRetrait\Model\PdrScheduleQuery;
use PointRetrait\PointRetrait;
use Propel\Runtime\Map\TableMap;
use Propel\Runtime\Propel;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Thelia\Controller\Admin\BaseAdminController;
use Thelia\Core\Security\AccessManager;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Tools\URL;

/**
 * Class ScheduleController
 * @package PointRetrait\Controller
 */
class ScheduleController extends BaseAdminController
{

    /*
     * Delete a day in a place's withdrawal schedule
     */
    public function deleteSchedule()
    {
        // Check current user authorization
        if (null !== $response = $this->checkAuth(AdminResources::MODULE, PointRetrait::getModuleCode(), AccessManager::UPDATE))
            return $response;

        $placeScheduleId = $this->getRequest()->get('schedule_id');
        $query = PdrScheduleQuery::create()->findById($placeScheduleId);
        if ($query === null)
            $error_msg = "Delivery area schedule not found by Id";
        else
        {
            $con = Propel::getConnection();
            $con->beginTransaction();
            $query->delete($con);
            $con->commit();
        }

        if ($this->getRequest()->request->get("success_url") == null) {
            return new RedirectResponse(URL::getInstance()->absoluteUrl(MODULE_URL));
        } else {
            return new RedirectResponse(URL::getInstance()->absoluteUrl($this->getRequest()->request->get("success_url")));
        }
    }


    /*
     * Update a day in a place's withdrawal schedule
     */
    public function updateSchedule()
    {
        // Check current user authorization
        if (null !== $response = $this->checkAuth(AdminResources::MODULE, PointRetrait::getModuleCode(), AccessManager::UPDATE))
            return $response;

        $con = Propel::getConnection();
        $con->beginTransaction();

        $error_msg = "";
        $changeForm = $this->createForm("pdr.place.update.schedule", "form");
        try {
            $form = $this->validateForm($changeForm, "POST");
            $data = $form->getData();

            $placeScheduleId = $this->getRequest()->get('schedule_id');
            $query = PdrScheduleQuery::create()->findOneById($placeScheduleId);
            if ($query === null)
                $error_msg = "Withdrawal place schedule not found by Id";
            else
            {
                $query->fromArray($data, TableMap::TYPE_FIELDNAME);
                $query->save($con);
                $con->commit();
            }
        } catch (FormValidationException $ex) {
            $error_msg = $this->createStandardFormValidationErrorMessage($ex);

            if (false !== $error_msg) {
                $this->setupFormErrorContext(
                    $this->getTranslator()->trans("Schedule update"),
                    $error_msg,
                    $changeForm,
                    $ex
                );

                return $this->generateErrorRedirect($changeForm);
            }
        }

        if ($data['success_url'] == null) {
            return new RedirectResponse(URL::getInstance()->absoluteUrl(MODULE_URL));
        } else {
            return $this->generateSuccessRedirect($changeForm);
        }
    }


    /*
     * Add a new withdrawal day
     */
    public function createSchedule()
    {
        // Check current user authorization
        if (null !== $response = $this->checkAuth(AdminResources::MODULE, PointRetrait::getModuleCode(), AccessManager::UPDATE))
            return $response;

        $con = Propel::getConnection();
        $con->beginTransaction();

        $error_msg = "";
        $changeForm = $this->createForm("pdr.place.create.schedule", "form");
        try {
            $form = $this->validateForm($changeForm, "POST");
            $data = $form->getData();

            $query = new PdrSchedule();
            $query->fromArray($data, TableMap::TYPE_FIELDNAME);
            $query->setIdPlace($data['place_id']);
            $query->save($con);
            $con->commit();

        } catch (FormValidationException $ex) {
            $error_msg = $this->createStandardFormValidationErrorMessage($ex);

            if (false !== $error_msg) {
                $this->setupFormErrorContext(
                    $this->getTranslator()->trans("Schedule update"),
                    $error_msg,
                    $changeForm,
                    $ex
                );

                return $this->generateErrorRedirect($changeForm);
            }
        }

        if ($data['success_url'] == null) {
            return new RedirectResponse(URL::getInstance()->absoluteUrl(MODULE_URL));
        } else {
            return $this->generateSuccessRedirect($changeForm);
        }
    }

}