<?php

/**
 * Bismillahir Rahmanir Raheem
 * 
 * PHP Mikrotik Billing (https://github.com/paybilling/phpnuxbill/)
 *
 * Paystack Payment Gateway for Advanced Hotspot System | PHPNuxBill Plugin
 *
 * @author: Focuslinks Digital Solutions <focuslinkstech@gmail.com>
 * Website: https://focuslinkstech.com.ng/
 * GitHub: https://github.com/Focuslinkstech/
 * Telegram: https://t.me/focuslinkstech/
 *
 **/

register_menu("Hotspot Paystack Gateway", true, "hotspot_pg_paystack_config", 'SETTINGS', '', '', "");

function hotspot_pg_paystack_config()
{
    global $ui, $admin, $config;
    $ui->assign('_title', Lang::T("Hotspot Payment Gateway [Paystack]"));
    $ui->assign('_system_menu', 'settings');
    $admin = Admin::_info();
    $ui->assign('_admin', $admin);

    // Check user type for access
    if (!in_array($admin['user_type'], ['SuperAdmin', 'Admin'])) {
        _alert(Lang::T('You do not have permission to access this page'), 'danger', "dashboard");
        exit;
    }

    $hotspot_pg_paystack_secret_key = _post('hotspot_pg_paystack_secret_key');

    if (_post('save') == 'save') {
        $settings = [
            'hotspot_pg_paystack_secret_key' => $hotspot_pg_paystack_secret_key,
        ];

        // Update or insert settings in the database - bKash এর মতোই
        foreach ($settings as $key => $value) {
            $d = ORM::for_table('tbl_appconfig')->where('setting', $key)->find_one();
            if ($d) {
                $d->value = $value;
                $d->save();
            } else {
                $d = ORM::for_table('tbl_appconfig')->create();
                $d->setting = $key;
                $d->value = $value;
                $d->save();
            }
        }

        _log('[' . $admin['username'] . ']: ' . Lang::T('Paystack Settings Saved Successfully'), $admin['user_type']);
        r2(U . 'plugin/hotspot_pg_paystack_config', 's', Lang::T('Settings Saved Successfully'));
    }

    $ui->assign('_c', $config);
    $ui->assign('companyName', $config['CompanyName']);
    $ui->display('hotspot_pg_paystack_config.tpl');
}

