<?php

namespace routes;

use classes\authentication;
use classes\backup_store;
use classes\response;
use classes\router;
use objects\logs_o;
use traits\route_t;

class moduleBackupsRoute
{
    use route_t;

    public function run(): void
    {
        global /** @var response $response */
        /** @var router $router */
        $router, $response;


        /** Modules > Backups > GET */
        $this->get('/modules/backup/backups', function () {
            global $response;
            $this->requirePermission('modules_backup_list');
            $user = (new authentication())->get_user();
            if ($user) {
                (new logs_o())->add('modules_backup', 'global', 1, $user->id, 'MODULES_BACKUP', 'Successfully fetched backup modules');
                $response->success(
                    (new backup_store())->listBackups()
                );
            } else {
                (new logs_o())->add('modules_backup', 'global', 1, 0, 'MODULES_BACKUP', 'No user found, or invalid session');
                $response->error('Invalid session', 400);
            }
        },
            [
                'modules_backup_list' => 'List all backup modules'
            ]
        );

        /** Modules > Backups > POST */
        $this->post('/modules/backup/backups', function () {
            global $response;
            $this->requirePermission('modules_backup_create');
            $user = (new authentication())->get_user();
            if ($user) {
                (new logs_o())->add('modules_backup', 'global', 1, $user->id, 'MODULES_BACKUP', 'Successfully created backup module');
                // Check if the request contains a name, and description parameter
                $name = $this->fromRequest('name');
                $description = $this->fromRequest('description');
                // Create the backup
                $response->success(
                    (new backup_store())->createBackup($name, $description)
                );
            } else {
                (new logs_o())->add('modules_backup', 'global', 1, 0, 'MODULES_BACKUP', 'No user found, or invalid session');
                $response->error('Invalid session', 400);
            }
        },
            [
                'modules_backup_create' => 'Create a backup module'
            ]
        );
    }
}