<?php
require_once '../config/database.php';
header('Content-Type: application/json');

try {
    $pdo = getDBConnection();

    // Create settings table if it doesn't exist
    $pdo->exec("CREATE TABLE IF NOT EXISTS settings (
        id INT AUTO_INCREMENT PRIMARY KEY,
        setting_key VARCHAR(100) UNIQUE NOT NULL,
        setting_value TEXT,
        description TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )");

    // Check if settings table has data
    $stmt = $pdo->query("SELECT COUNT(*) FROM settings");
    if ($stmt->fetchColumn() == 0) {
        // Insert default settings
        $defaultSettings = [
            ['app_name', 'KSO Chandigarh', 'Application Name'],
            ['app_version', '1.0.0', 'Application Version'],
            ['admin_email', 'admin@ksochandigarh.org', 'Administrator Email'],
            ['timezone', 'Asia/Kolkata', 'Application Timezone'],
            ['maintenance_mode', '0', 'Maintenance Mode (0=Off, 1=On)']
        ];

        $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value, description) VALUES (?, ?, ?)");
        foreach ($defaultSettings as $setting) {
            $stmt->execute($setting);
        }
    }

    // Fetch all settings
    $stmt = $pdo->query("SELECT * FROM settings ORDER BY setting_key");
    $settings = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['success' => true, 'data' => $settings]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
