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

// CRITICAL FIX: Allow specific origin instead of wildcard for credential support
$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');

// Add cache control headers to prevent stale data
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

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';

// CRITICAL FIX: Enhanced authentication debugging
// Check for admin session first, add detailed debugging if authentication fails
if (!isUserAdmin()) {
    // Debug session state if authentication fails
    $debug = [
        'error' => 'Admin authentication failed',
        'session_id' => session_id(),
        'session_status' => session_status(),
        'admin_logged_in' => isset($_SESSION['admin_logged_in']) ? $_SESSION['admin_logged_in'] : 'not set',
        'session_variables' => array_keys($_SESSION),
    ];
    
    // Write to error log for server-side debugging
    error_log('Admin authentication failed: ' . json_encode($debug));
    
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'error' => 'Admin authentication required',
        'debug' => $debug
    ]);
    exit;
}

// 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['name']) || empty($input['type']) || !in_array($input['type'], ['crypto', 'bank', 'mobile', 'other'])) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => 'Invalid input. Name and type (crypto/bank/mobile/other) are required.'
    ]);
    exit;
}

try {
    // Insert new payment method
    $stmt = $pdo->prepare("
        INSERT INTO payment_methods (name, type, details)
        VALUES (:name, :type, :details)
    ");
    
    $stmt->execute([
        ':name' => trim($input['name']),
        ':type' => $input['type'],
        ':details' => trim($input['details'] ?? '')
    ]);
    
    // Get the newly created method
    $methodId = $pdo->lastInsertId();
    $stmt = $pdo->prepare("SELECT * FROM payment_methods WHERE id = ?");
    $stmt->execute([$methodId]);
    $method = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Log the action (support both 'details' or 'description' column)
    $logDetails = json_encode(['method_id' => $methodId, 'name' => $method['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' => 'add_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' => 'add_payment_method',
                ':details' => $logDetails
            ]);
        } catch (Exception $le2) {
            // Silently ignore logging failures
        }
    }
    
    echo json_encode([
        'success' => true,
        'method' => $method
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Failed to add payment method: ' . $e->getMessage()
    ]);
}
