<?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 Schedule\Controller;

use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\View\Model\ViewModel;
use Laminas\Json\Json;
use Exception;

class ScheduleController extends AbstractActionController
{
    /**
     * Variables
     */
    protected $scheduleModel = null;
    protected $bsock = null;
    protected $acl_alert = false;

    /**
     * Index Action
     *
     * @return object
     */
    public function indexAction()
    {
        $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']
                    )
                )
            );
        }

        $module_config = $this->getServiceLocator()->get('ModuleManager')->getModule('Application')->getConfig();
        $invalid_commands = $this->CommandACLPlugin()->getInvalidCommands(
            $module_config['console_commands']['Schedule']['mandatory']
        );
        if (count($invalid_commands) > 0) {
            $this->acl_alert = true;
            return new ViewModel(
                array(
                    'acl_alert' => $this->acl_alert,
                    'invalid_commands' => implode(",", $invalid_commands)
                )
            );
        }

        $result = null;

        $action = $this->params()->fromQuery('action');
        $schedulename = $this->params()->fromQuery('schedule');

        try {
            $this->bsock = $this->getServiceLocator()->get('director');
        } catch (Exception $e) {
            error_log($e->getMessage());
            return new ViewModel(['error' => 'Failed to connect to director']);
        }

        if (!$this->bsock) {
            return new ViewModel(['error' => 'Failed to connect to director']);
        }

        $schedules = array();

        if (empty($action)) {
            try {
                $schedules = $this->getScheduleModel()->getSchedules($this->bsock);
            } catch (Exception $e) {
                error_log($e->getMessage());
            } finally {
                if ($this->bsock) {
                    try {
                        $this->bsock->disconnect();
                    } catch (Exception $e) {
                        error_log($e->getMessage());
                    }
                }
            }
            return new ViewModel(
                array(
                    'schedules' => $schedules
                )
            );
        } else {
            try {
                if ($action == "enable") {
                    $module_config = $this->getServiceLocator()->get('ModuleManager')->getModule('Application')->getConfig();
                    $invalid_commands = $this->CommandACLPlugin()->getInvalidCommands(
                        $module_config['console_commands']['Schedule']['optional']
                    );
                    if (count($invalid_commands) > 0 && in_array('enable', $invalid_commands)) {
                        $this->acl_alert = true;
                        return new ViewModel(
                            array(
                                'acl_alert' => $this->acl_alert,
                                'invalid_commands' => 'enable'
                            )
                        );
                    } else {
                        $schedules = $this->getScheduleModel()->getSchedules($this->bsock);
                        $result = $this->getScheduleModel()->enableSchedule($this->bsock, $schedulename);
                    }
                } elseif ($action == "disable") {
                    $module_config = $this->getServiceLocator()->get('ModuleManager')->getModule('Application')->getConfig();
                    $invalid_commands = $this->CommandACLPlugin()->getInvalidCommands(
                        $module_config['console_commands']['Schedule']['optional']
                    );
                    if (count($invalid_commands) > 0 && in_array('disable', $invalid_commands)) {
                        $this->acl_alert = true;
                        return new ViewModel(
                            array(
                                'acl_alert' => $this->acl_alert,
                                'invalid_commands' => 'disable'
                            )
                        );
                    } else {
                        $schedules = $this->getScheduleModel()->getSchedules($this->bsock);
                        $result = $this->getScheduleModel()->disableSchedule($this->bsock, $schedulename);
                    }
                }
            } catch (Exception $e) {
                error_log($e->getMessage());
            } finally {
                if ($this->bsock) {
                    try {
                        $this->bsock->disconnect();
                    } catch (Exception $e) {
                        error_log($e->getMessage());
                    }
                }
            }

            return new ViewModel(
                array(
                    'schedules' => $schedules,
                    'result' => $result
                )
            );
        }
    }

    /**
     * Overview Action
     *
     * @return object
     */
    public function overviewAction()
    {
        $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']
                    )
                )
            );
        }

        $result = null;

        try {
            $module_config = $this->getServiceLocator()->get('ModuleManager')->getModule('Application')->getConfig();
            $invalid_commands = $this->CommandACLPlugin()->getInvalidCommands(
                $module_config['console_commands']['Schedule']['optional']
            );
            if (count($invalid_commands) > 0 && in_array('show', $invalid_commands)) {
                $this->acl_alert = true;
                return new ViewModel(
                    array(
                        'acl_alert' => $this->acl_alert,
                        'invalid_commands' => 'show'
                    )
                );
            } else {
                try {
                    $this->bsock = $this->getServiceLocator()->get('director');
                    $result = $this->getScheduleModel()->showSchedules($this->bsock);
                } finally {
                    if ($this->bsock) {
                        try {
                            $this->bsock->disconnect();
                        } catch (Exception $e) {
                            error_log($e->getMessage());
                        }
                    }
                }
            }
        } catch (Exception $e) {
            error_log($e->getMessage());
        }

        return new ViewModel(
            array(
                'result' => $result
            )
        );
    }

    /**
     * Status Action
     *
     * @return object
     */
    public function statusAction()
    {
        $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']
                    )
                )
            );
        }

        $result = null;

        try {
            $module_config = $this->getServiceLocator()->get('ModuleManager')->getModule('Application')->getConfig();
            $invalid_commands = $this->CommandACLPlugin()->getInvalidCommands(
                $module_config['console_commands']['Schedule']['optional']
            );
            if (count($invalid_commands) > 0 && in_array('status', $invalid_commands)) {
                $this->acl_alert = true;
                return new ViewModel(
                    array(
                        'acl_alert' => $this->acl_alert,
                        'invalid_commands' => 'status'
                    )
                );
            } else {
                try {
                    $this->bsock = $this->getServiceLocator()->get('director');
                    $result = $this->getScheduleModel()->getFullScheduleStatus($this->bsock);
                } finally {
                    if ($this->bsock) {
                        try {
                            $this->bsock->disconnect();
                        } catch (Exception $e) {
                            error_log($e->getMessage());
                        }
                    }
                }
            }
        } catch (Exception $e) {
            error_log($e->getMessage());
        }

        return new ViewModel(
            array(
                'result' => $result
            )
        );
    }

    /**
     * Details Action
     *
     * @return object
     */
    public function detailsAction()
    {
        $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']
                    )
                )
            );
        }

        $result = null;

        $schedulename = $this->params()->fromQuery('schedule');

        try {
            $module_config = $this->getServiceLocator()->get('ModuleManager')->getModule('Application')->getConfig();
            $invalid_commands = $this->CommandACLPlugin()->getInvalidCommands(
                $module_config['console_commands']['Schedule']['optional']
            );
            if (count($invalid_commands) > 0 && in_array('status', $invalid_commands)) {
                $this->acl_alert = true;
                return new ViewModel(
                    array(
                        'acl_alert' => $this->acl_alert,
                        'invalid_commands' => 'status'
                    )
                );
            } else {
                try {
                    $this->bsock = $this->getServiceLocator()->get('director');
                    $result = $this->getScheduleModel()->getScheduleStatus($this->bsock, $schedulename);
                } finally {
                    if ($this->bsock) {
                        try {
                            $this->bsock->disconnect();
                        } catch (Exception $e) {
                            error_log($e->getMessage());
                        }
                    }
                }
            }
        } catch (Exception $e) {
            error_log($e->getMessage());
        }

        return new ViewModel(
            array(
                'result' => $result
            )
        );
    }

    /**
     * Get Schedule Model
     *
     * @return object
     */
    public function getScheduleModel()
    {
        if (!$this->scheduleModel) {
            $sm = $this->getServiceLocator();
            $this->scheduleModel = $sm->get('Schedule\Model\ScheduleModel');
        }
        return $this->scheduleModel;
    }
}
