<?php
/**
 * WHMCS Automated Payment Gateway Module for PayAutoBD
 * Upload path: /modules/gateways/payautobd.php
 */

if (!defined("WHMCS")) {
    die("This file cannot be accessed directly");
}

function payautobd_MetaData() {
    return array('DisplayName' => 'PayAutoBD Automated Gateway', 'APIVersion' => '1.1');
}

function payautobd_config() {
    return array(
        'FriendlyName' => array('Type' => 'System', 'Value' => 'PayAutoBD (bKash, Nagad, Rocket, Upay, Bank)'),
        'public_key' => array('FriendlyName' => 'Brand Public Key', 'Type' => 'text', 'Size' => '45'),
        'secret_key' => array('FriendlyName' => 'Brand Secret Key', 'Type' => 'password', 'Size' => '45'),
    );
}

function payautobd_link($params) {
    $payload = array(
        'merchant_order_id' => (string) $params['invoiceid'],
        'product_title' => $params['description'],
        'amount' => (float) $params['amount'],
        'customer_name' => trim($params['clientdetails']['firstname'] . ' ' . $params['clientdetails']['lastname']),
        'customer_phone' => $params['clientdetails']['phonenumber'],
        'customer_email' => $params['clientdetails']['email'],
        'store_domain' => parse_url($params['systemurl'], PHP_URL_HOST),
        'success_url' => $params['systemurl'] . 'viewinvoice.php?id=' . $params['invoiceid'] . '&paymentsuccess=true',
        'cancel_url' => $params['systemurl'] . 'viewinvoice.php?id=' . $params['invoiceid'] . '&paymentfailed=true',
    );

    $ch = curl_init('https://www.mcqhub.thetextualmentor.top/api/v1/payment/create');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Accept: application/json',
        'X-Public-Key: ' . trim($params['public_key']),
        'X-Secret-Key: ' . trim($params['secret_key']),
    ));

    $response = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($response, true);

    if (!empty($data['payment_url'])) {
        return '<a href="' . htmlspecialchars($data['payment_url']) . '" class="btn btn-success btn-block">' . $params['langpaynow'] . '</a>';
    }
    return '<div class="alert alert-danger">Gateway Error: ' . htmlspecialchars($data['message'] ?? 'Connection failed') . '</div>';
}