<?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'])) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => 'Payment method ID is required.'
    ]);
    exit;
}

try {
    // Start transaction
    $pdo->beginTransaction();
    
    // Get the method before deleting for logging
    $stmt = $pdo->prepare("SELECT * FROM payment_methods WHERE id = ?");
    $stmt->execute([$input['id']]);
    $method = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$method) {
        throw new Exception('Payment method not found.');
    }
    
    // Check if the method is in use via admin deposit addresses or user address requests
    $inUse = false;
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM admin_deposit_addresses WHERE payment_method_id = ?");
        $stmt->execute([$input['id']]);
        $inUse = ($stmt->fetch(PDO::FETCH_ASSOC)['count'] ?? 0) > 0;
    } catch (Exception $ignore) {
        // Table may not exist; ignore
    }
    if (!$inUse) {
        try {
            $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM user_address_requests WHERE payment_method_id = ?");
            $stmt->execute([$input['id']]);
            $inUse = ($stmt->fetch(PDO::FETCH_ASSOC)['count'] ?? 0) > 0;
        } catch (Exception $ignore) {
            // Table may not exist; ignore
        }
    }
    if ($inUse) {
        // Conflict: method has dependent records
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        http_response_code(409);
        echo json_encode([
            'success' => false,
            'error' => 'Cannot delete payment method with existing deposit addresses or requests. Remove dependencies first.'
        ]);
        exit;
    }
    
    // Delete the payment method
    $stmt = $pdo->prepare("DELETE FROM payment_methods WHERE id = ?");
    $stmt->execute([$input['id']]);
    
    if ($stmt->rowCount() === 0) {
        throw new Exception('No payment method found with the specified ID.');
    }
    
    // Log the action (support both 'details' or 'description' column)
    $logDetails = json_encode([
        'method_id' => $input['id'],
        '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' => 'delete_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' => 'delete_payment_method',
                ':details' => $logDetails
            ]);
        } catch (Exception $le2) {
            // Silently ignore logging failures
        }
    }
    
    // Commit transaction
    $pdo->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Payment method deleted successfully.'
    ]);
    
} catch (Exception $e) {
    // Rollback transaction on error
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Failed to delete payment method: ' . $e->getMessage()
    ]);
}
