<?php
if (!defined('BASE_PATH')) { define('BASE_PATH', __DIR__ . '/..'); }
require_once BASE_PATH . '/database/connection.php';

function ensurePaymentMethods($pdo) {
    try {
        $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");
        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_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_token VARCHAR(255) 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 api_currency VARCHAR(10) NULL"); } catch (Throwable $__) {}
    } catch (Throwable $e) {}
}

try {
    $pdo = Database::getInstance()->getConnection();
    ensurePaymentMethods($pdo);
    $base = $argv[1] ?? 'https://api.key2pay.io/v1';
    $user = $argv[2] ?? '';
    $pass = $argv[3] ?? '';
    if (!$user || !$pass) { echo json_encode(['success'=>false,'message'=>'username/password requeridos']); exit; }
    $sel = $pdo->prepare("SELECT id FROM payment_methods WHERE provider_key='key2pay' AND is_active=1 AND (type='deposit' OR type='both') ORDER BY id DESC LIMIT 1");
    $sel->execute();
    $row = $sel->fetch();
    if ($row) {
        $upd = $pdo->prepare("UPDATE payment_methods SET api_base_url=?, api_username=?, api_password=? WHERE id=?");
        $upd->execute([$base, $user, $pass, (int)$row['id']]);
    } else {
        $ins = $pdo->prepare("INSERT INTO payment_methods (name, display_name, provider_key, api_category, category, type, is_active, api_base_url, api_username, api_password) VALUES ('Key2Pay','Key2Pay','key2pay','Payment Method','Payment Method','deposit',1, ?, ?, ?)");
        $ins->execute([$base, $user, $pass]);
    }
    echo json_encode(['success'=>true]);
} catch (Throwable $e) {
    echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}

