<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/database.php';

header('Content-Type: text/plain; charset=utf-8');
header('X-Robots-Tag: noindex, nofollow, noarchive');

try {
    $config = rsvp_config()['database'];
    $serverDsn = sprintf(
        'mysql:host=%s;charset=%s',
        $config['host'],
        $config['charset'] ?? 'utf8mb4'
    );
    $pdo = new PDO($serverDsn, $config['user'], $config['pass'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);
    $databaseName = str_replace('`', '``', $config['name']);
    $charset = preg_replace('/[^a-zA-Z0-9_]/', '', $config['charset'] ?? 'utf8mb4');
    $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$databaseName}` CHARACTER SET {$charset} COLLATE {$charset}_unicode_ci");
    $pdo->exec("USE `{$databaseName}`");
    $schema = file_get_contents(__DIR__ . '/database/schema.sql');
    if ($schema === false) {
        throw new RuntimeException('Could not read database/schema.sql');
    }
    $pdo->exec($schema);
    $columns = $pdo->query("SHOW COLUMNS FROM rsvp_responses")->fetchAll(PDO::FETCH_COLUMN);
    if (!in_array('notification_sent', $columns, true)) {
        $pdo->exec("ALTER TABLE rsvp_responses ADD notification_sent TINYINT(1) NOT NULL DEFAULT 0 AFTER email_error");
    }
    if (!in_array('notification_error', $columns, true)) {
        $pdo->exec("ALTER TABLE rsvp_responses ADD notification_error TEXT DEFAULT NULL AFTER notification_sent");
    }
    if (!in_array('category', $columns, true)) {
        $pdo->exec("ALTER TABLE rsvp_responses ADD category VARCHAR(60) NOT NULL DEFAULT '' AFTER phone");
    }
    echo "RSVP database table is ready.\n";
} catch (Throwable $exception) {
    http_response_code(500);
    echo "Install failed: " . $exception->getMessage() . "\n";
}
