<?php
header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// CRITICAL: Allow origin with credentials
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';

// Require admin authentication
requireAdmin(true);

// Include dependencies after authentication check
require_once 'config.php';
require_once 'db.php';

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

// Validate input
if (empty($input['id']) || empty($input['name']) || empty($input['type']) || !in_array($input['type'], ['crypto', 'bank', 'mobile', 'other'])) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => 'Invalid input. ID, name and valid type (crypto/bank/mobile/other) are required.'
    ]);
    exit;
}

try {
    // Check if payment method exists
    $stmt = $pdo->prepare("SELECT * FROM payment_methods WHERE id = ?");
    $stmt->execute([$input['id']]);
    $existingMethod = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$existingMethod) {
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'error' => 'Payment method not found.'
        ]);
        exit;
    }
    
    // Update payment method
    $stmt = $pdo->prepare("
        UPDATE payment_methods 
        SET name = :name, type = :type, details = :details
        WHERE id = :id
    ");
    
    $stmt->execute([
        ':id' => $input['id'],
        ':name' => trim($input['name']),
        ':type' => $input['type'],
        ':details' => trim($input['details'] ?? '')
    ]);
    
    // Get the updated method
    $stmt = $pdo->prepare("SELECT * FROM payment_methods WHERE id = ?");
    $stmt->execute([$input['id']]);
    $updatedMethod = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Log the action (support both 'details' or 'description' column)
    $logDetails = json_encode([
        'method_id' => $input['id'],
        'old_name' => $existingMethod['name'],
        'new_name' => $updatedMethod['name']
    ]);
    try {
        $stmt = $pdo->prepare("
            INSERT INTO admin_logs (admin_id, action, details)
            VALUES (:admin_id, :action, :details)
        ");
        $stmt->execute([
            ':admin_id' => isset($_SESSION['admin_id']) ? $_SESSION['admin_id'] : 1,
            ':action' => 'update_payment_method',
            ':details' => $logDetails
        ]);
    } catch (Exception $le) {
        try {
            $stmt = $pdo->prepare("
                INSERT INTO admin_logs (admin_id, action, description)
                VALUES (:admin_id, :action, :details)
            ");
            $stmt->execute([
                ':admin_id' => isset($_SESSION['admin_id']) ? $_SESSION['admin_id'] : 1,
                ':action' => 'update_payment_method',
                ':details' => $logDetails
            ]);
        } catch (Exception $le2) {
            // Silently ignore logging failures to avoid breaking main flow
        }
    }
    
    echo json_encode([
        'success' => true,
        'method' => $updatedMethod
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Failed to update payment method: ' . $e->getMessage()
    ]);
}
