<?php
require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/orders.php';

$user = sparrow_require_backyard_login();

$bulk_action = $_POST['bulk_action'] ?? '';
$order_ids = $_POST['order_ids'] ?? [];

if (!is_array($order_ids)) {
    $order_ids = [$order_ids];
}

$order_ids = array_filter(array_map('intval', $order_ids));
$order_ids = array_values(array_unique($order_ids));

if (!$order_ids || $bulk_action === '') {
    sparrow_redirect('/backyard/dashboard.php');
}

if ($bulk_action === 'print_invoice') {
    sparrow_redirect(
        '/backyard/invoice.php?ids=' . implode(',', $order_ids)
    );
}

if ($bulk_action === 'print_packing_slip') {
    sparrow_redirect(
        '/backyard/packing-slip.php?ids=' . implode(',', $order_ids)
    );
}

if ($bulk_action === 'print_work_log') {
    sparrow_redirect(
        '/backyard/work-log.php?ids=' . implode(',', $order_ids)
    );
}

foreach ($order_ids as $order_id) {
    if ($bulk_action === 'trash') {
        sparrow_trash_order($order_id);
    }

    if ($bulk_action === 'restore') {
        sparrow_restore_order($order_id);
    }

    if ($bulk_action === 'delete_permanent') {
        sparrow_delete_order_permanent($order_id);
    }
}

if ($bulk_action === 'restore' || $bulk_action === 'delete_permanent') {
    sparrow_redirect('/backyard/trash.php');
}

sparrow_redirect('/backyard/dashboard.php');
