<?php namespace App\Controllers\Api\Customer\Projects;

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

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

    /**
     * Get short app detail
     * @return ResponseInterface
     */
    public function index(): ResponseInterface
    {
        $uid = esc($this->request->getGet("uid"));

        $projects = new AppsModel();

        $app = $projects
            ->where("uid", $uid)
            ->where("user", $this->userId)
            ->where("deleted_at", 0)
            ->select("uid,name,link,id")
            ->first();

        if (!$app) {
            return $this->respond(["message" => lang("Message.message_14")], 404);
        }

        $appSubscription = new AppSubscription($app["id"]);
        $subscription = $appSubscription->get_active_subscription();

        $common = new Common();

        return $this->respond([
            "name"      => $app["name"],
            "link"      => $app["link"],
            "icon"      => $common->get_icon($app["uid"]),
            "subscribe" => $subscription !== null,
            "subscription_active" => $subscription && $subscription["type"] === "subscription" && $subscription["is_active"],
            "subscribe_date" => $subscription && $subscription["type"] == "subscription" ? date('d-m-Y H:i', $subscription['expires_at']) : "",
            "build_count" => $subscription ? (int) $subscription["build_count"] : 0,
            "remaining_count" => $subscription ? (int) $subscription["remaining_count"] : 0,
            "subscription_uid" => $subscription ? $subscription["uid"] : "",
        ], 200);
    }

}