<?php
require_once __DIR__ . '/../config/database.php';

function ensureSiteSettingsTable(PDO $db): void {
    $db->exec(
        "CREATE TABLE IF NOT EXISTS site_settings (
            setting_key VARCHAR(100) NOT NULL PRIMARY KEY,
            setting_value TEXT NOT NULL,
            updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )"
    );

    $defaults = [
        'contact_phone' => '+234 800 000 0000',
        'contact_phone_2' => '+234 800 111 1111',
        'contact_email' => 'info@stilesenergylpg.com',
        'contact_location' => 'Lagos, Nigeria',
        'contact_hours' => 'Mon - Sat, 7:00 AM - 8:00 PM',
    ];

    $stmt = $db->prepare(
        'INSERT INTO site_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_key = setting_key'
    );
    foreach ($defaults as $k => $v) {
        $stmt->execute([$k, $v]);
    }
}

function getSiteSettings(): array {
    static $cache = null;
    if ($cache !== null) return $cache;

    $defaults = [
        'contact_phone'    => '+234 800 000 0000',
        'contact_phone_2'  => '+234 800 111 1111',
        'contact_email'    => 'info@stilesenergylpg.com',
        'contact_location' => 'Lagos, Nigeria',
        'contact_hours'    => 'Mon - Sat, 7:00 AM - 8:00 PM',
    ];

    try {
        $db = getDB();
        ensureSiteSettingsTable($db);
        $rows = $db->query('SELECT setting_key, setting_value FROM site_settings')->fetchAll(PDO::FETCH_KEY_PAIR);
        if (!is_array($rows)) $rows = [];
        $cache = array_merge($defaults, $rows);
    } catch (Throwable $e) {
        // If table is not migrated yet, keep frontend working with defaults.
        $cache = $defaults;
    }

    return $cache;
}

function formatPhoneForTel(string $phone): string {
    $trim = trim($phone);
    $trim = preg_replace('/\s+/', '', $trim);
    if ($trim === null) $trim = '';
    return preg_replace('/[^\d\+]/', '', $trim) ?: '+2348000000000';
}
