<?php
session_start();
header('Content-Type: application/json');
if (!defined('BASE_PATH')) define('BASE_PATH', dirname(dirname(__DIR__, 2)));
require_once BASE_PATH . '/database/connection.php';
require_once BASE_PATH . '/api/payment_method/big4pay/Big4payClient.php';

try {
  $db = Database::getInstance();
  $pdo = $db->getConnection();
  $pdo->exec("CREATE TABLE IF NOT EXISTS integration_settings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    integration_name VARCHAR(64) NOT NULL,
    setting_key VARCHAR(64) NOT NULL,
    setting_value TEXT NULL,
    UNIQUE KEY uniq_integration_setting (integration_name, setting_key)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
  $client = new Big4payClient($pdo);

  if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $currency = trim($_POST['currency'] ?? '');
    $extra = [
      'ipn_url' => trim($_POST['ipn_url'] ?? ''),
      'success_url' => trim($_POST['success_url'] ?? ''),
      'cancel_url' => trim($_POST['cancel_url'] ?? '')
    ];
    $ok = $client->saveConfiguration($username, $password, $currency ?: null, $extra);
    echo json_encode(['success' => (bool)$ok]);
    exit;
  }

  $cfg = $client->getConfiguration();
  echo json_encode(['success' => true, 'config' => $cfg]);
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>