<?php

namespace ModulesGarden\HostingQuotaNotifications\App\Libs\Notifications;

use \ModulesGarden\HostingQuotaNotifications\App\Models\Notifications;
use \ModulesGarden\HostingQuotaNotifications\Core\Models\Whmcs\Ticket;

/**
 * Description of Manage
 *
 * @author Artur Pilch <artur.pi@modulesgarden.com>
 */
class Manage
{

    public static function getLastNotification($hostingid, $kind, $type, $groupid)
    {
        $notification = Notifications::where('hostingid', '=', $hostingid)
                ->where('kind', '=', $kind)
                ->where('type', '=', $type)
                ->where('groupid', '=', $groupid)
                ->orderBy('date', 'desc')
                ->first();
        return $notification ? $notification->toArray() : [];
    }

    public static function getLastNotificationValue($hostingid, $kind, $type, $groupid, $value)
    {
        $notificataion = self::getLastNotification($hostingid, $kind, $type, $groupid);
        if (empty($notificataion))
        {
            return null;
        }
        return $notificataion[$value];
    }

    public static function isTicketOpen($hostingid, $kind, $type, $groupid)
    {
        $ticketTable       = (new Ticket())->getTable();
        $notificationTable = (new Notifications())->getTable();
        $ticket = Notifications::select($notificationTable . '.ticketid')
                ->join($ticketTable, $notificationTable . '.ticketid', '=', $ticketTable . '.id')
                ->where($notificationTable . '.hostingid', '=', $hostingid)
                ->where($notificationTable . '.kind', '=', $kind)
                ->where($notificationTable . '.type', '=', $type)
                ->where($notificationTable . '.groupid', '=', $groupid)
                ->where($notificationTable . '.ticketid', '!=', 0)
                ->orderBy($notificationTable .'.id', 'desc')
                ->first();
        return $ticket ? $ticket->ticketid : false;
    }
    
    public static function insert($data)
    {
        $notification = new Notifications();
        $notification->fill($data);
        $notification->save();
    }
    
    public static function update($hostingid, $kind, $type, $groupid, $update)
    {
        Notifications::where('hostingid', '=', $hostingid)
                ->where('kind', '=', $kind)
                ->where('type', '=', $type)
                ->where('groupid', '=', $groupid)
                ->orderBy('id', 'desc')
                ->limit(1)
                ->update($update);
    }

    public static function saveByFill($data)
    {
        $notification = new Notifications();
        $notification->fill($data);
        $notification->save();
    }
}
