<?php
session_start();
require_once '../config/config.php';

header('Content-Type: application/json');

if (!isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

try {
    $conn = new PDO($dsn, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Get renewal settings
    $stmt = $conn->prepare("
        SELECT setting_key, value
        FROM system_settings
        WHERE category = 'renewal'
    ");
    $stmt->execute();
    $settings_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format settings into an associative array
    $settings = [];
    foreach ($settings_data as $setting) {
        $key = $setting['setting_key'];
        $value = $setting['value'];
        
        // Convert to appropriate type
        switch ($key) {
            case 'first_reminder':
            case 'second_reminder':
            case 'final_reminder':
            case 'grace_period':
                $settings[$key] = (int)$value;
                break;
            case 'renewal_fee':
            case 'late_fee':
                $settings[$key] = (float)$value;
                break;
            case 'auto_renewal':
                $settings[$key] = $value === '1' || $value === 'true';
                break;
            default:
                $settings[$key] = $value;
        }
    }
    
    // Set default values if settings don't exist
    if (empty($settings)) {
        $settings = [
            'first_reminder' => 60,
            'second_reminder' => 30,
            'final_reminder' => 7,
            'grace_period' => 30,
            'renewal_fee' => 1000,
            'late_fee' => 200,
            'auto_renewal' => false
        ];
        
        // Insert default settings
        $default_settings = [
            ['renewal', 'first_reminder', '60'],
            ['renewal', 'second_reminder', '30'],
            ['renewal', 'final_reminder', '7'],
            ['renewal', 'grace_period', '30'],
            ['renewal', 'renewal_fee', '1000'],
            ['renewal', 'late_fee', '200'],
            ['renewal', 'auto_renewal', '0']
        ];
        
        $stmt = $conn->prepare("
            INSERT INTO system_settings (category, setting_key, value, created_at, updated_at)
            VALUES (?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
        ");
        
        foreach ($default_settings as $setting) {
            $stmt->execute($setting);
        }
    }
    
    echo json_encode([
        'success' => true,
        'settings' => $settings
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
