<?php
declare(strict_types = 1);

require_once(__DIR__ . '/Admin.class.php');

/**
 * Informations du tableau de bord.
 *
 * @license https://www.gnu.org/licenses/gpl-3.0.html
 * @link https://www.igalerie.org/
 */
class AdminDashboard extends Admin
{
	/**
	 * Récupération des derniers commentaires.
	 *
	 * @return void
	 */
	public static function comments(): void
	{
		if (!Config::$params['comments'])
		{
			return;
		}

		require_once(__DIR__ . '/AdminComments.class.php');

		$sql = 'SELECT com.*,
					   i.item_id,
					   item_type,
					   item_adddt,
					   item_name,
					   item_path,
					   item_status,
					   item_duration,
					   item_tb_params AS tb_params,
					   cat.cat_id,
					   cat.cat_name,
					   u.user_id,
					   user_avatar,
					   user_login,
					   user_nickname
				  FROM {comments} AS com
			 LEFT JOIN {items} AS i
					ON i.item_id = com.item_id
			 LEFT JOIN {categories} AS cat
					ON cat.cat_id = i.cat_id
			 LEFT JOIN {users} AS u
					ON u.user_id = com.user_id
				 WHERE com_status = "1"
				   AND item_status = "1"
			  ORDER BY com_id DESC
				 LIMIT 10';
		if (DB::execute($sql))
		{
			$last_comments = [];
			foreach (DB::fetchAll() as &$i)
			{
				$last_comments[] = AdminComments::getFormatedInfos($i);
			}
			Template::set('dashboard',
			[
				'last_comments_count' => count($last_comments),
				'last_comments' => $last_comments
			]);
		}
	}

	/**
	 * Nombre d'incidents.
	 *
	 * @return void
	 */
	public static function errors(): void
	{
		Template::set('dashboard',
		[
			'errors' => (CONF_DEBUG_MODE || CONF_DEV_MODE)
				? count(glob(GALLERY_ROOT . '/errors/*.xml'))
				: 0
		]);
	}

	/**
	 * Récupération des dernières images et vidéos.
	 *
	 * @return void
	 */
	public static function items(): void
	{
		$sql = 'SELECT item_id,
		               item_type,
					   item_adddt,
					   item_pubdt,
					   item_width,
					   item_height,
					   item_duration,
					   item_orientation,
					   item_name,
					   item_path,
					   item_url,
					   item_tb_params AS tb_params,
					   cat.cat_id,
					   cat.cat_name,
					   cat.cat_url,
					   u.user_id,
					   u.user_login,
					   u.user_nickname
				  FROM {items} AS i
			 LEFT JOIN {users} AS u
					ON i.user_id = u.user_id
			 LEFT JOIN {categories} AS cat
					ON i.cat_id = cat.cat_id
				 WHERE item_status = "1"
			  ORDER BY item_id DESC
				 LIMIT 10';
		if (!DB::execute($sql))
		{
			return;
		}
		$last_items = [];
		foreach (DB::fetchAll() as &$i)
		{
			$last_items[] =
			[
				'cat_id' => $i['cat_id'],
				'cat_name' => $i['cat_name'],
				'duration_text' => $i['item_duration']
					? App::formatDuration($i['item_duration'])
					: '00:00',
				'id' => $i['item_id'],
				'pubdt' => L10N::dt(__('%A %d %B %Y'), $i['item_pubdt']),
				'title' => $i['item_name'],
				'thumb_src' => function() use ($i)
				{
					return htmlspecialchars(App::getThumbSource('item',
						$i, self::$thumbSize, self::$thumbQuality));
				},
				'type' => Item::isVideo($i['item_type']) ? 'video' : 'image',
				'user_id' => $i['user_id'],
				'user_nickname' => User::getNickname($i['user_login'], $i['user_nickname'])
			];
		}
		Template::set('dashboard',
		[
			'last_items_count' => count($last_items),
			'last_items' => $last_items
		]);
	}

