<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_admin.php';
require_once __DIR__ . '/../../includes/audit.php';
require_once __DIR__ . '/../../includes/upload.php';

apply_cors();
$admin = require_super_admin(); // secrets — SUPER_ADMIN only
$pdo = getDbConnection();
$method = $_SERVER['REQUEST_METHOD'];

// GET  /payment_gateways.php          -> list all (secrets masked)
// PUT  /payment_gateways.php?id=1     -> update config (multipart if QR image included)
// PATCH /payment_gateways.php?id=1&action=status -> activate/deactivate (only one active at a time recommended)

function mask_secret(string $value): string
{
    if ($value === '') return '';
    return str_repeat('*', max(0, strlen($value) - 4)) . substr($value, -4);
}

if ($method === 'GET') {
    $stmt = $pdo->query('SELECT * FROM payment_gateways ORDER BY id ASC');
    $rows = $stmt->fetchAll();
    foreach ($rows as &$row) {
        $row['key_secret'] = mask_secret($row['key_secret']);
        $row['salt_key'] = mask_secret($row['salt_key']);
        $row['webhook_secret'] = mask_secret($row['webhook_secret']);
    }
    send_success(['gateways' => $rows]);
}

if ($method === 'PUT' && isset($_GET['id'])) {
    $id = (int) $_GET['id'];
    $isMultipart = str_starts_with($_SERVER['CONTENT_TYPE'] ?? '', 'multipart/form-data');
    $input = $isMultipart ? $_POST : get_json_input();

    $qrUrl = null;
    if ($isMultipart && isset($_FILES['qr_image']) && $_FILES['qr_image']['size'] > 0) {
        $qrUrl = handle_file_upload('qr_image', 'qr', ALLOWED_IMAGE_TYPES);
    }

    $allowed = ['mode', 'key_id', 'key_secret', 'webhook_secret', 'merchant_id', 'salt_key',
                'salt_index', 'upi_id', 'upi_name', 'instructions'];
    $fields = [];
    $params = [':id' => $id];
    foreach ($allowed as $f) {
        // Skip masked placeholder values (client sends back masked string unchanged)
        if (isset($input[$f]) && strpos((string) $input[$f], '*') === false) {
            $fields[] = "$f = :$f";
            $params[":$f"] = $input[$f];
        }
    }
    if ($qrUrl !== null) {
        $fields[] = 'qr_image_url = :qr_url';
        $params[':qr_url'] = $qrUrl;
    }
    if (empty($fields)) send_error('No fields to update.', 422);

    $stmt = $pdo->prepare('UPDATE payment_gateways SET ' . implode(', ', $fields) . ' WHERE id = :id');
    $stmt->execute($params);

    log_admin_action($admin['email'], 'UPDATE_PAYMENT_GATEWAY', 'gateway_id:' . $id, 'Config updated (secrets not logged)');
    send_success(null, 'Gateway configuration updated.');
}

if ($method === 'PATCH' && isset($_GET['id']) && ($_GET['action'] ?? '') === 'status') {
    $id = (int) $_GET['id'];
    $input = get_json_input();
    require_fields($input, ['is_active']);

    $stmt = $pdo->prepare('UPDATE payment_gateways SET is_active = :active WHERE id = :id');
    $stmt->execute([':active' => $input['is_active'] ? 1 : 0, ':id' => $id]);

    log_admin_action($admin['email'], 'TOGGLE_PAYMENT_GATEWAY', 'gateway_id:' . $id, '');
    send_success(null, 'Gateway status updated.');
}

send_error('Invalid request.', 400);
