<?php
    if ( !$user['superAdmin'] ) {
        session_start();
        $_SESSION['error'] = 'Unauthorized';

        header('Location: '.URL_APP_ADMIN);
        exit;
    }

    if ( !$client = $db->row("SELECT * FROM client WHERE id = ?", $_POST['clientId']) ) {
        session_start();
        $_SESSION['error'] = 'Invalid client ID';

        header('Location: '.URL_APP_ADMIN.'/?page=c');
        exit;
    }

    $whitelist = [
        '30 minutes',
        '1 hour',
        '4 hours',
        '12 hours',
        '24 hours',
        '48 hours'
    ];

    $tokenLifetime = ( in_array($_POST['tokenLifetime'], $whitelist) )
        ? $_POST['tokenLifetime']
        : '30 minutes'
    ;

    $client['user'] = $db->row("SELECT * FROM user WHERE clientId = ?", $_POST['clientId']);

    $selector    = bin2hex(random_bytes(12));
    $token       = bin2hex(random_bytes(32));
    $hashedToken = hash('sha256', $token);
    $expiresAt   = date('Y-m-d H:i:s', strtotime('+'.$tokenLifetime, time()));
    
    $db->insert('auth_token', [
        'selector'  => $selector,
        'token'     => $hashedToken,
        'expiresAt' => $expiresAt,
        'userId'    => $client['user']['id'],
    ]);
    
    //send an email with the selector and token
    $tokenString = base64_encode("$selector:$token");
    $queryString = "t=$tokenString&r=1";

    try {
        $dMessageTransport = (new Swift_SmtpTransport(EMAIL_SMTP, 587));
        $dMessageMailer    = new Swift_Mailer($dMessageTransport);
        $dMessageSubject   = COMPANY_NAME.' Client Portal Login';
        $dMessage          = (new Swift_Message($dMessageSubject));

        $dTo[$client['email']] = COMPANY_NAME.' Client';

        ob_start();
?>
            <h3><?php echo COMPANY_NAME; ?> Client Portal Login</h3>
            <p>Click the link below to login to your Client Portal. The link is valid for <?php echo $tokenLifetime; ?>.</p>
            <p><a href="<?php echo URL_APP_LOGIN ?>login.php?<?php echo $queryString; ?>">LOGIN</a></p>
<?php
        $dMessageHtml = ob_get_clean();

        $dMessage->setFrom([EMAIL_FROM_ADDRESS => EMAIL_FROM_NAME])
            ->setTo($dTo)
            ->setBody($dMessageHtml, 'text/html')
        ;

        $dMessageResult = $dMessageMailer->send($dMessage);
    } catch ( Exception $e ) {
        //log it, notify
    }

    session_start();
    $_SESSION['error'] = 'Login token sent';

    header('Location: '.URL_APP_ADMIN.'/?page=c');
    exit;