<?php

namespace ModulesGarden\HostingQuotaNotifications\App\Libs\Usage;


use ModulesGarden\HostingQuotaNotifications\App\Helper\Pages\Services\Formatter;
use ModulesGarden\HostingQuotaNotifications\App\Helper\Tables;
use ModulesGarden\HostingQuotaNotifications\App\Models\Usage;
use ModulesGarden\HostingQuotaNotifications\Core\Models\Whmcs\Client;
use ModulesGarden\HostingQuotaNotifications\Core\Models\Whmcs\Hosting;
use ModulesGarden\HostingQuotaNotifications\Core\Models\Whmcs\Product;


/**
 * Class Manage
 *
 * @author Artur Pilch <artur.pi@modulesgarden.com>
 */
class Manage
{
    public static function saveByFill($data)
    {
        $usageModel = new Usage();
        $usageModel->fill($data);
        $usageModel->save();
    }

    public static function getUsages($hid)
    {
        return Usage::where('hid', '=', $hid)->get()->toArray();
    }

    public static function getServicesUsage()
    {
        $hostingTableName = (new Hosting())->getTable();
        $clientTableName  = (new Client()) ->getTable();
        $productTableName = (new Product())->getTable();
        $usageTableName   = Tables::tableNames('usage');

        $services = Hosting::select("{$hostingTableName}.id", "{$hostingTableName}.id AS service", "{$hostingTableName}.domain", "{$hostingTableName}.userid", "{$hostingTableName}.packageid")
            ->selectRaw("{$productTableName}.name AS productName")
            ->selectRaw("concat({$clientTableName}.firstname, ' ', {$clientTableName}.lastname) as client")
            ->join($clientTableName , "{$clientTableName}.id"  ,'=', "{$hostingTableName}.userid")
            ->join($productTableName, "{$productTableName}.id" ,'=', "{$hostingTableName}.packageid")
            ->join($usageTableName  , "{$usageTableName}.hid"  ,'=', "{$hostingTableName}.id")
            ->orderBy("{$hostingTableName}.id")
            ->distinct()
            ->get();


        return $services;
    }
}