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

use App\Controllers\PrivateController;
use App\Libraries\Common;
use App\Models\SubscribesModel;
use CodeIgniter\HTTP\ResponseInterface;

define("LIMIT", 20);

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

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

        $subscribes = new SubscribesModel();
        $common = new Common();

        $list = $subscribes
            ->where("user_id", $user_id)
            ->where("is_disable", 0)
            ->orderBy("subscribes.id", "DESC")
            ->join("plans", "plans.id = subscribes.plan_id")
            ->join("apps", "apps.id = subscribes.app_id")
            ->select("subscribes.uid, subscribes.created_at, subscribes.expires_at, subscribes.price, subscribes.is_active, subscribes.remaining_count, apps.name as app_name, apps.uid as app_uid, plans.type, plans.build_count")
            ->findAll(LIMIT, $offset);
        
        $items = [];

        if ($list) {
            foreach ($list as $item) {
                $items[] = [
                    "uid"        => $item["uid"],
                    "created_at" => date('d-m-Y H:i', $item['created_at']),
                    "expires_at" => date('d-m-Y H:i', $item['expires_at']),
                    "price"      => $item["price"],
                    "app"        => [
                        "name" => $item["app_name"],
                        "uid"  => $item["app_uid"],
                        "icon" => $common->get_icon($item["app_uid"])
                    ],
                    "is_active"  => (bool) $item["is_active"],
                    "build_count" => (int) $item["build_count"] ?? 0,
                    "remaining_count" => (int) $item["remaining_count"] ?? 0,
                    "type" => $item["type"],
                ];
            }
        }

        $total = $subscribes
            ->where("user_id", $user_id)
            ->where("is_disable", 0)
            ->countAllResults();

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

}