<?php
namespace App\Libraries;

use App\Models\SubscribesModel;

class AppSubscription
{
    private $app_id;

    private $subscribes;

    function __construct(int $app_id)
    {
        $this->app_id = $app_id;

        $this->subscribes = new SubscribesModel();
    }

    /**************************************************************************************
     * PUBLIC FUNCTIONS
     **************************************************************************************/

    /**
     * Check active subscription
     * @return bool
     */
    public function active_subscription_exists(): bool
    {
        $subscribe = $this->get_active_subscription();
        return $subscribe !== null;
    }

    /**
     * Get active subscription
     * @return array|null
     */
    public function get_active_subscription(): ?array
    {
        return $this->find_last_subscription([
            "active" => true
        ]);
    }

    /**
     * Get last subscription
     * @return array|null
     */
    public function get_subscription(): ?array
    {
        return $this->find_last_subscription();
    }

    /**
     * Decrement remaining count on active subscription
     * @return void
     */
    public function decrement_remaining_count(): void
    {
        $activeSubscription = $this->get_active_subscription();

        if (!$activeSubscription || $activeSubscription["remaining_count"] === 0) {
            return;
        }

        $this->subscribes->update($activeSubscription["id"], [
            "remaining_count" => $activeSubscription["remaining_count"] - 1
        ]);
    }

    /**************************************************************************************
     * PRIVATE FUNCTIONS
     **************************************************************************************/

    /**
     * Find last subscription
     * @param array $where
     * @return array|null
     */
    private function find_last_subscription(array $where = ["active" => false]): ?array
    {
        $subscribe = $this->subscribes->join("plans", "plans.id = subscribes.plan_id")->where([
            "app_id" => $this->app_id,
            "is_disable" => 0,
        ])->orderBy("subscribes.id", "DESC")->select("subscribes.*, plans.type, plans.build_count, plans.count, plans.price, plans.save, plans.api_id")->first();

        if (!$subscribe) {
            return null;
        }

        if (!$where["active"]) {
            return $subscribe;
        }

        if ($subscribe["type"] == "subscription" && $subscribe["expires_at"] > time()) {
            return $subscribe;
        }

        if ($subscribe["type"] == "per_build" && $subscribe["remaining_count"] > 0) {
            return $subscribe;
        }

        return null;
    }
}
