<?php

/**
 *
 * bareos-webui - Bareos Web-Frontend
 *
 * @link      https://github.com/bareos/bareos for the canonical source repository
 * @copyright Copyright (C) 2013-2026 Bareos GmbH & Co. KG (http://www.bareos.org/)
 * @license   GNU Affero General Public License (http://www.gnu.org/licenses/)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

namespace Api\Controller;

use Laminas\Mvc\Controller\AbstractRestfulController;
use Laminas\View\Model\JsonModel;
use Exception;

class PoolController extends AbstractRestfulController
{
    protected $bsock = null;
    protected $poolModel = null;
    protected $result = null;

    public function getList()
    {
        $this->RequestURIPlugin()->setRequestURI();

        if (!$this->SessionTimeoutPlugin()->isValid()) {
            return $this->redirect()->toRoute(
                'auth',
                array(
                    'action' => 'login'
                ),
                array(
                    'query' => array(
                        'req' => $this->RequestURIPlugin()->getRequestURI(),
                        'dird' => $_SESSION['bareos']['director']
                    )
                )
            );
        }

        $this->bsock = $this->getServiceLocator()->get('director');
        $pool = $this->params()->fromQuery('pool');

        if ($pool !== null && !preg_match('/^[A-Za-z0-9_\-\. ]+$/', $pool)) {
            $this->bsock->disconnect();
            $this->getResponse()->setStatusCode(400);
            return new JsonModel(['error' => 'Invalid pool name']);
        }

        try{
            if (isset($pool)) {
                $this->result = $this->getPoolModel()->getPool($this->bsock, $pool);
            } else {
                $this->result = $this->getPoolModel()->getPools($this->bsock);
            }
        } catch(Exception $e) {
            $this->getResponse()->setStatusCode(500);
            error_log($e->getMessage());
        }

        $this->bsock->disconnect();

        return new JsonModel($this->result);
    }

    public function getPoolModel()
    {
        if (!$this->poolModel) {
            $sm = $this->getServiceLocator();
            $this->poolModel = $sm->get('Pool\Model\PoolModel');
        }
        return $this->poolModel;
    }
}
