<?php
include 'renderer.php';
require_once 'vendor/autoload.php';

use setasign\Fpdi\Fpdi;

class Membership extends Renderer {
    protected array $formFields = [
        ['label' => 'Vorname', 'type' => 'text', 'size' => 50, 'name' => 'firstname', 'combine_with_next_line' => false],
        ['label' => 'Nachname', 'type' => 'text', 'size' => 50, 'name' => 'lastname', 'combine_with_next_line' => false],
        ['label' => 'Straße (mit Hausnummer)', 'type' => 'text', 'size' => 50, 'name' => 'street', 'combine_with_next_line' => false],
        ['label' => 'Plz', 'type' => 'text', 'size' => 5, 'name' => 'zip', 'combine_with_next_line' => true],
        ['label' => 'Ort', 'type' => 'text', 'size' => 40, 'name' => 'town', 'combine_with_next_line' => false],
        ['label' => 'Geburtsdatum', 'type' => 'date', 'size' => 50, 'name' => 'birthdate', 'combine_with_next_line' => false],
        ['label' => 'Telefon-Nr.', 'type' => 'text', 'size' => 50, 'name' => 'phone', 'combine_with_next_line' => false],
        ['label' => 'Email-Adresse', 'type' => 'email', 'size' => 50, 'name' => 'email', 'combine_with_next_line' => false],
        ['label' => 'Name des Kindes (Optional)', 'type' => 'text', 'size' => 50, 'name' => 'childname', 'combine_with_next_line' => false],
        ['label' => 'Straße des Kindes (Optional)', 'type' => 'text', 'size' => 50, 'name' => 'childstreet', 'combine_with_next_line' => false],
        ['label' => 'Gewählter Jahresbeitrag', 'type' => 'combobox', 'size' => 50, 'name' => 'payheight', 'combine_with_next_line' => false,
            'values' => ['12 €', '25 €', '50 €', '60 €', '100 €', 'Selbst wählen'], 'default' => '25 €',],
        ['label' => 'Höhe des freien Beitrags (Optional)', 'type' => 'number', 'size' => 50, 'name' => 'freepayheight', 'value' => 0, 'combine_with_next_line' => false],
        ['label' => 'Ich stimme der elektronischen Verarbeitung und Speicherung meiner Daten zu', 'type' => 'checkbox', 'size' => 1, 'name' => 'accept_electronical_usage', 'value' => 1],
        ['type' => 'spacer', 'value' => ''],
        ['type' => 'infotext', 'label' => '<h3>(Optional) Bankeinzugsinformationen</h3>'],
        ['label' => 'Geldinstitut', 'type' => 'text', 'size' => 50, 'name' => 'bankname', 'combine_with_next_line' => false],
        ['label' => 'IBAN', 'type' => 'text', 'size' => 50, 'name' => 'iban', 'combine_with_next_line' => false],
        ['label' => 'BIC', 'type' => 'text', 'size' => 50, 'name' => 'bic', 'combine_with_next_line' => false],
        ['label' => 'Kontoinhaber', 'type' => 'text', 'size' => 50, 'name' => 'accountmembername', 'combine_with_next_line' => false],
    ];
    protected string $formSendButtonLabel = 'Mitgliedschaftsantrag vorausgefüllt beantragen';
    
