<?php
session_start();
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role_id'], [1, 2])) {
    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();
}

$user_id = $_SESSION['user_id'];
$role_id = $_SESSION['role_id'];
$store_id = $_SESSION['store_id'] ?? null;
$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();
}

$allowed_ids = [];

if ($role_id == 2 && $store_id) {
    // Manager can only act on their store's deleted expenses
    $placeholders = implode(',', array_fill(0, count($selected_ids), '?'));
    $check_sql = "SELECT id FROM expenses WHERE id IN ($placeholders) AND store_id = ? AND deleted_at IS NOT NULL";
    $stmt = $conn->prepare($check_sql);

    $params = [...$selected_ids, $store_id];
    $types = str_repeat('i', count($params));
    $stmt->bind_param($types, ...$params);

    $stmt->execute();
    $result = $stmt->get_result();
    $allowed_ids = array_column($result->fetch_all(MYSQLI_ASSOC), 'id');
    $stmt->close();
} else {
    // Admin can access all selected IDs
    $allowed_ids = $selected_ids;
}

if (empty($allowed_ids)) {
    header("Location: expenses_trash.php?error=unauthorized_or_no_match");
    exit();
}

// Execute the action
$placeholders = implode(',', array_fill(0, count($allowed_ids), '?'));
$types = str_repeat('i', count($allowed_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);
$stmt->bind_param($types, ...$allowed_ids);

if ($stmt->execute()) {
    // Audit logging
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
    $module = 'expenses';
    $action_text = $action === 'restore' ? 'Bulk Restore Expenses' : 'Bulk Permanent Delete Expenses';

    foreach ($allowed_ids as $id) {
        $details = json_encode(["expense_id" => $id, "action" => $action]);

        $log_stmt = $conn->prepare("
            INSERT INTO audit_log (user_id, action, details, created_at, module, role_id, device_info)
            VALUES (?, ?, ?, NOW(), ?, ?, ?)
        ");
        $log_stmt->bind_param("isssiss", $user_id, $action_text, $details, $module, $role_id, $user_agent);
        $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();
}
?>
