<?php
require_once '../../config/db.php';
// Admin Auth Check would go here

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    $data = json_decode(file_get_contents("php://input"));
    
    $provider = isset($data->provider) ? $data->provider : 'stripe';
    $api_key = isset($data->api_key) ? trim($data->api_key) : '';
    $secret_key = isset($data->secret_key) ? trim($data->secret_key) : '';
    $is_active = isset($data->is_active) ? (int)$data->is_active : 0;

    // Check if exists
    $stmt = $pdo->prepare("SELECT id FROM payment_gateways WHERE provider = ?");
    $stmt->execute([$provider]);
    
    if ($stmt->fetch()) {
        // Update
        $sql = "UPDATE payment_gateways SET api_key = ?, secret_key = ?, is_active = ? WHERE provider = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$api_key, $secret_key, $is_active, $provider]);
    } else {
        // Insert
        $sql = "INSERT INTO payment_gateways (provider, api_key, secret_key, is_active) VALUES (?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$provider, $api_key, $secret_key, $is_active]);
    }
    
    echo json_encode(['status' => 'success', 'message' => 'Payment settings updated']);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
