```php
<?php
// export_report.php
session_start();
require_once 'config/db_config.php'; // expects $pdo (PDO)

// ---- Auth (admins and branch users) ----
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role'])) {
    header("Location: login.php");
    exit();
}

// ---- CSRF token validation ----
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['csrf']) || $_POST['csrf'] !== $_SESSION['csrf_token']) {
    $_SESSION['error'] = "Invalid CSRF token.";
    header("Location: reports.php");
    exit();
}

// ---- Helpers ----
function h(string $v): string { return htmlspecialchars($v, ENT_QUOTES, 'UTF-8'); }
function csv_escape(string $v): string {
    return '"' . str_replace('"', '""', $v) . '"';
}

// ---- Determine filters ----
$selected_branch_id = $_SESSION['role'] === 'branch' ? $_SESSION['branch_id'] : ($_POST['branch_id'] ?? 'all');
$start_date = $_POST['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
$end_date = $_POST['end_date'] ?? date('Y-m-d');
$status = $_POST['status'] ?? 'all';

$where_clause = ["o.order_date BETWEEN :start_date AND :end_date"];
$params = ['start_date' => $start_date . ' 00:00:00', 'end_date' => $end_date . ' 23:59:59'];

if ($selected_branch_id !== 'all' && is_numeric($selected_branch_id)) {
    $where_clause[] = 'o.branch_id = :branch_id';
    $params['branch_id'] = $selected_branch_id;
}
if ($status !== 'all' && in_array($status, ['pending', 'processing', 'completed', 'cancelled'])) {
    $where_clause[] = 'o.status = :status';
    $params['status'] = $status;
}

// ---- Fetch tax rates ----
$tax_rates = [];
try {
    $stmt = $pdo->prepare("
        SELECT branch_id, cgst_rate, sgst_rate
        FROM taxes
        WHERE effective_date <= :end_date
        ORDER BY effective_date DESC
    ");
    $stmt->execute(['end_date' => $end_date]);
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $tax) {
        $tax_rates[$tax['branch_id']] = ['cgst' => $tax['cgst_rate'], 'sgst' => $tax['sgst_rate']];
    }
} catch (PDOException $e) {
    $_SESSION['error'] = "Error fetching tax rates: " . h($e->getMessage());
    header("Location: reports.php");
    exit();
}

// ---- Fetch orders for export ----
try {
    $query = "
        SELECT o.order_id, o.customer_name, o.customer_contact, o.order_date, o.total_amount, o.status, o.branch_id, b.branch_name
        FROM orders o
        JOIN branches b ON o.branch_id = b.branch_id
        " . (!empty($where_clause) ? "WHERE " . implode(' AND ', $where_clause) : "") . "
        ORDER BY o.order_date DESC
    ";
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $_SESSION['error'] = "Error fetching orders: " . h($e->getMessage());
    header("Location: reports.php");
    exit();
}

// ---- Generate CSV ----
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="orders_report_' . date('Ymd_His') . '.csv"');

$output = fopen('php://output', 'w');
fwrite($output, "\xEF\xBB\xBF"); // UTF-8 BOM for Excel compatibility

// CSV Headers
fputcsv($output, [
    'Order ID',
    'Customer Name',
    'Customer Contact',
    'Order Date',
    'Total Amount ($)',
    'Net Amount ($)',
    'CGST ($)',
    'SGST ($)',
    'Status'
]);

// CSV Data
foreach ($orders as $order) {
    $branch_id = $order['branch_id'];
    $cgst_rate = $tax_rates[$branch_id]['cgst'] ?? 0;
    $sgst_rate = $tax_rates[$branch_id]['sgst'] ?? 0;
    $total_tax_rate = ($cgst_rate + $sgst_rate) / 100;
    $net_amount = $order['total_amount'] / (1 + $total_tax_rate);
    $tax_amount = $order['total_amount'] - $net_amount;
    $cgst_amount = $tax_amount * ($cgst_rate / ($cgst_rate + $sgst_rate));
    $sgst_amount = $tax_amount * ($sgst_rate / ($cgst_rate + $sgst_rate));

    fputcsv($output, [
        $order['order_id'],
        $order['customer_name'] ?: 'Walk-in Customer',
        $order['customer_contact'],
        date('d M Y, H:i', strtotime($order['order_date'])),
        number_format($order['total_amount'], 2),
        number_format($net_amount, 2),
        number_format($cgst_amount, 2),
        number_format($sgst_amount, 2),
        ucfirst($order['status'])
    ]);
}

fclose($output);
exit();
?>
```