<?php

namespace Trainingssystem\Module\AppAdminPanel;

use Trainingssystem\Module\AppAdminPanel\Query\AddTrainingAudioMappingQuery;
use Trainingssystem\Module\AppAdminPanel\Query\DeleteTrainingAudioMappingQuery;
use Trainingssystem\Module\AppAdminPanel\Query\GetAllTrainingAudioMappingsQuery;
use Trainingssystem\Module\AppAdminPanel\RequestHandler\AudioPostHandler;

class AppAdminPanelModule
{
    private AudioPostHandler $audioPostHandler;
    private GetAllTrainingAudioMappingsQuery $trainingAudioMappingsQuery;

    public function __construct()
    {
        $this->audioPostHandler = new AudioPostHandler(
            new AddTrainingAudioMappingQuery(),
            new DeleteTrainingAudioMappingQuery()
        );
        $this->trainingAudioMappingsQuery = new GetAllTrainingAudioMappingsQuery();
    }


    public function __invoke(): void
    {
        if(\Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("appAdmin")) {

            if (isset($_POST['submit'])) {
                $this->audioPostHandler->handle($_POST);
            }

            $twig = \Trainingssystem_Plugin_Twig::getInstance()->twig;

            $query_audio_args = array(
                'post_type'      => 'attachment',
                'post_mime_type' => 'audio',
                'posts_per_page' => - 1,
                'post_status'    => 'inherit',
                'orderby'        => 'title',
                'order'          => 'ASC',
            );
            $query_audio = new \WP_Query($query_audio_args);

            $audio_files = array();
            foreach($query_audio->posts as $a_post) {
                $audio_files[$a_post->ID] = $a_post;
            }

            $query_trainings_lektionen_args = array(
                'post_type'      => array('lektionen', 'trainings'),
                'posts_per_page' => - 1,
                'orderby'       => 'title',
                'order'          => 'ASC',
            );
            $query_trainings_lektionen = new \WP_Query($query_trainings_lektionen_args);

            $trainings_lektionen = array();
            foreach($query_trainings_lektionen->posts as $tl_post) {
                $trainings_lektionen[$tl_post->ID] = $tl_post;
            }
            
            echo $twig->render(
                'admin-backend/admin-backend-app-audio.html',
                [
                    'audio_files' => $audio_files,
                    'trainings_lektionen' => $trainings_lektionen,
                    'trainingAudioLinks' => $this->trainingAudioMappingsQuery->execute(),
                ]
            );
        } else {
            echo $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
        }
    }
}
