<?php

namespace Api\Controllers\Integration\Discord;

use Api\Core\Controller;
use Api\Services\UserService;
use DateTime;
use DateTimeZone;
use PDO;

class UserController extends Controller
{
  public function show($discordUserID)
  {
    $user = UserService::getByDiscordUserID($discordUserID);
    if (!$user) api()->notFound('USER_NOT_FOUND', 'User not found!');

    unset($user['password']);

    $roles = db()->prepare("SELECT R.id, R.name, R.slug, R.discordRoleID, AR.expiryDate FROM AccountRoles AR INNER JOIN Roles R ON R.id = AR.roleID WHERE AR.accountID = ?");
    $roles->execute([$user['id']]);
    if (!moduleIsDisabled('discord_bot')) {
	    $user['roles'] = array_map(function ($role) {
		    $expiryDate = $role["expiryDate"];
		    if ($expiryDate != '1000-01-01 00:00:00') {
			    // Format roles expiry date timezone (UTC+0)
			    try {
				    $timezone = (settings('timezone') == '' || settings('timezone') == null) ? 'UTC' : settings('timezone');
				    $expiryDateObj = new DateTime($role["expiryDate"], new DateTimeZone($timezone));
				    $expiryDate = $expiryDateObj->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s');
			    } catch (\Exception $e) {
				    $expiryDate = $role["expiryDate"]; // Return original date in case of error
			    }
		    }
		    $role['expiryDate'] = $expiryDate;
		    
		    return $role;
	    }, $roles->fetchAll(PDO::FETCH_ASSOC));
    } else {
			$user['roles'] = $roles->fetchAll(PDO::FETCH_ASSOC);
    }

    response()->json($user);
  }
}