	/**
	 * Dates d'expiration et de publication.
	 *
	 * @return void
	 */
	public static function dates(): void
	{
		foreach (['expiration' => 'item_expdt', 'publication' => 'item_pubdt'] as $type => $col)
		{
			if (empty(Config::$params["dates_$type"]))
			{
				continue;
			}

			$sql_status = $col == 'item_expdt' ? "'1'" : "'-1', '0'";
			$sql = "SELECT COUNT(*) AS count,
						   $col,
						   cat_id,
						   cat_name
					  FROM {items}
				 LEFT JOIN {categories} USING (cat_id)
					 WHERE $col > NOW()
					   AND item_status IN ($sql_status)
				  GROUP BY cat_id, cat_name, $col
				  ORDER BY $col ASC";
			if (!DB::execute($sql))
			{
				continue;
			}

			$scheduled = [];
			foreach (DB::fetchAll() as &$i)
			{
				$scheduled[] =
				[
					'cat_link' => App::getURL('album/' . $i['cat_id']),
					'cat_name' => $i['cat_name'],
					'count' => L10N::formatNumber((int) $i['count']),
					'date' => L10N::dt(__('%A %d %B %Y à %H:%M:%S'), $i[$col]),
					'text' => $col == 'item_expdt'
						? ($i['count'] > 1
							? __('%s fichiers seront désactivés le %s dans l\'album %s.')
							: __('%s fichier sera désactivé le %s dans l\'album %s.'))
						: ($i['count'] > 1
							? __('%s fichiers seront activés le %s dans l\'album %s.')
							: __('%s fichier sera activé le %s dans l\'album %s.'))
				];
			}
			if ($scheduled)
			{
				Template::set('dashboard', ['scheduled' => [$type => $scheduled]]);
			}
		}
	}

	/**
	 * Vérification de la disponibilité d'une nouvelle version.
	 *
	 * @return void
	 */
	public static function newVersion(): void
	{
		Template::set('dashboard', ['new_version' => FALSE]);

		if (!Config::$params['new_version_check'] || !Update::isAllowedHTTPOrigin())
		{
			return;
		}

		if (Config::$params['new_version_check_date'] != date('Y-m-d'))
		{
			$new_version = Update::getLatestVersion();
			Config::changeDBParams(
			[
				'new_version' => $new_version,
				'new_version_check_date' => date('Y-m-d')
			]);
		}
		else
		{
			$new_version = Config::$params['new_version'];
		}

		if (is_array($new_version)
		&& isset($new_version['version']) && isset($new_version['php']))
		{
			$app_version = (string) $new_version['version'];
			$php_version = (string) $new_version['php'];
			if (preg_match(Update::VERSION_REGEXP, $app_version)
			&& preg_match(Update::VERSION_REGEXP, $php_version)
			&& version_compare(System::APP_VERSION, $app_version, '<'))
			{
				Template::set('dashboard', ['new_version' => $app_version]);
				Template::set('dashboard', ['new_version_php' => $php_version]);
				Template::set('dashboard', ['new_version_php_ok'
					=> version_compare(System::getPHPVersion(), $php_version, '>=')
				]);
			}
		}
	}

	/**
	 * Récupération des objets en attente de validation.
	 *
	 * @return void
	 */
	public static function pending(): void
	{
		// Fichiers en attente.
		if (Config::$params['users'])
		{
			$sql = 'SELECT COUNT(*) FROM {items_pending}';
			if (DB::execute($sql) && $count = DB::fetchVal())
			{
				Template::set('dashboard',
				[
					'pending' =>
					[
						'items' => $count > 1
							? sprintf(__('%s fichiers'), L10N::formatNumber((int) $count))
							: sprintf(__('%s fichier'), L10N::formatNumber((int) $count))
					]
				]);
			}
		}

		// Utilisateurs en attente.
		if (Config::$params['users'])
		{
			$sql = 'SELECT count(*) FROM {users} WHERE user_status = "-1"';
			if (DB::execute($sql) && $count = DB::fetchVal())
			{
				Template::set('dashboard',
				[
					'pending' =>
					[
						'users' => $count > 1
							? sprintf(__('%s utilisateurs'), L10N::formatNumber((int) $count))
							: sprintf(__('%s utilisateur'), L10N::formatNumber((int) $count))
					]
				]);
			}
		}

		// Commentaires en attente.
		if (Config::$params['comments'])
		{
			$sql = 'SELECT count(*) FROM {comments} WHERE com_status = "-1"';
			if (DB::execute($sql) && $count = DB::fetchVal())
			{
				Template::set('dashboard',
				[
					'pending' =>
					[
						'comments' => $count > 1
							? sprintf(__('%s commentaires'), L10N::formatNumber((int) $count))
							: sprintf(__('%s commentaire'), L10N::formatNumber((int) $count))
					]
				]);
			}
		}
	}