    protected function formAction(): void {
        $formData['firstname'] = trim(filter_input(INPUT_POST, 'firstname', FILTER_SANITIZE_STRING));
        $formData['lastname'] = trim(filter_input(INPUT_POST, 'lastname', FILTER_SANITIZE_STRING));
        $formData['street'] = trim(filter_input(INPUT_POST, 'street', FILTER_SANITIZE_STRING));
        $formData['zip'] = trim(filter_input(INPUT_POST, 'zip', FILTER_SANITIZE_STRING));
        $formData['town'] = trim(filter_input(INPUT_POST, 'town', FILTER_SANITIZE_STRING));
        $formData['birthDate'] = trim(filter_input(INPUT_POST, 'birthdate', FILTER_SANITIZE_STRING));
        $formData['phoneNumber'] = trim(filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_STRING));
        $formData['email'] = trim(filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING));
        $formData['childName'] = trim(filter_input(INPUT_POST, 'childname', FILTER_SANITIZE_STRING));
        $formData['childStreet'] = trim(filter_input(INPUT_POST, 'childstreet', FILTER_SANITIZE_STRING));
        $formData['payHeight'] = trim(filter_input(INPUT_POST, 'payheight', FILTER_SANITIZE_STRING));
        $formData['bankname'] = trim(filter_input(INPUT_POST, 'bankname', FILTER_SANITIZE_STRING));
        $formData['iban'] = trim(filter_input(INPUT_POST, 'iban', FILTER_SANITIZE_STRING));
        $formData['bic'] = trim(filter_input(INPUT_POST, 'bic', FILTER_SANITIZE_STRING));
        $formData['agreedElectronicalHandling'] = intval(filter_input(INPUT_POST, 'accept_electronical_usage', FILTER_SANITIZE_NUMBER_INT));
        $formData['accountmembername'] = trim(filter_input(INPUT_POST, 'accountmembername', FILTER_SANITIZE_STRING));
        $this->checkFormData($formData);
        $this->saveNewMember($formData);
        $this->sendEmail($formData);
    }
    
    protected function checkFormData(array $formData): void {
         if ($formData['payHeight'] === 'Selbst wählen') {
            $formData['payHeight'] = filter_input(INPUT_POST, 'freepayheight', FILTER_SANITIZE_NUMBER_INT);
        }
        if (!preg_match('/^([0-9]{5})$/', $formData['zip'])) {
            $this->errors['zip'] = 'Die Postleitzahl ist nicht korrekt';
        }
        if (!preg_match('/^((19|20)([0-9]){2}-[0-9]{2})-([0-9]{2})$/', $formData['birthDate']) || (DateTimeImmutable::createFromFormat('Y-m-d', $formData['birthDate']))->getTimestamp() > time()) {
            $this->errors['birthdate'] = 'Das eingegebene Geburtsdatum ist nicht korrekt';
        }
        if (!preg_match('/^0([0-9]{2,6})([ ]{0,1})([-\/]{0,1})([ ]{0,1})([0-9 ]{4,25})$/', $formData['phoneNumber'])) {
            $this->errors['phone'] = 'Die Telefonnummer ist nicht korrekt';
        }
        if (!filter_var($formData['email'], FILTER_VALIDATE_EMAIL)) {
            $this->errors['email'] = 'Die Email-Adresse ist inkorrekt';
        }
        if ($formData['agreedElectronicalHandling'] !== 1) {
            $this->errors['accept_electronical_usage'] = 'Für die Online-Registrierung müssen Sie der elektronischen Verarbeitung zustimmen';
        }
    }
   
    protected function saveNewMember(array $formData): void {
        $salt = $this->generateRandomString();
        $query = sprintf("INSERT INTO ffajs.clubmember( "
             . "        first_name, last_name, street, zip, town,  "
             . "        birthdate, phone, email, child_name, child_street,  "
             . "        subscription, bank_name, iban, bic, account_member_name,  "
             . "        membership_status, salt) "
             . "VALUES('%s', '%s', '%s', '%s', '%s',  "
             . "        '%s', '%s', '%s', '%s', '%s',  "
             . "        '%s', '%s', '%s', '%s', '%s', "
             . "        %d, '%s') ",
        $this->getDbEncryptedValueIfNeeded($formData, 'firstname', $salt), 
        $this->getDbEncryptedValueIfNeeded($formData, 'lastname', $salt),
        $this->getDbEncryptedValueIfNeeded($formData, 'street', $salt),
        $this->getDbEncryptedValueIfNeeded($formData, 'zip', $salt),
        $this->getDbEncryptedValueIfNeeded($formData, 'town', $salt),
        $this->getDbEncryptedValueIfNeeded($formData, 'birthDate', $salt),
        $this->getDbEncryptedValueIfNeeded($formData, 'phoneNumber', $salt),
        $this->getDbEncryptedValueIfNeeded($formData, 'email', $salt),
        $this->getDbEncryptedValueIfNeeded($formData, 'childName', $salt),
        $this->getDbEncryptedValueIfNeeded($formData, 'childStreet', $salt),
        $this->getDbEncryptedValueIfNeeded($formData, 'payHeight', $salt),
        $this->getDbEncryptedValueIfNeeded($formData, 'bankname', $salt),
        $this->getDbEncryptedValueIfNeeded($formData, 'iban', $salt),
        $this->getDbEncryptedValueIfNeeded($formData, 'bic', $salt),
        $this->getDbEncryptedValueIfNeeded($formData, 'accountmembername', $salt),
            1,
            $salt);
        mysqli_query($this->dbConnection, $query);
    }
   
    protected function sendEmail(array $formData): void {
        error_reporting(E_ALL);
        ini_set('display_errors', 1);
        $noForm = count($this->errors) === 0;
        if ($noForm) {
            $data = ['Vorname' => $formData['firstname'], 'Nachname' => $formData['lastname'], 'Strasse' => $formData['street'], 'Ort' => $formData['zip'] . ' ' . $formData['town'], 
                'Geburtstag' => $formData['birthDate'], 'Telefon' => $formData['phoneNumber'], 'Email' => $formData['email'], 
                'Name des Kindes' => $formData['childName'], 'Straße des Kindes' => $formData['childStreet'],
                'Gewünschter Mitgliedsbeitrag' => $formData['payHeight'], 'Geldinstitut' => $formData['bankname'], 
                'IBAN' => $formData['iban'], 'BIC' => $formData['bic'], 'Kontoinhaber' => $formData['accountmembername'], 
                'Elektronischer Verarbeitung zugestimmg' => $formData['agreedElectronicalHandling']
            ];
            $mail = $this->initSmtpMailer();
            $mail->setFrom('foerderverein-ajs@gmx.de');
            $mail->addReplyTo($formData['email'], $formData['firstname'] . ' ' . $formData['lastname']);
            $mail->addAddress('foerderverein-ajs@gmx.de', 'Vorstand Förderverein AJS');
            $message = '';
            foreach ($data as $field => $value) {
                $message .= $field . ': ' . $value . "\n";
            }
            $attachment = [
                'Mitgliedsantrag.pdf' => ['content' => $this->createPdf($formData), 'type' => 'application/pdf']
            ];
            $this->sendMail($mail, 'Mitgliedsantrag', $message, '', $attachment);
            $this->templateName = 'membership_success';
        }
    }
   
    protected function createPdf(array $formData): string
    {
        $pdf = new Fpdi();
        $pdf->AddFont('DejaVuSans', '', 'DejaVuSans.php');
        $pdf->AddFont('DejaVuSans Bold', '', 'DejaVuSans-Bold.php');
        $pdf->AddPage('P', 'A4');
        $pdf->SetMargins(20, 20, 20, 20); 
        $pdf->SetFont('DejaVuSans Bold', '', 15);
        $pdf->Cell(0, 2, utf8_decode('Verein der Freunde und Förderer'), 0, 1, 'C');
        $pdf->Cell(0, 10, utf8_decode('der August-Jaspert-Schule e.V.'), 0, 1, 'C');
        $pdf->SetFont('DejaVuSans Bold', '', 13);
        $pdf->Cell(0, 13.5, utf8_decode('Beitrittserklärung'), 0, 1, 'L');
        $pdf->setFont('DejaVuSans', '', 12);
        $pdf->Cell(0, 12, utf8_decode('Folgende Felder sind Pflicht und müssen ausgefüllt werden'), 0, 1, 'L');
        $newFields = [
            'Name' => $formData['lastname'],
            'Vorname' => $formData['firstname'],
            'Straße' => $formData['street'],
            'PLZ und Wohnort' => $formData['zip'] . ' ' . $formData['town'],
            'Telefon' => $formData['phoneNumber'],
            'Email-Adresse' => $formData['email'],
            'Geburtsdatum' => $formData['birthDate'],
            'Gewünschter Beitrag' => str_replace('€', '', $formData['payHeight']) . ' EUR',
        ];
        foreach ($newFields as $field => $value) {
            $pdf->Cell(60, 5, utf8_decode($field), 0);
            $pdf->Cell(0, 5, utf8_decode($value), 0, 1);
        }
        $pdf->Ln(5);
        $pdf->MultiCell(0, 5, utf8_decode('Ich erkläre hiermit, dass ich die Satzung des Vereins erhalten habe und akzeptiere und trete dem Verein bei.'));
        $pdf->Ln(14);
        $lineStartX = $pdf->GetX();
        $pdf->Cell(0, 0, '', 'T'); 
        $lineEndX = $pdf->GetX();
        $pdf->SetFont('DejaVuSans', '', 10);
        $pdf->Ln(1);
        $pdf->Cell(60, 2, utf8_decode('Ort, Datum'), 0);
        $pdf->Cell(0, 2, utf8_decode('Unterschrift'), 0);
        $pdf->Ln(15);
        $pdf->SetFont('DejaVuSans', '', 12);
        $pdf->MultiCell(0, 5, utf8_decode('Wenn Sie die Abbuchung per SEPA-Mandat wünschen, füllen Sie bitte folgende Felder aus:'));
        $pdf->Ln(5);
        $newFields = [
            'Geldinstitut' => $formData['bankname'],
            'IBAN' => $formData['iban'],
            'BIC' => $formData['bic'],
            'Kontoinhaber' => $formData['accountmembername'],
        ];
        foreach ($newFields as $field => $value) {
            $pdf->Cell(60, 5, utf8_decode($field), 0);
            $pdf->Cell(0, 5, utf8_decode($value), 0, 1);
        }
        $pdf->Ln(5);
        $pdf->MultiCell(0, 5, utf8_decode('Mir ist bekannt, das ich diese Einzugsermächtigung jederzeit widerrufen kann und sie mit Beendigung meiner Mitgliedschaft automatisch erlischt.'));
        $pdf->Ln(14);
        $lineStartX = $pdf->GetX();
        $pdf->Cell(0, 0, '', 'T'); 
        $lineEndX = $pdf->GetX();
        $pdf->SetFont('DejaVuSans', '', 10);
        $pdf->Ln(1);
        $pdf->Cell(60, 2, utf8_decode('Ort, Datum'), 0);
        $pdf->Cell(0, 2, utf8_decode('Unterschrift'), 0);
        return $pdf->Output('S', '');
    }
   
}