function hotspot_processPayment_paystack($data)
{
    global $config;
    $phone = $data['phone'];
    $mac_address = $data['mac_address'];
    $ip_address = $data['ip_address'];
    $routername = $data['routername'];
    $txref = $data['txref'];
    $planid = $data['planid'];
    $plan_name = $data['plan_name'];
    $status = $data['status'];
    $amount = $data['amount'];
    $email = $data['email'];
    $paymentGateway = $data['payment_gateway'];

    if (empty($config['hotspot_pg_paystack_secret_key'])) {
        $message = urlencode(Lang::T("Paystack payment gateway not configured. Please report to "). ' ' . $config['CompanyName']);
        Message::sendTelegram("Paystack Hotspot Payment Failed: Payment gateway not configured. Please setup Paystack hotspot system gateway ");
        header('Location: ' . U . "plugin/hotspot_verify&message=" . $message);
        exit();
    }

    $total = $amount * 100; // Convert to kobo (Paystack uses smallest currency unit)
    $serverHost = $_SERVER['HTTP_HOST'];
    $customer_email = ($serverHost === 'localhost') ? "$phone@$serverHost.com" : "$phone@$serverHost";

    $json = [
        'reference' => $txref,
        'amount' => $total,
        'email' => $customer_email,
        'customer' => [
            'first_name' => "Hotspot $phone",
            'phone' => $phone
        ],
        'metadata' => [
            'price' => $amount,
            'planid' => $planid,
            'router' => $routername,
            'mac_address' => $mac_address,
            'ip_address' => $ip_address,
            'plan_name' => $plan_name
        ],
        'customizations' => [
            'title' => $plan_name,
            'description' => $plan_name
        ],
        'callback_url' => U . 'plugin/hotspot_pg_paystack_verify'
    ];

    $response = Http::postJsonData(
        'https://api.paystack.co/transaction/initialize',
        $json,
        [
            'Authorization: Bearer ' . $config['hotspot_pg_paystack_secret_key'],
            'Cache-Control: no-cache'
        ]
    );

    $result = json_decode($response, true);
    
    if (!$result || !isset($result['status'])) {
        Message::sendTelegram("Paystack Hotspot Payment API response error:\n\n" . json_encode($response, JSON_PRETTY_PRINT));
        header('Location: ' . U . "plugin/hotspot_verify&message=" . urlencode(Lang::T("Failed to create transaction. Paystack API error.")));
        exit();
    }

    if ($result['status'] === false) {
        Message::sendTelegram("Paystack Hotspot payment initialization failed\n\n" . json_encode($result, JSON_PRETTY_PRINT));
        header('Location: ' . U . "plugin/hotspot_verify&message=" . urlencode(Lang::T("Failed to create transaction.\n" . $result['message'])));
        exit();
    }

    // Save transaction to database - bKash এর মতোই
    $failedMessage = Lang::T("Failed to save transaction. Please try again later.");
    $trx = ORM::for_table('tbl_hotspot_payments')->create();
    $trx->transaction_id = $result['data']['reference'];
    $trx->transaction_ref = $txref;
    $trx->amount = $amount;
    $trx->phone_number = $phone;
    $trx->plan_id = $planid;
    $trx->plan_name = $plan_name;
    $trx->mac_address = $mac_address;
    $trx->ip_address = $ip_address;
    $trx->router_name = $routername;
    $trx->voucher_code = '**********';
    $trx->transaction_status = $status;
    $trx->payment_gateway = $paymentGateway;
    $trx->gateway_response = json_encode($result);

    try {
        $trx->save();
        header('Location: ' . $result['data']['authorization_url']);
        exit();
    } catch (Exception $e) {
        _log(Lang::T("Failed to save Paystack transaction: ") . $e->getMessage());
        hotspot_throwError($failedMessage);
        exit;
    }
}

