<?php

namespace User\Controllers;

use App\Libraries\GatewayApi;
use User\Models\UserModel;
use User\Controllers\BaseController;

class AddFunds extends UserController
{
    public $data = [];
    public $model, $apikey, $convert_rate, $payment_lib;

    public function __construct()
    {
        parent::__construct();
        $this->model = new UserModel();
        $this->payment_lib = new GatewayApi();
        $this->convert_rate = !empty(get_option('new_currecry_rate')) ? (float)get_option('new_currecry_rate') : 1;
        $this->apikey = $this->model->get('brand_key,uid,id', 'brands', ['uid' => 1])->brand_key;
    }

    public function index()
    {
        _is_ajax();
        $payments = $this->model->get('type, name, id, params', 'payments', ['id' => 1], 'sort', 'ASC');
        $data = array(
            "module"          => get_class($this),
            "payments"        => $payments,
            "currency_code"   => get_option("currency_code", 'BDT'),
            "currency_symbol" => get_option("currency_symbol", '৳'),
        );
        return view('User\Views\add_funds\index', $data);
    }

    public function process()
    {
        _is_ajax();
        $payment_id     = (int)post("payment_id");

        $amount         = (float)post("amount");
        $agree = post("agree");
        if ($amount == "") {
            ms(array(
                "status" => "error",
                "message" => lang("amount_is_required"),
            ));
        }

        if ($amount < 0) {
            ms(array(
                "status" => "error",
                "message" => lang("amount_must_be_greater_than_zero"),
            ));
        }

        /*----------  Check payment method  ----------*/
        $payment = $this->model->get('id, type, name, params', 'payments', ['id' => $payment_id]);
        if (!$payment) {
            _validation('error', 'Error 1: Payment method not found in database.');
        }

        $min_payment = get_value($payment->params, 'min');
        $max_payment = get_value($payment->params, 'max');

        if ($amount < $min_payment) {
            _validation('error', lang("minimum_amount_is") . " " . $min_payment);
        }

        if ($max_payment > 0 && $amount > $max_payment) {
            _validation('error', 'Maximal amount is' . " " . $max_payment);
        }

        if (!$agree) {
            _validation('error', lang("you_must_confirm_to_the_conditions_before_paying"));
        }

        $response = $this->create_payment($amount);
        if (!empty($response)) {
            $res = json_decode($response);
            log_message('alert', $response);
            if (isset($res->status) && $res->status == 1) {
                ms(['status' => 'success', 'message' => 'You are being redirected to payment page', 'redirect_url' => $res->payment_url]);
            } elseif (isset($res->message)) {
                _validation('error', 'API Error: ' . $res->message);
            } else {
                _validation('error', 'API Response Error: ' . $response);
            }
        }

        _validation('error', 'Error 2: Payment session could not be created.');
    }

    public function create_payment($amount)
    {
        _is_ajax();
        if (!$amount) {
            _validation('error', 'Error 3: Amount is missing when creating payment.');
        }
        if (!$this->apikey) {
            _validation('error', 'Error 4: API Key is missing in your Brands table.');
        }

        $users     = current_user();
        $full_name = trim(($users->first_name ?? '') . ' ' . ($users->last_name ?? ''));
        $amount    = $amount * $this->convert_rate;

        // ──────────────────────────────────────────────────────────────────
        // DIRECT DATABASE APPROACH
        // main & secent share the same DB (u670609146_paypay).
        // Inserting directly avoids cURL/SSL loopback issues on shared hosting.
        // ──────────────────────────────────────────────────────────────────
        $db    = db_connect();
        $brand = $db->table('brands')->where('brand_key', $this->apikey)->get()->getRowArray();

        if (empty($brand)) {
            return json_encode(['status' => 0, 'message' => 'Error 4b: Brand not found for API key.']);
        }

        $ids   = ids();
        $param = [
            "cus_name"    => $full_name ?: 'Customer',
            "cus_email"   => $users->email ?? 'noreply@example.com',
            "success_url" => user_url("add_funds/complete/success"),
            "cancel_url"  => user_url("add_funds/complete/unsuccess"),
            "webhook_url" => user_url("add_funds/complete/validate"),
        ];
        $meta  = ['phone' => $users->phone ?? '', 'uid' => $users->id];

        $db->table('temp_transactions')->insert([
            "ids"            => $ids,
            "uid"            => $brand['uid'],
            "brand_id"       => $brand['id'],
            "params"         => json_encode($param),
            "meta"           => json_encode($meta),
            "request"        => 'GET',
            "amount"         => $amount,
            "transaction_id" => trxId(),
            "created_at"     => date('Y-m-d H:i:s'),
        ]);

        if ($db->affectedRows() > 0) {
            $payment_url = rtrim(getenv('PAYMENT_URL'), '/') . '/api/execute/' . $ids;
            return json_encode(['status' => 1, 'message' => 'Payment Link', 'payment_url' => $payment_url]);
        }

        return json_encode(['status' => 0, 'message' => 'Failed to create payment session. DB insert failed.']);
    }

