<?php

    if ( !isset($_POST['comments']) ) {
        session_start();
        $_SESSION['error'] = 'Your request was invalid';

        header("Location: ".URL_APP."/dashboard/");
        exit;
    } else {
        $comments = $_POST['comments'];
    }

    if ( !isset($_POST['projectId']) ) {
        session_start();
        $_SESSION['error'] = 'Your request was invalid';

        header("Location: ".URL_APP."/dashboard/");
        exit;
    } else {
        $projectId = $_POST['projectId'];
    }

    if ( $user['client']['observer'] ) {
        session_start();
        $_SESSION['error'] = 'You do not have permission to use the contact feature';

        header("Location: ".URL_APP."/project/?projectId=$projectId");
        exit;
    }

    //project email notifications
    $pdo           = $db->getPdo();
    $stmt          = $pdo->prepare("SELECT user.email, user.name, user.superAdmin FROM user, project_email_notification WHERE (project_email_notification.projectId = ? AND project_email_notification.userId = user.id) OR user.superAdmin = 1 ORDER BY user.name ASC;");
    $exec          = $stmt->execute([$projectId]);
    $notifications = $stmt->fetchAll(\PDO::FETCH_ASSOC);

    $name = ( $user['name'] )
        ? $user['name']
        : $user['email']
    ;

    try {
        $dMessageTransport = (new Swift_SmtpTransport(EMAIL_SMTP, 587));
        $dMessageMailer    = new Swift_Mailer($dMessageTransport);
        $dMessageSubject   = COMPANY_ABBR." Client Portal - Message from $name";
        $dMessage          = (new Swift_Message($dMessageSubject));

        // $dTo[EMAIL_ADMIN_ADDRESS] = EMAIL_ADMIN_NAME;
        foreach ( $notifications as $notification ) {
            $dTo[$notification['email']] = $notification['name'];
        }

        ob_start();
?>
            <h3>Contact from <?php echo $name; ?></h3>
            <p>Time: <?php echo date('Y-m-d H:i:s', time()); ?></p>
            <p>Email: <?php echo $user['email']; ?></p>
            <p>Comments: <?php echo $comments; ?></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'] = 'Message sent';

    header("Location: ".URL_APP."/project/?projectId=$projectId");
    exit;
?>