<?php
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
if (!defined('BASE_PATH')) define('BASE_PATH', dirname(__DIR__, 2));
require_once __DIR__ . '/../../database/connection.php';
$apiLoaderPath = BASE_PATH . '/api/shared/ApiLoader.php';
if (file_exists($apiLoaderPath)) { require_once $apiLoaderPath; }
$db = getDB();
$pdo = $db->getConnection();
$active = 'payments';

$pdo->exec("CREATE TABLE IF NOT EXISTS payment_methods (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(64) NOT NULL,
    display_name VARCHAR(128) NOT NULL,
    provider_key VARCHAR(64) NOT NULL,
    api_category VARCHAR(64) NOT NULL DEFAULT 'Payment Method',
    category VARCHAR(32) NOT NULL,
    type ENUM('deposit','withdraw','both') NOT NULL DEFAULT 'deposit',
    logo_path VARCHAR(255) NULL,
    config JSON NULL,
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$hasLogoPath = $pdo->query("SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'payment_methods' AND COLUMN_NAME = 'logo_path'")->fetchColumn();
if ((int)$hasLogoPath === 0) {
    $pdo->exec("ALTER TABLE payment_methods ADD COLUMN logo_path VARCHAR(255) NULL AFTER type");
}
$hasApiCat = $pdo->query("SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'payment_methods' AND COLUMN_NAME = 'api_category'")->fetchColumn();
if ((int)$hasApiCat === 0) {
    $pdo->exec("ALTER TABLE payment_methods ADD COLUMN api_category VARCHAR(64) NOT NULL DEFAULT 'Payment Method' AFTER provider_key");
}

$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $display = trim($_POST['display_name'] ?? $name);
    $provider = strtolower(trim($_POST['controller_key'] ?? ($_POST['provider_key'] ?? '')));
    $apiCategory = trim($_POST['api_category'] ?? 'Payment Method');
    $category = trim($_POST['category'] ?? 'Payment Method');
    $type = trim($_POST['type'] ?? 'deposit');
    $config = null;
    $activeFlag = isset($_POST['is_active']) ? 1 : 0;
    $logoPath = null;
    $supportedCurrencies = trim($_POST['supported_currencies'] ?? '');
    if (!empty($_FILES['logo']['name'])) {
        $uploadDir = BASE_PATH . '/public/uploads/';
        if (!is_dir($uploadDir)) { @mkdir($uploadDir, 0777, true); }
        $fname = 'pm_' . time() . '_' . preg_replace('/[^a-z0-9\._-]/i','', $_FILES['logo']['name']);
        $dest = $uploadDir . $fname;
        if (is_uploaded_file($_FILES['logo']['tmp_name'])) {
            @move_uploaded_file($_FILES['logo']['tmp_name'], $dest);
            $logoPath = '/public/uploads/' . $fname;
        }
    }
    try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN api_group VARCHAR(64) NULL"); } catch (Throwable $__) {}
    try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN api_key VARCHAR(64) NULL"); } catch (Throwable $__) {}
    try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN api_endpoint VARCHAR(255) NULL"); } catch (Throwable $__) {}
    try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN handler_class VARCHAR(64) NULL"); } catch (Throwable $__) {}
    try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN api_username VARCHAR(128) NULL"); } catch (Throwable $__) {}
    try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN api_password VARCHAR(128) NULL"); } catch (Throwable $__) {}
    try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN api_ipn_url VARCHAR(255) NULL"); } catch (Throwable $__) {}
    try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN api_success_url VARCHAR(255) NULL"); } catch (Throwable $__) {}
    try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN api_cancel_url VARCHAR(255) NULL"); } catch (Throwable $__) {}
    try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN supported_currencies VARCHAR(128) NULL"); } catch (Throwable $__) {}
    try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN checkout_redirect_url VARCHAR(255) NULL"); } catch (Throwable $__) {}
    $apiGroup = 'payment_method';
    $apiKey = strtolower($provider);
    $apiEndpoint = '/api/payment_method/' . $apiKey . '/payment_method.php';
    $handlerClass = null;
    $integrations = class_exists('ApiLoader') ? ApiLoader::getAvailableIntegrations() : [];
    if (isset($integrations[$apiKey]['class'])) { $handlerClass = $integrations[$apiKey]['class']; }
    $apiUsername = null; $apiPassword = null; $apiBaseUrl = null; $apiCurrency = null;
    $minAmount = isset($_POST['min_amount']) ? (float)$_POST['min_amount'] : null;
    $maxAmount = isset($_POST['max_amount']) ? (float)$_POST['max_amount'] : null;
    $etaLabel = trim($_POST['eta_label'] ?? '');
    if ($provider === 'big4pay') {
        $apiUsername = trim($_POST['big4pay_username'] ?? '');
        $apiPassword = trim($_POST['big4pay_password'] ?? '');
    } elseif ($provider === 'key2pay') {
        $apiBaseUrl = trim($_POST['key2pay_api_base_url'] ?? '');
        $apiUsername = trim($_POST['key2pay_username'] ?? '');
        $apiPassword = trim($_POST['key2pay_password'] ?? '');
        $apiCurrency = trim($_POST['key2pay_currency'] ?? 'USD');
    }
    $checkoutRedirect = trim($_POST['checkout_redirect_url'] ?? '');
    $mode = trim($_POST['mode'] ?? 'create');
    $pmId = (int)($_POST['id'] ?? 0);
    // Autoconfigurar URL de checkout por proveedor si no fue provista
    if ($checkoutRedirect === '') {
        $scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
        $origin = $scheme . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
        $rootPath = rtrim(dirname(dirname($_SERVER['SCRIPT_NAME'])), '/');
        if (strtolower($provider) === 'key2pay') {
            $checkoutRedirect = $origin . $rootPath . '/modules/checkout/key2pay/index.php';
        } elseif (strtolower($provider) === 'big4pay') {
            $checkoutRedirect = $origin . $rootPath . '/modules/checkout/big4pay/index.php';
        }
    }
    if ($mode === 'toggle_active' && $pmId > 0) {
        $toActive = isset($_POST['is_active']) ? (int)$_POST['is_active'] : 0;
        $stmt = $pdo->prepare("UPDATE payment_methods SET is_active=? WHERE id=?");
        $stmt->execute([$toActive, $pmId]);
        $message = $toActive ? 'Método activado' : 'Método desactivado';
    } elseif ($mode === 'delete' && $pmId > 0) {
        $stmt = $pdo->prepare("DELETE FROM payment_methods WHERE id = ? LIMIT 1");
        $stmt->execute([$pmId]);
        $message = 'Método eliminado';
    } elseif ($mode === 'update' && $pmId > 0) {
        try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN api_base_url VARCHAR(255) NULL"); } catch (Throwable $__) {}
        try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN api_currency VARCHAR(10) NULL"); } catch (Throwable $__) {}
        $stmt = $pdo->prepare("UPDATE payment_methods SET name=?, display_name=?, provider_key=?, api_category=?, category=?, type=?, logo_path=COALESCE(?, logo_path), is_active=?, api_group=?, api_key=?, api_endpoint=?, handler_class=?, api_username=COALESCE(?, api_username), api_password=COALESCE(?, api_password), api_base_url=COALESCE(?, api_base_url), api_currency=COALESCE(?, api_currency), min_amount=COALESCE(?, min_amount), max_amount=COALESCE(?, max_amount), eta_label=COALESCE(?, eta_label), supported_currencies=?, checkout_redirect_url=COALESCE(?, checkout_redirect_url) WHERE id=?");
        $stmt->execute([$name, $display, $provider, $apiCategory, $category, $type, $logoPath, $activeFlag, $apiGroup, $apiKey, $apiEndpoint, $handlerClass, $apiUsername, $apiPassword, $apiBaseUrl, $apiCurrency, $minAmount, $maxAmount, ($etaLabel!==''?$etaLabel:null), $supportedCurrencies, ($checkoutRedirect!==''?$checkoutRedirect:null), $pmId]);
    } else {
        try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN api_base_url VARCHAR(255) NULL"); } catch (Throwable $__) {}
        try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN api_currency VARCHAR(10) NULL"); } catch (Throwable $__) {}
        $stmt = $pdo->prepare("INSERT INTO payment_methods (name, display_name, provider_key, api_category, category, type, logo_path, config, is_active, api_group, api_key, api_endpoint, handler_class, api_username, api_password, api_base_url, api_currency, min_amount, max_amount, eta_label, supported_currencies, checkout_redirect_url) VALUES (?,?,?,?,?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$name, $display, $provider, $apiCategory, $category, $type, $logoPath, $config, $activeFlag, $apiGroup, $apiKey, $apiEndpoint, $handlerClass, $apiUsername, $apiPassword, $apiBaseUrl, $apiCurrency, $minAmount, $maxAmount, ($etaLabel!==''?$etaLabel:null), $supportedCurrencies, ($checkoutRedirect!==''?$checkoutRedirect:null)]);
    }
    // Integrar credenciales directamente con la API de Big4pay si aplica
    // Las credenciales se guardan en payment_methods; no usar integration_settings para métodos de pago
    if ($mode!=='delete') { $message = ($mode==='update') ? 'Método actualizado' : 'Método agregado'; }
}

$rows = $pdo->query("SELECT * FROM payment_methods ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
$availableIntegrations = class_exists('ApiLoader') ? ApiLoader::getAvailableIntegrations() : [
    'big4pay' => ['name' => 'Big4pay','description' => 'Procesador de pagos','class' => 'Big4payClient'],
    'voiso' => ['name' => 'Voiso','description' => 'Sistema de llamadas','class' => 'VoisoClient']
];
$page_title = 'Payment Methods';
$content_file = __DIR__ . '/payments_content.php';
include __DIR__ . '/../shared/layout.php';
$pdo->exec("ALTER TABLE payment_methods MODIFY COLUMN type ENUM('deposit','withdraw','both') NOT NULL DEFAULT 'deposit'");
$pdo->exec("CREATE TABLE IF NOT EXISTS payment_methods (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(64) NOT NULL,
    display_name VARCHAR(128) NOT NULL,
    provider_key VARCHAR(64) NOT NULL,
    api_category VARCHAR(64) NOT NULL DEFAULT 'Payment Method',
    category VARCHAR(32) NOT NULL,
    type ENUM('deposit','withdraw','both') NOT NULL DEFAULT 'deposit',
    logo_path VARCHAR(255) NULL,
    config JSON NULL,
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    min_amount DECIMAL(18,6) NULL,
    max_amount DECIMAL(18,6) NULL,
    eta_label VARCHAR(64) NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN min_amount DECIMAL(18,6) NULL"); } catch (Throwable $__) {}
try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN max_amount DECIMAL(18,6) NULL"); } catch (Throwable $__) {}
try { $pdo->exec("ALTER TABLE payment_methods ADD COLUMN eta_label VARCHAR(64) NULL"); } catch (Throwable $__) {}
