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

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

    if ( !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
        session_start();
        $_SESSION['error'] = 'Invalid email address';

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

    if ( $_POST['ssEmail'] ) {
        if ( !filter_var($_POST['ssEmail'], FILTER_VALIDATE_EMAIL) ) {
            session_start();
            $_SESSION['error'] = 'Invalid Smartsheet email address';

            header('Location: '.URL_APP_ADMIN.'/?page=u');
            exit;
        }
    } else {
        $_POST['ssEmail'] = NULL;
    }

    $name = trim($_POST['name']);
    if ( !$name ) {
        session_start();
        $_SESSION['error'] = 'Name cannot be blank';

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

    $admin = ( $_POST['admin'] == 'on' || $_POST['admin'] == 1 )
        ? 1
        : 0
    ;

    $superAdmin = ( $_POST['superAdmin'] == 'on' || $_POST['superAdmin'] == 1 )
        ? 1
        : 0
    ;

    $active = ( $_POST['active'] == 'on' || $_POST['active'] == 1 )
        ? 1
        : 0
    ;

    $userUpdate = [
        'name'       => $name,
        'email'      => $_POST['email'],
        'ssEmail'    => $_POST['ssEmail'],
        'admin'      => $admin,
        'superAdmin' => $superAdmin,
        'active'     => $active,
    ];

    $db->update('user', $userUpdate, ['id' => $_POST['userId']]);

    $db->delete('project_email_notification', ['userId' => $_POST['userId']]);
    foreach ( $_POST['userProjectNotifications'] as $projectId ) {
        $db->insert('project_email_notification', ['userId' => $_POST['userId'], 'projectId' => $projectId]);
    }

    session_start();
    $_SESSION['error'] = 'User updated';

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