<?php

namespace PointRetrait\Controller\backOffice;

use PointRetrait\Model\PdrPlacesQuery;
use PointRetrait\PointRetrait;
use Propel\Runtime\Map\TableMap;
use Propel\Runtime\Propel;
use Thelia\Controller\Admin\BaseAdminController;
use Thelia\Core\Security\AccessManager;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Form\Exception\FormValidationException;

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

    public function viewPlace()
    {
        $selectedPlace = PdrPlacesQuery::create()->findOneById($this->getRequest()->query->get("place_id"));

        return $this->render("place-edit", array('module_code' => PointRetrait::getModuleCode(),
            'place_id' => $selectedPlace));
    }


    public function editPlace()
    {
        // Check current user authorization
        if (null !== $response = $this->checkAuth(AdminResources::MODULE, PointRetrait::getModuleCode(), AccessManager::VIEW))
            return $response;

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

        $error_msg = "";
        $changeForm = $this->createForm("pdr-place-main-update", "form");

        try {
            $form = $this->validateForm($changeForm, "POST");

            $data = $form->getData();
            $place = PdrPlacesQuery::create()->findOneById($data['place_id']);
            if ($place === null) {
                $error_msg = "Withdrawal place not found by Id";
            }
            else {
                $place->fromArray($data, TableMap::TYPE_FIELDNAME);
                $place->save();
                $con->commit();
            }
        } catch (FormValidationException $ex) {
            $error_msg = $this->createStandardFormValidationErrorMessage($ex);
        }

        if ($this->getRequest()->get('save_mode') == 'stay')
            return $this->render("place-edit");

        return $this->render("places-list");
    }

}