	/**
	 * Statistiques de la galerie.
	 *
	 * @return void
	 */
	public static function stats(): void
	{
		$sql = 'SELECT cat_a_size,
					   cat_a_albums,
					   cat_a_images,
					   cat_a_videos,
					   cat_a_hits,
					   cat_a_comments,
					   cat_a_votes,
					   cat_a_favorites
				  FROM {categories}
				 WHERE cat_id = 1';
		if (!DB::execute($sql))
		{
			return;
		}
		$gallery_stats = DB::fetchRow();

		Template::set('dashboard',
		[
			'comments_count' => $gallery_stats['cat_a_comments'],
			'favorites_count' => $gallery_stats['cat_a_favorites'],
			'filesize' => L10N::formatFilesize($gallery_stats['cat_a_size']),
			'hits_count' => $gallery_stats['cat_a_hits'],
			'images_count' => $gallery_stats['cat_a_images'],
			'items_count' => $gallery_stats['cat_a_images'] + $gallery_stats['cat_a_videos'],
			'videos_count' => $gallery_stats['cat_a_videos'],
			'votes_count' => $gallery_stats['cat_a_votes']
		]);

		// Nombre d'albums.
		$sql = 'SELECT COUNT(*)
				  FROM {categories}
				 WHERE cat_filemtime IS NOT NULL
				   AND cat_status = "1"
				   AND thumb_id > -1';
		if (DB::execute($sql))
		{
			Template::set('dashboard', ['albums_count' => DB::fetchVal()]);
		}

		// Nombre de tags.
		if (Config::$params['tags'])
		{
			$sql = 'SELECT COUNT(DISTINCT(t.tag_id))
					  FROM {tags} AS t
				 LEFT JOIN {tags_items} AS ti
						ON t.tag_id = ti.tag_id
				 LEFT JOIN {items} AS i
						ON ti.item_id = i.item_id
					 WHERE item_status = "1"';
			if (DB::execute($sql))
			{
				Template::set('dashboard', ['tags_count' => DB::fetchVal()]);
			}
		}

		// Nombre de membres.
		if (Config::$params['users'])
		{
			$sql = 'SELECT COUNT(*)
					  FROM {users} AS u,
						   {groups} as g
					 WHERE u.group_id = g.group_id
					   AND user_status = "1"
					   AND user_id != 2
					   AND group_admin = "0"';
			if (DB::execute($sql))
			{
				Template::set('dashboard', ['members_count' => DB::fetchVal()]);
			}
		}

		// Nombre d'administrateurs.
		$sql = 'SELECT COUNT(*)
				  FROM {users} AS u,
					   {groups} as g
				 WHERE u.group_id = g.group_id
				   AND user_status = "1"
				   AND user_id != 2
				   AND group_admin = "1"';
		if (DB::execute($sql))
		{
			Template::set('dashboard', ['admins_count' => DB::fetchVal()]);
		}

		// Nombre de groupes.
		if (DB::execute('SELECT COUNT(*) FROM {groups}'))
		{
			Template::set('dashboard', ['groups_count' => DB::fetchVal()]);
		}
	}

	/**
	 * Récupération des informations système.
	 *
	 * @return void
	 */
	public static function system(): void
	{
		Template::set('dashboard',
		[
			'app_version' => Config::$params['app_version'],
			'db_type' => DB::NAME,
			'db_version' => DB::$version,
			'os_infos' => System::getOSInfos('srm'),
			'php_version' => System::getPHPVersion()
		]);
	}

	/**
	 * Récupération des derniers utilisateurs
	 * et du nombre d'utilisateurs en attente de validation.
	 *
	 * @return void
	 */
	public static function users(): void
	{
		if (!Config::$params['users'])
		{
			return;
		}

		// Derniers utilisateurs.
		$sql = 'SELECT user_id,
					   user_login,
					   user_nickname,
					   user_avatar,
					   user_crtdt,
					   group_admin
				  FROM {users}
			 LEFT JOIN {groups} USING (group_id)
				 WHERE user_status = "1"
				   AND user_id NOT IN (2)
			  ORDER BY user_id DESC
				 LIMIT 10';
		if (DB::execute($sql))
		{
			$last_users = DB::fetchAll();
			foreach ($last_users as &$i)
			{
				$i['avatar_thumb_src'] = Avatar::getURL(
					(int) $i['user_id'], (bool) $i['user_avatar']
				);
				$i['user_nickname'] = User::getNickname($i['user_login'], $i['user_nickname']);
				$i['user_crtdt'] = L10N::dt(__('%A %d %B %Y'), $i['user_crtdt']);
			}
			Template::set('dashboard',
			[
				'last_users_count' => count($last_users),
				'last_users' => $last_users
			]);
		}
	}

	/**
	 * Message de bienvenue.
	 *
	 * @return void
	 */
	public static function welcome(): void
	{
		Template::set('welcome', (int) (bool) Config::$params['welcome']);

		if (isset($_POST['welcome_hide']))
		{
			Config::changeDBParams(['welcome' => 0]);
			Template::set('welcome', 0);
		}

		else if (Config::$params['welcome'])
		{
			if (file_exists($upgrade_file = GALLERY_ROOT . '/upgrade.php'))
			{
				File::unlink($upgrade_file);
			}
			if (is_dir($install_dir = GALLERY_ROOT . '/install'))
			{
				File::rmdir($install_dir);
			}
		}
	}
}
?>