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

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

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

    $clientUpdate = [
        'email' => $_POST['email']
    ];

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

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

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

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

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

    $db->delete('client_project', ['clientId' => $_POST['clientId']]);
    foreach ( $_POST['clientProjects'] as $projectId ) {
        $db->insert('client_project', ['clientId' => $_POST['clientId'], 'projectId' => $projectId]);
    }

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

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