<?php

use WHMCS\Database\Capsule;

/**
 * Standard add_hook call @see https://developers.whmcs.com/hooks/getting-started/
 */
add_hook('AdminHomeWidgets', 1, function() {
    /**
     * Return a new instance of the widget object for display
     */
    return new s10wa_adminwidget();
});

/**
 * Sample Widget example
 */
class s10wa_adminwidget extends \WHMCS\Module\AbstractWidget
{
    /**
     * @type string The title of the widget
     */
    protected $title = 'HostiNoz Whatsapp API';

    /**
     * @type string A description/purpose of the widget
     */
    protected $description = 'To show HostiNoz Whatsapp status and as a shortcut to the module';

    /**
     * @type int The sort weighting that determines the output position on the page
     */
    protected $weight = 10;

    /**
     * @type int The number of columns the widget should span (1, 2 or 3)
     */
    protected $columns = 1;

    /**
     * @type bool Set true to enable data caching
     */
    protected $cache = true;

    /**
     * @type int The length of time to cache data for (in seconds)
     */
    protected $cacheExpiry = 600;

	protected $wrapper = false;
	//protected $draggable = false;
	
    /**
     * @type string The access control permission required to view this widget. Leave blank for no permission.
     * @see Permissions section below.
     */
    protected $requiredPermission = '';

    /**
     * Get Data.
     *
     * Obtain data required to render the widget.
     *
     * We recommend executing queries and API calls within this function to enable
     * you to take advantage of the built-in caching functionality for improved performance.
     *
     * When caching is enabled, this method will be called when the cache is due for
     * a refresh or when the user invokes it.
     *
     * @return array
     */
    public function getData()
    {
		$mulai = date('Y-m-d H:i:s');

        $schema = Capsule::schema();

		if(!$schema->hasColumn('s10wa_sendmsg','s10wa_statusdate')){
			$schema->table('s10wa_sendmsg', function ($tabel) {
				$tabel->datetime('s10wa_statusdate')->after('s10wa_status')->useCurrent();
			});
		}	
		if(!$schema->hasColumn('s10wa_sendmsg','lastupdate')){
			$schema->table('s10wa_sendmsg', function ($tabel) {
				$tabel->timestamp('lastupdate')->after('s10wa_statusdate')->useCurrent();
			});
		}	
		
		$licconfig = WHMCS\Database\Capsule::table('s10wa_config')->select('suiten_lisensi','suiten_logretention')->first();
		$inqueue = WHMCS\Database\Capsule::table('s10wa_sendmsg')->select('id')->where('s10wa_status', 0)->count();
		$lastsentrecord = WHMCS\Database\Capsule::table('s10wa_sendmsg')->select('s10wa_sendid','lastupdate')->where('s10wa_status', '<>', '0')->orderBy('lastupdate', 'desc')->first();
		
		$ambiljumlahhari = $licconfig->suiten_logretention;
		if ($ambiljumlahhari > 0) {
			$jumlahhari = $ambiljumlahhari;
		} else {
			$jumlahhari = 30;
		}
		$tglhitung = \Carbon\Carbon::now()->subDays($jumlahhari);
		$kirimhitung = WHMCS\Database\Capsule::table('s10wa_sendmsg')->select('s10wa_sendid')->where('s10wa_date','>',$tglhitung)->where('s10wa_status', '=', '1')->count();

		$selesai = date('Y-m-d H:i:s');
		$durasi = $selesai - $mulai;
		
		return array(
			'inqueue' => $inqueue,
			'key' => $licconfig->suiten_lisensi,
			'lastsentid' => $lastsentrecord->s10wa_sendid,
			'lastsenttime' => $lastsentrecord->lastupdate,
			'kirimhitung' => $kirimhitung,
			'durasi' => $durasi,
			'lastdata' => $selesai,
			'jumlahhari' => $jumlahhari,
		);

    }

    /**
     * Generate Output.
     *
     * Generate and return the body output for the widget.
     *
     * @param array $data The data returned by the getData method.
     *
     * @return string
     */
    public function generateOutput($data)
    {
		$inqueue = (int) $data['inqueue'];
		$lickey = $data['key'];
		$lastid = $data['lastsentid'];
		$kirimhitung = $data['kirimhitung'];
		$terakhir = $data['lastdata'];
		$sekarang = date('Y-m-d H:i:s');
		$durasi = $data['durasi'];
		$jumlahhari = $data['jumlahhari'];
		$lalu = round((strtotime(date('Y-m-d H:i:s')) - strtotime($terakhir)) / 60,1);
		$next = date('d-M H:i:s', strtotime($terakhir. ' +10 minutes'));
		
		if ($inqueue == 0) {
			if ($kirimhitung == 0)  {
				$lastnote = '<span style="color: #fff;"> You have no message for the last 30 days</span>';
			} elseif ($kirimhitung == 1)  {
				$lastnote = '<span style="color: #fff;"> Delivered one message for the last 30 days</span>';
			} else {
				$lastnote = '<span style="color: #fff;"> Delivered '. $kirimhitung. ' messages for the last ' . $jumlahhari . ' days</span>';
			}
			$warnabg1 = "49a94d"; // dark-green
			$warnabg2 = "5dc560"; // green
		} else {

			$lastsent = $data['lastsenttime'];	
			$hourdiff = round((strtotime(date('Y-m-d H:i:s') ) - strtotime($lastsent))/3600, 1);

			$lastnote = '<span style="color: #fff;"><strong> '.$inqueue.' message'.(($inqueue == 1) ? '' : 's') .' </strong>in Queue</span><br/><span style="color: #fff;">Last Sent ['.$lastid.'] </span>
					<span style="color: #fff;"> at '.$lastsent.' ('.$hourdiff.' hour'. ($hourdiff <= 1 ? '' : 's').' ago)</span>';

			if ($hourdiff < 6) {
				$warnabg1 = "49a94d"; // dark-green
				$warnabg2 = "4a521e"; // army green
			} else {
				$warnabg1 = "49a94d"; // dark-green
				$warnabg2 = "8a0303"; // red
			}
						
		}
		//$footnote = "<br/><small>Last Update " . $terakhir . " (" . $lalu . "m ago in " . $durasi . "s)</small>";
		$footnote = "<br/><small>Next Update: " . $next  . "</small>";

        return <<<EOF
	<div style="padding-left: 7px;padding-right: 7px;">
		<div style="background-color: #{$warnabg2}; clearfix;">
			<div style="background-color: #{$warnabg1}; ">
				<p style="padding: 10px; color: #fff;">
					<a href="" style="color: #fff; text-decoration:none;">
						<i class="fas fa-comment" style="color: #fff;"></i>&nbsp;
					</a>
					HostiNoz Whatsapp API Status
				</p>
			</div>
			<div style="background-color: #{$warnabg2};">
				<p style="padding-left: 10px;padding-top: 5px;padding-bottom: 10px;">
					<a href="addonmodules.php?module=suiten_whatsapp" style="color: #fff; text-decoration:none;">
						{$lastnote}
					</a>
					{$footnote}
				</p>
			</div>
		</div>
	</div>
EOF;
    }
}