<?php echo $this->extend('template/admin/main') ?>

<?php echo $this->section('content') ?>
<div class="card mb-4">
    <div class="card-body">
        <form id="paymentForm">
            <?php echo $this->include('common/security') ?>
            <?php if(in_array(session()->get('role_id'),[1,2])){ ?>
                <div class="col-12 mt-3">
                    <label for="amount" class=""><?php echo lang("Localize.company") ?></label> 
                    <select class="form-select select2" name="company_id" id="company_id" required>
                        <option value="">None</option>

                        <?php foreach ($companies as $company) : ?>
                            <option value="<?php echo $company->id ?>"><?php echo $company->name ?></option>
                        <?php endforeach ?>
                    </select>
                </div>
            <?php } ?>
            <div class="form-group">
                <label for="amount"><?php echo lang("Localize.amount") ?></label>
                <input type="text" id="amount" name="amount" class="form-control" required>
            </div>
            <button type="button" id="payNowButton" class="btn btn-primary mt-3"><?php echo lang("Localize.pay_now") ?></button>
        </form>
    </div>
</div>

<script src="https://www.merchant.geidea.net/hpp/geideaCheckout.min.js"></script>
<script>
    $(document).ready(function () {
        let csrfToken = '<?= csrf_hash() ?>';
        const csrfTokenName = '<?= csrf_token() ?>';
        let amount = $('#amount').val();
        let selectedCompanyId = $('#company_id').val();
        let merchantReferenceId = null;

        $('#payNowButton').on('click', function () {
            amount = $('#amount').val();
            selectedCompanyId = $('#company_id').val();

            if (!amount) {
                alert('Please enter an amount.');
                return;
            }

            $.ajax({
                url: '<?= base_url("modules/backend/agents/process-payment") ?>',
                method: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                data: JSON.stringify({
                    amount: amount,
                    companyId : selectedCompanyId,
                    [csrfTokenName]: csrfToken

                }),
                success: function (data) {
                    if (data.sessionId) {
                        csrfToken = data.csrfToken;
                        merchantReferenceId = data.merchantReferenceId || null;
                        const payment = new GeideaCheckout(onSuccess, onError, onCancel);
                        payment.startPayment(data.sessionId);
                    } else {
                        alert('Error: ' + (data.error || 'Unknown error'));
                    }
                },
                error: function (xhr, status, error) {
                    console.error("XHR:", xhr.responseText);
                    alert('Error: ' + error);
                }
            });
        });

        const onSuccess = function (data) {
            console.log(data);
            console.log('JSON String:', JSON.stringify(data));
           $.ajax({
                url: '<?= base_url("modules/backend/agents/payment_success") ?>',
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                data: JSON.stringify({
                    amount: amount,
                    companyId : selectedCompanyId,
                    merchantReferenceId: merchantReferenceId,
                    paymentReference: data.orderId,
                    [csrfTokenName]: csrfToken
                }),
                success: function (response) {
                    if (response.success) {
                        alert('Payment processed successfully!');
                        location.href = '<?= base_url("modules/backend/payagents") ?>';
                    } else {
                        alert('Error: ' + (response.message || 'Unknown error occurred.'));
                    }
                },
                error: function (xhr) {
                    alert('Error saving payment!');
                    console.error(xhr.responseText);
                }
            });

        };

        const onError = function (data) {
            alert('Payment Error Try after some time');
        };

        const onCancel = function (data) {
            alert('Payment Cancelled: ' + JSON.stringify(data));
            location.reload();
        };
    });
</script>
<?php echo $this->endSection() ?>