<?php

namespace ModulesGarden\HostingQuotaNotifications\App\Libs\Groups;

use \ModulesGarden\HostingQuotaNotifications\App\Models;
use \ModulesGarden\HostingQuotaNotifications\Core\Models\Whmcs;
use \ModulesGarden\HostingQuotaNotifications\App\Helper\Request;
use \ModulesGarden\HostingQuotaNotifications\App\Libs\GroupConfiguration;
use \ModulesGarden\HostingQuotaNotifications\App\Libs\ProductGroups;
use \ModulesGarden\HostingQuotaNotifications\App\Models\Groups;

/**
 * Description of Manage
 *
 * @author Artur Pilch <artur.pi@modulesgarden.com>
 */
class Manage
{
    public static function getProducts($gid = 0)
    {
        $tableProductGroup = with(new Models\ProductGroup())->getTable();
        $tableProduct      = with(new Whmcs\Product())->getTable();
        
        return   Whmcs\Product::select($tableProduct.'.id', $tableProduct.'.name')->leftJoin($tableProductGroup, $tableProduct.'.id', '=', $tableProductGroup.'.pid')
                ->whereRaw($tableProductGroup . '.pid IS NULL')
                ->orWhere($tableProductGroup . '.gid', '=', $gid)
                ->get()->pluck('name', 'id')->toArray();

    }

    public static function getGroup($id)
    {
        return Models\Groups::where('id', '=', $id)->first()->toArray();
    }

    public static function getGroupWithProducts($id)
    {
        $out             = self::getGroup($id);
        $out['products'] = ProductGroups\Manage::getProducts($id);
        return $out;
    }

    public static function delete($id)
    {
        Models\Groups::where('id', '=', $id)->delete();
    }

    public static function update($field, $condition, $value, $data)
    {
        Models\Groups::where($field, $condition, $value)->update($data);
    }

    public static function checkType($groupId)
    {
        return Models\Groups::select('type')->where('id', '=', $groupId)->value('type');
    }

    public static function checkIfTypeChanged($type, $groupid)
    {
        $result = Models\Groups::where('type', '=', $type)->where('id', '=', $groupid)->value('type');
        if (!$result)
        {
            GroupConfiguration\Manage::deleteStepsForGroup($groupid);
            return true;
        }
        return false;
    }
    
    public static function getValueForGroup($groupid, $value)
    {
        return Models\Groups::where('id', '=', $groupid)->value($value);
    }
    
    public static function getEnabledGroups()
    {
        return Models\Groups::where('status', '=', 'on')->get();
    }

}
