<?php
if ( !$user['superAdmin'] ) {
    if ( !$exists = $db->cell("SELECT id FROM client_project WHERE clientId = ? AND projectId = ?", $user['client']['id'], $_POST['id']) ) {
        http_response_code(403);
        echo json_encode('You do not have permission to order selection groups on this project');
        exit;
    }
}

if ( !$project = $db->row("SELECT * FROM project WHERE id = ?", $_POST['id']) ) {
    http_response_code(400);
    echo json_encode('Invalid project ID');
    exit;
}

// $order = json_decode($_POST['order']);
$orders = $_POST['order'];
foreach ( $orders as $order ) {
    if ( !$group = $db->row("SELECT * FROM selection_group WHERE id = ? AND projectId = ?", $order['id'], $_POST['id']) ) {
        http_response_code(400);
        echo json_encode('Invalid selection group ID');
        exit;
    }
    $db->update('selection_group', ['sort' => $order['order']], ['id' => $order['id'], 'projectId' => $_POST['id']]);
}


// if ( !$publicProjectAttachment = $db->row("SELECT * FROM public_project_attachment WHERE id = ?", $_POST['id']) ) {
//     http_response_code(400);
//     echo json_encode('Invalid public project attachment ID');
//     exit;
// } 
// $txt .= print_r($publicProjectAttachment, true);

// $db->delete('public_project_attachment', ['id' => $_POST['id']]);

// $txt .= "done\n\n\n\n";
// $file = fopen(PATH_LOGS.'/btb.delete-public-project-image.log', "a");
// fwrite($file, $txt);
// fclose($file);

http_response_code(200);
echo json_encode('Selection groups ordered');