<?php
include 'renderer.php';

class Bulkmail extends Renderer {
    protected array $formFields = [
        ['label' => 'Betreff', 'type' => 'text', 'size' => 50, 'name' => 'subject', 'combine_with_next_line' => false, 'filter' => FILTER_SANITIZE_STRING, 'optional' => false],
        ['label' => 'Text', 'type' => 'textarea', 'name' => 'body', 'combine_with_next_line' => false, 'filter' => FILTER_UNSAFE_RAW, 'optional' => false, 'rows' => 20, 'cols' => '60'],
        ['label' => 'Signatur', 'type' => 'combobox', 'size' => 5, 'name' => 'signature', 'combine_with_next_line' => false, 
            'values' => ['Persönliche Signatur', 'Vorstandssignatur'], 
        ],
        ['label' => 'An normale Mitglieder', 'type' => 'checkbox', 'size' => 50, 'name' => 'custommembers', 'size' => 1, 'value' => 1, 'combine_with_next_line' => false],
        ['label' => 'An den Vorstand', 'type' => 'checkbox', 'size' => 50, 'name' => 'board', 'size' => 1, 'value' => 1, 'combine_with_next_line' => false],
    ];
    protected string $formSendButtonLabel = 'Email an ausgewählte Empfängergruppe senden';
    
    protected function formAction(): void {
        $this->sendEmail($this->generateSubject(), $this->generateBody(), $this->generateSignature(filter_input(INPUT_POST, 'signature')));
    }
    
    protected function generateSubject(): string {
        return filter_input(INPUT_POST, 'subject', FILTER_SANITIZE_STRING);
    }
    
    protected function generateBody(): string {
        return preg_replace('/(<script(.*)\/script>|<iframe(.*)\/iframe>)/', '', filter_input(INPUT_POST, 'body'));
    }
    
    protected function sendEmail(string $subject, string $body, string $signature): void {
        $mail = $this->initSmtpMailer();;
        $bccRecipients = $this->loadReceivers();
        $sendToCustomMembers = intval(filter_input(INPUT_POST, 'custommembers')) === 1;
        $sendToBoard = intval(filter_input(INPUT_POST, 'board')) === 1;
        $sendTo = [];
        try {
            $mail->setFrom('foerderverein-ajs@gmx.de', 'Förderverein der Steffi-Jones-Schule');
            $mail->addReplyTo('foerderverein-ajs@gmx.de', 'Förderverein der Steffi-Jones-Schule');
            $mail->addAddress('vorstand@fvajs.de', 'Vorstand des FVAJS');
            foreach ($bccRecipients as $recipient) {
                if (($sendToCustomMembers && $recipient['position'] === null)
                    || ($sendToBoard && $recipient['position'] !== null)) {
                    $mail->addBCC($recipient['email']);
                    $sendTo[] = $recipient['email'];
                } else {
                    var_dump($recipient['position']);
                }
            }
            $this->sendMail($mail, $subject, $body, $signature);
        } catch (Exception $e) {
            $this->templateName = 'error_smtp';
        }        
        $this->templateName = 'bulkmail_success';
        $this->content['recipients'] = implode('<br />', $sendTo);
    }
    
    protected function loadReceivers(): array {
        $query = 'SELECT c.first_name, c.last_name, c.email, c.salt, c.position_id
                FROM clubmember c 
                JOIN clubmember_status cs 
                ON cs.id = c.membership_status 
                WHERE cs.status_text = "Mitgliedschaft bestätigt"';
        $dbResult = mysqli_query($this->dbConnection, $query);
        $recipientsList = [];
        while ($row = mysqli_fetch_assoc($dbResult)) {
            $recipientsList[] = ['email' => $this->decode($row['email'], $row['salt']), 'position' => $row['position_id'] ];
        }
        return $recipientsList;
    }
}
