<?php
/**
 * =====================================================================
 * HomeController PATCH — Newsletter Settings Addition
 * =====================================================================
 *
 * ADD the following code block to your existing HomeController.php
 * BEFORE the line that says: $csrfToken = generateCsrfToken();
 *
 * Also ADD 'newsletterSettings' to the $this->view() data array.
 *
 * SEE FULL INSTRUCTIONS BELOW.
 * =====================================================================
 */

// ═══════════════════════════════════════════════════════════════════
// STEP 1: Add this variable at the top with other initializations:
// ═══════════════════════════════════════════════════════════════════

$newsletterSettings = [];

// ═══════════════════════════════════════════════════════════════════
// STEP 2: Add this code block BEFORE the CSRF token generation line:
//         (add it just before: $csrfToken = generateCsrfToken();)
// ═══════════════════════════════════════════════════════════════════

// --- 12. Newsletter Settings ---
try {
    $nlStmt = $this->db->prepare(
        'SELECT `setting_key`, `setting_value` FROM `settings` WHERE `setting_key` LIKE :pattern'
    );
    $nlStmt->execute([':pattern' => 'newsletter_%']);
    $nlRows = $nlStmt->fetchAll(\PDO::FETCH_ASSOC);

    if (!empty($nlRows)) {
        foreach ($nlRows as $row) {
            if (!empty($row['setting_key'])) {
                $newsletterSettings[$row['setting_key']] = $row['setting_value'];
            }
        }
    }

    // Also check key_name/value columns
    $nlStmt2 = $this->db->prepare(
        'SELECT `key_name`, `value` FROM `settings` WHERE `key_name` LIKE :pattern'
    );
    $nlStmt2->execute([':pattern' => 'newsletter_%']);
    $nlRows2 = $nlStmt2->fetchAll(\PDO::FETCH_ASSOC);

    if (!empty($nlRows2)) {
        foreach ($nlRows2 as $row) {
            if (!empty($row['key_name'])) {
                if (!isset($newsletterSettings[$row['key_name']]) || $newsletterSettings[$row['key_name']] === '') {
                    $newsletterSettings[$row['key_name']] = $row['value'];
                }
            }
        }
    }
} catch (\Throwable $e) {
    error_log('Home newsletter settings error: ' . $e->getMessage());
}

// ═══════════════════════════════════════════════════════════════════
// STEP 3: Add 'newsletterSettings' to the view data array:
// ═══════════════════════════════════════════════════════════════════
// In the $this->view('home/index', [...]) call, add this line:
//
//   'newsletterSettings' => $newsletterSettings,
