<?php

namespace Home\Controllers;

use App\Controllers\BaseController;
use App\Libraries\GatewayApi;
use Blocks\Models\QueueModel;
use CodeIgniter\Debug\Exceptions;
use Home\Models\HomeModel;

class HomeController extends BaseController
{
    public $data = [];
    public $model, $db, $params, $apikey, $payment_lib;
    public function __construct()
    {
        $this->model = new HomeModel;
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // Real stats from database (safe with try-catch using \Throwable)
        try {
            $db = db_connect();
            $totalUsers = $db->query("SELECT COUNT(*) as cnt FROM users")->getRow()->cnt ?? 0;
        } catch (\Throwable $e) { $totalUsers = 0; }

        try {
            $db = db_connect();
            $totalTransactions = $db->query("SELECT COUNT(*) as cnt FROM transactions")->getRow()->cnt ?? 0;
        } catch (\Throwable $e) { $totalTransactions = 0; }

        try {
            $db = db_connect();
            $totalSuccess = $db->query("SELECT COUNT(*) as cnt FROM transactions WHERE status = 2")->getRow()->cnt ?? 0;
        } catch (\Throwable $e) { $totalSuccess = 0; }

        try {
            $db = db_connect();
            $totalPaymentMethods = $db->query("SELECT COUNT(*) as cnt FROM payments WHERE status = 1")->getRow()->cnt ?? 0;
        } catch (\Throwable $e) { $totalPaymentMethods = 0; }

        // Recent successful transactions for live feed
        try {
            $db = db_connect();
            $recentTx = $db->query("SELECT t.amount, t.created_at FROM transactions t WHERE t.status = 2 ORDER BY t.id DESC LIMIT 20")->getResultArray();
        } catch (\Throwable $e) { $recentTx = []; }

        // Fetch Approved Reviews with user avatars
        try {
            $db = db_connect();
            $reviews = $db->query("SELECT r.*, u.avatar FROM reviews r LEFT JOIN users u ON r.user_id = u.id WHERE r.status = 1 ORDER BY r.id DESC LIMIT 6")->getResultArray();
        } catch (\Throwable $e) { $reviews = []; }

        $data = [
            "payments"     => $this->model->list_items(null, ['task' => 'list-items-payments']),
            "faqs"         => $this->model->list_items(null, ['task' => 'list-items-faq']),
            "plans"        => $this->model->list_items(null, ['task' => 'list-items-plans']),
            "total_users"  => $totalUsers,
            "total_tx"     => $totalTransactions,
            "total_success" => $totalSuccess,
            "total_methods" => $totalPaymentMethods,
            "recent_tx"    => $recentTx,
            "reviews"      => $reviews,
        ];
        return  $this->template->view('index', $data)->render();
    }

    public function pricing()
    {
        $data = [
            "plans" => $this->model->list_items(null, ['task' => 'list-items-plans']),
            "title" => "Pricing"
        ];
        return $this->template->view('pricing', $data)->render();
    }

    public function terms()
    {
        return  $this->template->view('terms')->render();
    }
    public function privacy()
    {
        return  $this->template->view('privacy')->render();
    }

    public function blogs()
    {
        $item = $this->model->fetch('*', 'blogs', ['status' => 1, 'created_at <=' => now()], 'id');
        return  $this->template->view('blogs', ['items' => $item])->render();
    }

    public function blogSingle($uri)
    {
        $item = $this->model->fetch('*', 'blogs', ['status' => 1, 'created_at <=' => now()], 'id');
        $blog = $this->model->get('*', 'blogs', ['uri' => $uri, 'status' => 1], 'id');

        if (!empty($blog)) {
            $data = [
                "og_title"        => $blog->title,
                "og_description"  => $blog->title,
                "og_image"        => base_url($blog->thumbnail),
                "description"     => $blog->description,
                "og_url"          => current_url(),
                "items"           => $item,
                "blog"           => $blog,
            ];
            return  $this->template->view('blog', $data)->render();
        }
        load_404();
    }

    public function invoice($ids = '')
    {

        $this->params = ['ids' => $ids];
        $item = $this->model->getItem($this->params, ['task' => 'get-item']);


        if (!empty($item)) {
            $data['items'] = $item;
            $rate = 1;
            $this->apikey = get_brand_data($item['brand_id'], $item['uid'])->brand_key;

            if (isset($_GET['start_payment'])) {

                $success_url = base_url('invoice/' . $ids . "?complete=" . $ids);
                $cancel_url  = base_url('invoice/' . $ids);

                // ── Direct DB insert (bypasses cURL/SSL loopback issue on shared hosting) ──
                $db    = db_connect();
                $brand = $db->table('brands')->where('brand_key', $this->apikey)->get()->getRowArray();

                if (!empty($brand)) {
                    $tmp_ids = ids();
                    $param   = [
                        "cus_name"    => $item['customer_name'],
                        "cus_email"   => $item['customer_email'],
                        "success_url" => $success_url,
                        "cancel_url"  => $cancel_url,
                        "webhook_url" => $success_url,
                    ];

                    $db->table('temp_transactions')->insert([
                        "ids"            => $tmp_ids,
                        "uid"            => $brand['uid'],
                        "brand_id"       => $brand['id'],
                        "params"         => json_encode($param),
                        "meta"           => json_encode([]),
                        "request"        => 'GET',
                        "amount"         => $item['customer_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/' . $tmp_ids;
                        return redirect()->to($payment_url);
                    }
                }
                return redirect()->to(previous_url());

            } elseif (isset($_GET['complete'])) {
                $trxId  = $_REQUEST['transactionId'] ?? '';
                $amount = $_REQUEST['paymentAmount']  ?? '';

                if (!empty($trxId)) {
                    // ── Direct DB verify (bypasses cURL/SSL loopback issue) ──
                    $db    = db_connect();
                    $brand = $db->table('brands')->where('brand_key', $this->apikey)->get()->getRowArray();

                    if (!empty($brand)) {
                        $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'];
                            $sta_text   = $status_map[$trx['status']] ?? 'ERROR';
                            $sta        = $sta_text == 'COMPLETED' ? '2' : ($sta_text == 'PENDING' ? '1' : '0');

                            $db->table('invoice')
                                ->where('ids', $ids)
                                ->update(['pay_status' => $sta, 'transaction_id' => $trxId]);
                        }
                    }
                }
                return redirect()->to(base_url('invoice/' . $ids));
            } else {
                return view('Home\Views\invoice', $data);
            }
        } else {
            load_404();
        }
    }
}
