<?php
session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] != 1) {
    header("Location: ../../index.php");
    exit();
}

include('../../includes/config.php');

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['selected_ids']) || !is_array($_POST['selected_ids']) || empty($_POST['selected_ids'])) {
    header("Location: expenses_trash.php?error=no_selection");
    exit();
}

$selected_ids = array_map('intval', $_POST['selected_ids']);
$action = $_POST['action'] ?? '';

if (!$selected_ids || !in_array($action, ['restore', 'permanent_delete'])) {
    header("Location: expenses_trash.php?error=invalid_action");
    exit();
}

$placeholders = implode(',', array_fill(0, count($selected_ids), '?'));

if ($action === 'restore') {
    $sql = "UPDATE expenses SET deleted_at = NULL WHERE id IN ($placeholders)";
} else {
    $sql = "DELETE FROM expenses WHERE id IN ($placeholders)";
}

$stmt = $conn->prepare($sql);
$types = str_repeat('i', count($selected_ids));
$stmt->bind_param($types, ...$selected_ids);

if ($stmt->execute()) {
    // Audit log entries for each ID
    $user_id = $_SESSION['user_id'];
    $role_id = $_SESSION['role_id'];
    $action_text = $action === 'restore' ? 'Bulk Restore Expenses' : 'Bulk Permanent Delete Expenses';

    foreach ($selected_ids as $id) {
        $details = "$action_text: Expense ID $id";
        $log_stmt = $conn->prepare("INSERT INTO audit_log (user_id, action, details, created_at, module, role_id) VALUES (?, ?, ?, NOW(), 'expenses', ?)");
        $log_stmt->bind_param("isss", $user_id, $action_text, $details, $role_id);
        $log_stmt->execute();
        $log_stmt->close();
    }

    $msg = $action === 'restore' ? 'restored' : 'deleted';
    header("Location: expenses_trash.php?bulk_{$msg}=1");
    exit();
} else {
    header("Location: expenses_trash.php?error=bulk_action_failed");
    exit();
}
