<?php

namespace Bdp\Modules\EventParticipants\Controllers;

use Bdp\Libs\FileAccess;
use function Bdp\Modules\EventParticipants\Views\registrationForm;

class ParticipationSignupController
{
	public static function saveRegistration(array $postedData) : string {
		global $dbHandler;

        $participation_types = ['other', 'participant', 'volunteer'];
		if (isset($postedData['foto']) && is_array($postedData['foto'])) {
			foreach ($postedData['foto'] as $fotoData) {
				$postedData['foto_' . $fotoData] = true;
			}
		}

		if ($postedData['badeerlaubnis'] == '') {
			$postedData['badeerlaubnis'] = 'complete';
		}
      	if (isset($postedData['zusatzbeitrag'])) {
			(int)$postedData['beitrag'] += (int)$postedData['zusatzbeitrag'];
          	unset($postedData['zusatzbeitrag']);
        }
        
		unset($postedData['foto']);
		unset($postedData['_dsgvo_accept']);
        $postedData['teilnahme'] = $participation_types[$postedData['gruppe_id']];
        unset($postedData['gruppe_id']);
		if (null == $dbHandler->insertRows(MainController::KOMPASS_EVENTS_PARTICIPANTS, $postedData)) {
            $errorPage = file_get_contents(dirname(__FILE__) . '/../Templates/Partials/Registration/error.webseite.php');
            $errorPage = sprintf($errorPage,
                $postedData['vorname']
            );

            wp_mail('thomas@pfadfinden-halle.de', 'Anmeldung für Pfingstlager fehlerhaft', print_r($postedData, true));

            return $errorPage;
        }


		$successMail = file_get_contents(dirname(__FILE__) . '/../Templates/Partials/Registration/done.email.php');
		$successMail = sprintf($successMail,
			$postedData['vorname'],
			\DateTime::createFromFormat('Y-m-d', $postedData['anreise'])->format('d.m.Y'),
			\DateTime::createFromFormat('Y-m-d', $postedData['abreise'])->format('d.m.Y'),
		ucfirst($postedData['essgewohnheit'])
		);


		$successPage = file_get_contents(dirname(__FILE__) . '/../Templates/Partials/Registration/done.webseite.php');
		$successPage = sprintf($successPage,
			$postedData['vorname'],
			\DateTime::createFromFormat('Y-m-d', $postedData['anreise'])->format('d.m.Y'),
			\DateTime::createFromFormat('Y-m-d', $postedData['abreise'])->format('d.m.Y'),
			ucfirst($postedData['essgewohnheit'])
		);

		$sent = wp_mail(
			$postedData['email_1'],
			'Anmeldung zum Pfingstlager 2024 in Taucha',
			$successMail,
			['Reply-To: thomas@pfadfinden-halle.de', 'Content-Type: text/html; charset=UTF-8']);


		if ('' !== $postedData['email_2']) {
			$sent = wp_mail(
				$postedData['email_2'],
				'Anmeldung zum Pfingstlager 2024 in Taucha',
				$successMail,
				['Reply-To: thomas@pfadfinden-halle.de', 'Content-Type: text/html; charset=UTF-8']);
		}

		return $successPage;
	}
}