    /**
     * Called after payment completes on secent side.
     */
    public function complete($type = '')
    {
        if ($type == 'validate') {
            $trxId = $_REQUEST['transactionId'] ?? '';
            if (empty($trxId)) return;

            // ── Direct DB verify (no cURL) ──────────────────────────────
            $db    = db_connect();
            $brand = $db->table('brands')->where('brand_key', $this->apikey)->get()->getRowArray();
            if (empty($brand)) return;

            $trx = $db->table('temp_transactions')
                ->where('transaction_id', $trxId)
                ->where('uid', $brand['uid'])
                ->get()->getRowArray();

            if (!empty($trx)) {
                $status_map = [1 => 'PENDING', 2 => 'COMPLETED', 3 => 'ERROR'];
                $status     = $status_map[$trx['status']] ?? 'ERROR';
                $params_arr = json_decode($trx['params'] ?? '{}', true);
                $meta_arr   = json_decode($trx['meta']   ?? '{}', true);
                $tr         = $db->table('transactions')
                    ->where('ids', $trx['ids'])
                    ->where('uid', $brand['uid'])
                    ->get()->getRowArray();

                // Recreate the same object shape that was expected from the old API
                $data = (object)[
                    'cus_name'       => $params_arr['cus_name']  ?? '',
                    'cus_email'      => $params_arr['cus_email'] ?? '',
                    'amount'         => $trx['amount'],
                    'transaction_id' => $trx['transaction_id'],
                    'metadata'       => (object)$meta_arr,
                    'payment_method' => $tr['type'] ?? '',
                    'status'         => $status,
                ];
            } else {
                return;
            }

            if (!empty($data)) {
                set_session('uid', get_value($data->metadata, 'uid'));

                $se = $this->model->get('*', 'user_transactions', ['transaction_id' => $trxId]);

                if (empty($se)) {
                    if ($data->status == 'COMPLETED') {
                        $this->db = db_connect();
                        $message = "Add fund amount of" . currency_format($data->amount) . " is " . strtolower($data->status);
                        $data_item_tnx = [
                            "ids"               => ids(),
                            "uid"               => session("uid"),
                            "type"              => 'add_balance',
                            "transaction_id"    => $trxId,
                            "amount"            => $data->amount,
                            "information"       => json_encode(['message' => $message]),
                            "status"            => 2,
                            "currency"          => "BDT",
                            "created_at"        => now(),
                            "updated_at"        => now(),
                        ];
                        $this->db->table('user_transactions')->insert($data_item_tnx);
                        $insertId = $this->db->insertID();
                        $this->model->add_funds_bonus_email($insertId);
                    }
                } else {
                    $sta = $data->status == 'COMPLETED' ? 2 : ($data->status == 'PENDING' ? 1 : 3);
                    if ($se->status == 2 && $sta != 2) {
                        $this->db->table('user_transactions')->update(['status' => $sta], ['transaction_id' => $trxId]);
                        $this->model->add_funds_bonus_email($se->id, 'deduct');
                    } elseif ($se->status != 2 && $sta == 2) {
                        $this->model->add_funds_bonus_email($se->id, 'add');
                    }
                }
            }
        } elseif (!empty($_GET['transactionId']) && $type == 'success') {
            $transaction_id = $_GET['transactionId'];
            $transaction = $this->model->get("*", 'transactions', ['transaction_id' => $transaction_id]);
            if (!empty($transaction)) {
                if ($transaction->status == 1) {
                    set_flashdata('message', ['message' => 'Your request is sent for Review', 'status' => 'warning']);
                } else {
                    set_flashdata('message', ['message' => 'Your Balance added Successfully', 'status' => 'success']);
                }

                $data = array(
                    "module" => get_class($this),
                    "transaction" => $transaction,
                );
                return $this->template->view('add_funds/payment_successfully', $data)->render();
            } else {
                set_flashdata('message', ['message' => 'Sorry! Failed to add Balance! Please Contact with Administrator', 'status' => 'error']);

                redirect()->to(user_url());
            }
        }
        set_flashdata('message', ['message' => 'Sorry! Failed to add Balance! Please Contact with Administrator', 'status' => 'error']);
        return $this->template->view('add_funds/payment_unsuccessfully', $this->data)->render();
    }
}
