<?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=c');
        exit;
    }

    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=c');
        exit;
    }

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

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

    $clientInsert = [
        'email' => $_POST['email']
    ];
    $clientInsert['createdBy'] = $user['id'];
    $clientInsert['createdAt'] = date('Y-m-d H:i:s');
    $clientInsert['social']    = ( $_POST['social'] == 'on' || $_POST['social'] == 1 )
        ? 1
        : 0
    ;
    $clientInsert['observer'] = ( $_POST['observer'] == 'on' || $_POST['observer'] == 1 )
        ? 1
        : 0
    ;

    $db->insert('client', $clientInsert);

    $clientId = $db->cell("SELECT id FROM client WHERE email = ?", $clientInsert['email']);

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

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

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

    $userId = $db->cell("SELECT id FROM user WHERE clientId = ? AND email = ?", $userInsert['clientId'], $userInsert['email']);
    $db->update('client', ['userId' => $userId], ['id' => $clientId]);

    if ( $_POST['addProjectClient'] ) {
        $ids = $_POST['projects'];
        foreach ( $ids as $id ) {
            $db->insert('client_project', ['clientId' => $clientId, 'projectId' => $id]);
        }
    }

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

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