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

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

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

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

    $status = trim($_POST['status']);
    if ( !$status ) {
        $status = 'Active';
    }

    $sheetId = trim($_POST['sheetId']);
    if ( !$sheetId ) {
        session_start();
        $_SESSION['error'] = 'Sheet ID cannot be blank';

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

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

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

    if ( strlen($zip) != 5 ) {
        session_start();
        $_SESSION['error'] = 'ZIP must be 5 characters';

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

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

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

    $projectUpdate = [
        'title'   => $title,
        'status'  => $status,
        'sheetId' => $sheetId,
        'zip'     => $zip,
        'city'    => $city,
    ];

    $db->update('project', $projectUpdate, ['id' => $_POST['projectId']]);


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

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

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

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