<?php
declare(strict_types=1);

require dirname(__DIR__) . '/_bootstrap.php';

$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'astrotv.http02';
$projectRoot = dirname(__DIR__, 3);
$currentPath = parse_url($_SERVER['REQUEST_URI'] ?? '/new/contact/', PHP_URL_PATH) ?: '/new/contact/';
$canonicalUrl = sprintf('%s://%s%s', $scheme, $host, rtrim($currentPath, '/') . '/');

$contactForm = [
    'naam' => '',
    'email' => '',
    'telefoonnummer' => '',
    'datum' => '',
    'naam_medium' => '',
    'boxnummer' => '',
    'message' => '',
];
$contactErrors = [];
$contactSuccess = (string) astrotvV2FlashGet('contact_success', '');

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $contactForm['naam'] = trim((string) ($_POST['naam'] ?? ''));
    $contactForm['email'] = trim((string) ($_POST['email'] ?? ''));
    $contactForm['telefoonnummer'] = trim((string) ($_POST['telefoonnummer'] ?? ''));
    $contactForm['datum'] = trim((string) ($_POST['datum'] ?? ''));
    $contactForm['naam_medium'] = trim((string) ($_POST['naam_medium'] ?? ''));
    $contactForm['boxnummer'] = trim((string) ($_POST['boxnummer'] ?? ''));
    $contactForm['message'] = trim((string) ($_POST['body'] ?? $_POST['message'] ?? ''));
    $honeypot = trim((string) ($_POST['company'] ?? ''));
    $csrf = (string) ($_POST['_csrf'] ?? '');
    $ip = astrotvV2ClientIp();

    if (!hash_equals(astrotvV2CsrfToken(), $csrf)) {
        $contactErrors[] = 'Je sessie is verlopen. Ververs de pagina en probeer opnieuw.';
    }
    if ($honeypot !== '') {
        $contactErrors[] = 'Je bericht kon niet worden verstuurd.';
    }
    if (!filter_var($contactForm['email'], FILTER_VALIDATE_EMAIL)) {
        $contactErrors[] = 'Vul een geldig e-mailadres in.';
    }
    if ($contactForm['message'] === '' || mb_strlen($contactForm['message']) < 10) {
        $contactErrors[] = 'Vul een bericht van minimaal 10 tekens in.';
    }
    if (mb_strlen($contactForm['message']) > 5000) {
        $contactErrors[] = 'Je bericht is te lang.';
    }
    if (astrotvV2TurnstileEnabled()) {
        $turnstileToken = trim((string) ($_POST['cf-turnstile-response'] ?? ''));
        if ($turnstileToken === '' || !astrotvV2VerifyTurnstile($turnstileToken, $ip)) {
            $contactErrors[] = 'De anti-spam controle is mislukt. Probeer het opnieuw.';
        }
    }
    $throttleError = astrotvV2ContactThrottleCheck($projectRoot, $ip, $contactForm['email']);
    if ($throttleError !== null) {
        $contactErrors[] = $throttleError;
    }

    if ($contactErrors === []) {
        $sent = astrotvV2SendContactMail('klantenservice@astrotv.nl', $contactForm, $ip);
        astrotvV2ContactLog($projectRoot, [
            'time' => date('c'),
            'ip' => $ip,
            'email' => $contactForm['email'],
            'naam' => $contactForm['naam'],
            'telefoonnummer' => $contactForm['telefoonnummer'],
            'datum' => $contactForm['datum'],
            'naam_medium' => $contactForm['naam_medium'],
            'boxnummer' => $contactForm['boxnummer'],
            'message_length' => mb_strlen($contactForm['message']),
            'sent' => $sent,
        ]);

        if ($sent) {
            astrotvV2ContactThrottleStore($projectRoot, $ip, $contactForm['email']);
            astrotvV2FlashSet('contact_success', 'Je bericht is verstuurd. We nemen zo snel mogelijk contact met je op.');
            header('Location: /new/contact/');
            exit;
        }

        $contactErrors[] = 'Het bericht kon technisch niet worden verstuurd. Probeer het later opnieuw.';
    }
}

$page = [
    'title' => 'Contact | AstroTV',
    'description' => 'Neem contact op met AstroTV via de contactpagina met informatie, tarieven, app en beveiligd formulier.',
    'canonical_url' => $canonicalUrl,
    'body_class' => 'page-contact',
    'schema_json' => json_encode([
        '@context' => 'https://schema.org',
        '@graph' => [
            [
                '@type' => 'ContactPage',
                'name' => 'Contact',
                'url' => $canonicalUrl,
                'description' => 'Neem contact op met AstroTV via de contactpagina met informatie, tarieven, app en beveiligd formulier.',
            ],
            [
                '@type' => 'Organization',
                'name' => 'In Programme Sales BV',
                'address' => [
                    '@type' => 'PostalAddress',
                    'streetAddress' => 'Leyenseweg 113',
                    'postalCode' => '3721 BC',
                    'addressLocality' => 'Bilthoven',
                    'addressCountry' => 'NL',
                ],
                'telephone' => '0623851124',
            ],
        ],
    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
    'turnstile_site_key' => astrotvV2TurnstileEnabled() ? trim((string) astrotvV2EnvValue('TURNSTILE_SITE_KEY', '')) : '',
];
$view = $projectRoot . '/templates/pages/contact.php';

require $projectRoot . '/templates/layout.php';
