<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit(0);

require_once '../config/database.php';

try {
    $pdo = getDBConnection();
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (isset($input['default_consultation_price'])) {
            $price = floatval($input['default_consultation_price']);
            
            // Update or insert the price setting
            $stmt = $pdo->prepare("
                INSERT INTO settings (id, default_consultation_price) 
                VALUES (1, ?) 
                ON DUPLICATE KEY UPDATE 
                default_consultation_price = VALUES(default_consultation_price),
                updated_at = NOW()
            ");
            
            $result = $stmt->execute([$price]);
            
            if ($result) {
                echo json_encode([
                    'success' => true,
                    'message' => 'Default consultation price updated successfully',
                    'default_consultation_price' => $price
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'error' => 'Failed to update price'
                ]);
            }
        } else {
            echo json_encode([
                'success' => false,
                'error' => 'default_consultation_price parameter required'
            ]);
        }
    } else {
        // GET request - return current settings
        $stmt = $pdo->prepare("SELECT default_consultation_price FROM settings WHERE id = 1");
        $stmt->execute();
        $settings = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($settings) {
            echo json_encode([
                'success' => true,
                'default_consultation_price' => $settings['default_consultation_price']
            ]);
        } else {
            echo json_encode([
                'success' => true,
                'default_consultation_price' => 500.0
            ]);
        }
    }
    
} catch (Exception $e) {
    error_log("Update Settings API Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'error' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