function hotspot_pg_paystack_verify()
{
    global $config;

    if (isset($_GET['reference'])) {
        $reference = $_GET['reference'] ?? '';

        if (!$reference) {
            _log(Lang::T("Paystack Payment verification: No reference supplied"));
            header('Location: ' . U . "plugin/hotspot_verify&message=" . urlencode(Lang::T("Paystack Payment verification: No reference supplied")));
            die();
        }

        $trx = ORM::for_table('tbl_hotspot_payments')
            ->where('transaction_id', $reference)
            ->find_one();

        if (!$trx) {
            _log(Lang::T("Paystack Payment verification: Transaction with this Reference ID: $reference Not Found"));
            header('Location: ' . U . "plugin/hotspot_verify&message=" . urlencode(Lang::T("Transaction with this Reference ID: $reference Not Found")));
            die();
        }

        // Check if transaction has already been processed
        if (in_array($trx->transaction_status, ['paid', 'failed', 'cancelled'])) {
            _log(Lang::T("[Paystack Payment verification] Transaction with this Reference ID: $reference has already been processed and its status is") . ' ' . $trx->transaction_status);
            header('Location: ' . U . "plugin/hotspot_verify&message=" . urlencode(Lang::T("Transaction with this Reference ID: $reference has already been processed and its status is") . ' ' . $trx->transaction_status));
            die();
        }

        // Verify transaction with Paystack
        $result = json_decode(Http::getData(
            'https://api.paystack.co/transaction/verify/' . $reference,
            [
                'Authorization: Bearer ' . $config['hotspot_pg_paystack_secret_key'],
                'Cache-Control: no-cache'
            ]
        ), true);

        if (!$result || !isset($result['status'])) {
            Message::sendTelegram("Paystack Hotspot Payment verification failed: Unable to verify transaction");
            header('Location: ' . U . "plugin/hotspot_verify&message=" . urlencode(Lang::T("Unable to verify transaction. Please try again later.")));
            exit();
        }

        $amountPaid = $result['data']['amount'] / 100;
        $amountToPay = $trx->amount;
        $status = $result['data']['status'];
        $channel = $result['data']['channel'];
        $gateway_response = $result['data']['gateway_response'];

        if ($result['status'] === true && $status === 'success' && $amountPaid >= $amountToPay) {
            // Payment successful - bKash এর মতোই activation process
            $phone = $trx->phone_number;
            $routername = $trx->router_name;
            $planid = $trx->plan_id;

            $voucherCode = $trx->mac_address;
            $serverHost = $_SERVER['HTTP_HOST'];
            $email = ($serverHost === 'localhost') ? "$phone@$serverHost.com" : "$phone@$serverHost";

            // Create customer - bKash এর মতোই
            $c = ORM::for_table('tbl_customers')->create();
            $c->username = $config['hotspot_voucher_mode'] ? $voucherCode : $phone;
            $c->password = $config['hotspot_voucher_mode'] ? $voucherCode : $phone;
            $c->pppoe_password = '0';
            $c->email = $email;
            $c->fullname = "Hotspot $phone";
            $c->phonenumber = Lang::phoneFormat($phone);
            $c->service_type = 'Hotspot';
            $c->save();

            // Activate package - bKash এর মতোই
            if (!Package::rechargeUser($c->id, $routername, $planid, 'PAYSTACK', $channel)) {
                _log('[' . Lang::T("Failed to activate your Package.") . ']: Paystack Hotspot Payment - ' . json_encode($result));
                Message::sendTelegram("Failed to activate the package for Paystack transaction ID $reference.");
                header('Location: ' . U . "plugin/hotspot_verify&message=" . urlencode(Lang::T("Failed to activate your Package, try again later. Contact Support")));
                exit;
            }

            $expiration = ORM::for_table('tbl_user_recharges')->where('plan_id', $planid)->where('username', $c['username'])->where('status', 'on')->find_one();
            $expired_date = $expiration->expiration;
            $expired_time = $expiration->time;
            $expired = $expired_date . " " . date("h:i A", strtotime($expired_time));
            $loginCode = $config['hotspot_voucher_mode'] ? $voucherCode : $phone;

            // Update transaction - bKash এর মতোই
            $trx->voucher_code = $loginCode;
            $trx->payment_method = 'PAYSTACK - ' . $channel;
            $trx->payment_date = date('Y-m-d H:i:s');
            $trx->transaction_status = 'paid';
            $trx->gateway_response = json_encode($result);
            $trx->expired_date = date('Y-m-d H:i:s', strtotime($expired));
            $trx->save();

            // Send SMS/WhatsApp - bKash এর মতোই
            hotspot_sendMessage($phone, $expiration->namebp, $voucherCode, $expiration->expiration);
            _log('[' . Lang::T("Notification") . ']: Paystack Hotspot Payment Success - ' . json_encode($result));
            header('Location: ' . U . "plugin/hotspot_verify&reference={$trx->transaction_ref}");

        } else {
            // Payment failed
            $trx->payment_method = 'PAYSTACK - ' . $channel;
            $trx->payment_date = date('Y-m-d H:i:s');
            $trx->transaction_status = 'failed';
            $trx->gateway_response = json_encode($result);
            $trx->save();
            
            _log('[' . Lang::T("Notification") . ']: Paystack Hotspot Payment Failed - ' . json_encode($result));
            header('Location: ' . U . "plugin/hotspot_verify&reference={$trx->transaction_ref}&message=" . urlencode(Lang::T("Payment failed. Please try again.")));
        }
    } else {
        header('Location: ' . U . "plugin/hotspot_verify&message=" . urlencode(Lang::T("Invalid payment verification request")));
    }
}

