<?php namespace App\Controllers\Api\Manager\Transactions;

use App\Controllers\PrivateController;
use App\Models\TransactionsModel;
use CodeIgniter\HTTP\ResponseInterface;

define("LIMIT", 20);

class Transactions extends PrivateController
{
    /**************************************************************************************
     * PUBLIC FUNCTIONS
     **************************************************************************************/

    /**
     * Get all transactions
     * @return ResponseInterface
     */
    public function index(): ResponseInterface
    {
        $offset = (int) $this->request->getGet("offset");

        $transactions = new TransactionsModel();
        
        $transactions_list = $transactions
            ->select('transactions.uid, transactions.amount, transactions.created_at, transactions.external_uid, transactions.subscribe_external_id, deposit_methods.name as method_name, deposit_methods.logo as method_logo, subscribes.uid as subscribe_uid')
            ->join('deposit_methods', 'deposit_methods.id = transactions.method_id')
            ->join('subscribes', 'subscribes.subscribe_external_id = transactions.subscribe_external_id')
            ->orderBy('transactions.id', 'DESC')
            ->findAll(LIMIT, $offset);

        $items = [];

        foreach ($transactions_list as $item) {
            $items[] = [
                "uid"          => $item["uid"],
                "external_uid" => $item["external_uid"],
                "subscribe_external_id" => $item["subscribe_external_id"],
                "amount"       => $item["amount"],
                "method"       => [
                    "name" => $item["method_name"],
                    "logo" => base_url("deposit/".$item["method_logo"])
                ],
                "subscription_uid" => $item["subscribe_uid"],
                "created_at"   => date('d-m-Y H:i', $item['created_at']),
            ];
        }

        $total = $transactions->countAllResults();

        return $this->respond(["list" => $items, "total" => $total], 200);
    }
}