<?php
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

require_once __DIR__ . '/../required.php';

?>
<div class="card-deck">
    <div class="card bg-green text-light">
        <div class="card-body">
            <h4 class="card-title">Cached Accounts</h4>
            <h1><i class="fas fa-fw fa-users"></i> <?php echo $database->count('accounts'); ?></h1>
        </div>
    </div>
    <?php
    /**
     * This function from https://stackoverflow.com/a/18602474
     */
	function time_elapsed_string($datetime, $full = false) {
		$now = new DateTime;
		$ago = new DateTime($datetime);
		$diff = $now->diff($ago);

		$diff->w = floor($diff->d / 7);
		$diff->d -= $diff->w * 7;

		$string = array(
		    'y' => 'year',
		    'm' => 'month',
		    'w' => 'week',
		    'd' => 'day',
		    'h' => 'hour',
		    'i' => 'minute',
		    's' => 'second',
		);
		foreach ($string as $k => &$v) {
		    if ($diff->$k) {
		        $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
		    } else {
		        unset($string[$k]);
		    }
		}

		if (!$full) $string = array_slice($string, 0, 1);
		return $string ? implode(', ', $string) . ' ago' : 'Just now';
	}

    $lastsync = $database->get('config', "value", ["key" => "lastsync"]);
    $cardcolor = "blue";
    if ($lastsync == false) {
    	$cardcolor = "deep-orange";
		$syncstring = "Never";
    } else {
    	$diff = time() - $lastsync;
    	if ($diff > 60 * 10) {
    		$cardcolor = "deep-orange";
    	}
    	$syncstring = time_elapsed_string("@" . $lastsync);
    }
    ?>
    <div class="card bg-<?php echo $cardcolor; ?> text-light">
        <div class="card-body">
            <h4 class="card-title">Last Cloud Sync</h4>
            <h1><i class="fas fa-fw fa-cloud"></i> <?php echo $syncstring; ?></h1>
        </div>
        <div class="card-footer">
            <a href="sync.php" class="text-light"><i class="fas fa-sync"></i> Sync Now</a>
        </div>
    </div>
</div>