// Webhook function - bKash এর মতোই structure
function hotspot_pg_paystack_webhook()
{
    global $config;

    if (strtoupper($_SERVER['REQUEST_METHOD']) != 'POST') {
        header('Content-Type: application/json');
        header('HTTP/1.1 400 Bad Request');
        echo json_encode(['error' => 'Bad Request: Not a valid webhook.']);
        exit();
    }

    $paymentDetails = @file_get_contents("php://input");
    file_put_contents("pages/paystack-hotspot-webhook.html", date('Y-m-d H:i:s') . "<pre>$paymentDetails</pre>", FILE_APPEND);

    // Validate webhook signature
    if (
        !isset($_SERVER['HTTP_X_PAYSTACK_SIGNATURE']) ||
        $_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] !== hash_hmac('sha512', $paymentDetails, $config['hotspot_pg_paystack_secret_key'])
    ) {
        http_response_code(403);
        echo json_encode(['error' => 'Invalid signature']);
        exit();
    }

    http_response_code(200);

    // Decode the event payload
    $event = json_decode($paymentDetails);
    
    if (!isset($event->event) || $event->event !== 'charge.success') {
        echo json_encode(['status' => 'ignored', 'message' => 'Event not processed']);
        exit();
    }

    $reference = $event->data->reference;
    $amount = $event->data->amount / 100;
    $status = $event->data->status;
    $channel = $event->data->channel;

    if (!$reference) {
        Message::sendTelegram(Lang::T("Paystack Hotspot Webhook: No reference supplied"));
        exit();
    }

    $trx = ORM::for_table('tbl_hotspot_payments')
        ->where('transaction_id', $reference)
        ->find_one();

    if (!$trx) {
        _log("Paystack Hotspot Webhook: Transaction with reference $reference not found.");
        http_response_code(404);
        exit();
    }

    if (in_array($trx->transaction_status, ['paid', 'failed', 'cancelled'])) {
        _log("Paystack Hotspot Webhook: Transaction with reference $reference already processed.");
        exit();
    }

    if ($status === 'success') {
        // bKash এর মতোই activation process
        $phone = $trx->phone_number;
        $routername = $trx->router_name;
        $planid = $trx->plan_id;

        $voucherCode = hotspot_generate_voucher_code();
        $serverHost = $_SERVER['HTTP_HOST'];
        $email = ($serverHost === 'localhost') ? "$phone@$serverHost.com" : "$phone@$serverHost";

        // Create customer
        $c = ORM::for_table('tbl_customers')->create();
        $c->username = $config['hotspot_voucher_mode'] ? $voucherCode : $phone;
        $c->password = $config['hotspot_voucher_mode'] ? $voucherCode : $phone;
        $c->pppoe_password = '0';
        $c->email = $email;
        $c->fullname = "Hotspot $phone";
        $c->phonenumber = Lang::phoneFormat($phone);
        $c->service_type = 'Hotspot';
        $c->save();

        // Activate package
        if (!Package::rechargeUser($c->id, $routername, $planid, 'PAYSTACK', $channel)) {
            _log('[' . Lang::T("Failed to activate the package") . ']: Paystack Hotspot Webhook: ' . json_encode($event));
            Message::sendTelegram('Paystack Hotspot Webhook: Failed to activate package for reference: ' . $reference);
        } else {
            $expiration = ORM::for_table('tbl_user_recharges')
                ->where('plan_id', $planid)
                ->where('username', $c['username'])
                ->where('status', 'on')
                ->find_one();
                
            if ($expiration) {
                $expired_date = $expiration->expiration;
                $expired_time = $expiration->time;
                $expired = $expired_date . " " . date("h:i A", strtotime($expired_time));
            } else {
                $expired = date('Y-m-d H:i:s', strtotime('+1 day'));
            }
            
            $loginCode = $config['hotspot_voucher_mode'] ? $voucherCode : $phone;

            // Update transaction
            $trx->voucher_code = $loginCode;
            $trx->payment_method = 'PAYSTACK - ' . $channel;
            $trx->payment_date = date('Y-m-d H:i:s');
            $trx->transaction_status = 'paid';
            $trx->gateway_response = json_encode($event);
            $trx->expired_date = date('Y-m-d H:i:s', strtotime($expired));
            $trx->save();

            // Send notification
            hotspot_sendMessage($phone, $trx->plan_name, $loginCode, $expired);
            _log('[' . Lang::T("Notification") . ']: Paystack Hotspot Webhook Success - Reference: ' . $reference);
            Message::sendTelegram('Paystack Hotspot Webhook: Payment successful for reference: ' . $reference);
        }
    }
}