<?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;
    }

    if ( $db->cell("SELECT email FROM user WHERE email = ?", $_POST['email']) ) {
        session_start();
        $_SESSION['error'] = 'A user with that email address already exists';

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

    if ( $_POST['ssEmail'] ) {
        if ( $db->cell("SELECT ssEmail FROM user WHERE ssEmail = ?", $_POST['ssEmail']) ) {
            session_start();
            $_SESSION['error'] = 'A user with that Smartsheet email address already exists';

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

    $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
    ;

    $userInsert = [
        'clientId'   => 0,
        'name'       => $name,
        'email'      => $_POST['email'],
        'admin'      => $admin,
        'ssEmail'    => $_POST['ssEmail'],
        'superAdmin' => $superAdmin,
        'active'     => $active,
        'createdBy'  => $user['id'],
        'createdAt'  => date('Y-m-d H:i:s'),
    ];

    $db->insert('user', $userInsert);

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

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