<?php
session_start();
require_once '../config/database.php';
// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

// Get institution name and address from site settings database
require_once '../includes/site_settings.php';
$institution_name = get_setting($pdo, 'site_name', 'বিদ্যা সংগঠন');
$institution_address = get_setting($pdo, 'site_address', 'ঢাকা, বাংলাদেশ');

// Get filter parameters
$start_date = $_GET['start_date'] ?? date('Y-m-01');
$end_date = $_GET['end_date'] ?? date('Y-m-t');

// Calculate income
$incomeSql = "SELECT SUM(amount) as received_income, 
                     COUNT(*) as total_bills
              FROM fee_payments 
              WHERE payment_date BETWEEN ? AND ?";
$incomeStmt = $pdo->prepare($incomeSql);
$incomeStmt->execute([$start_date, $end_date]);
$incomeData = $incomeStmt->fetch();

// Calculate expenses
$expenseSql = "SELECT SUM(amount) as total_expenses, COUNT(*) as expense_count
               FROM expenses 
               WHERE expense_date BETWEEN ? AND ?";
$expenseStmt = $pdo->prepare($expenseSql);
$expenseStmt->execute([$start_date, $end_date]);
$expenseData = $expenseStmt->fetch();

// Get monthly breakdown
$monthlySql = "
    SELECT 
        DATE_FORMAT(fp.payment_date, '%Y-%m') as month,
        SUM(fp.amount) as received_income,
        COALESCE(e.total_expense, 0) as total_expense
    FROM fee_payments fp
    LEFT JOIN (
        SELECT DATE_FORMAT(expense_date, '%Y-%m') as month, SUM(amount) as total_expense
        FROM expenses 
        GROUP BY DATE_FORMAT(expense_date, '%Y-%m')
    ) e ON DATE_FORMAT(fp.payment_date, '%Y-%m') = e.month
    WHERE fp.payment_date BETWEEN ? AND ?
    GROUP BY DATE_FORMAT(fp.payment_date, '%Y-%m')
    UNION
    SELECT 
        DATE_FORMAT(e.expense_date, '%Y-%m') as month,
        0 as received_income,
        SUM(e.amount) as total_expense
    FROM expenses e
    WHERE e.expense_date BETWEEN ? AND ?
      AND DATE_FORMAT(e.expense_date, '%Y-%m') NOT IN (
          SELECT DISTINCT DATE_FORMAT(fp.payment_date, '%Y-%m') 
          FROM fee_payments fp 
          WHERE fp.payment_date BETWEEN ? AND ?
      )
    GROUP BY DATE_FORMAT(e.expense_date, '%Y-%m')
    ORDER BY month
";
$monthlyStmt = $pdo->prepare($monthlySql);
$monthlyStmt->execute([$start_date, $end_date, $start_date, $end_date, $start_date, $end_date]);
$monthlyData = $monthlyStmt->fetchAll(PDO::FETCH_ASSOC);

// Get category-wise expense breakdown
$categorySql = "
    SELECT ec.name as category_name, SUM(e.amount) as total_expense
    FROM expenses e
    JOIN expense_categories ec ON e.category_id = ec.id
    WHERE e.expense_date BETWEEN ? AND ?
    GROUP BY ec.name
    ORDER BY total_expense DESC
";
$categoryStmt = $pdo->prepare($categorySql);
$categoryStmt->execute([$start_date, $end_date]);
$categoryData = $categoryStmt->fetchAll(PDO::FETCH_ASSOC);

// Get previous balance for the given date range
$prevBalanceSql = "SELECT SUM(opening_balance) as total_prev_balance FROM previous_balances WHERE balance_date <= ?";
$prevBalanceStmt = $pdo->prepare($prevBalanceSql);
$prevBalanceStmt->execute([$end_date]);
$prevBalanceData = $prevBalanceStmt->fetch();

// Calculate net profit/loss
$receivedIncome = $incomeData['received_income'] ?? 0;
$totalExpenses = $expenseData['total_expenses'] ?? 0;
$netResult = $receivedIncome - $totalExpenses;
$previousBalance = $prevBalanceData['total_prev_balance'] ?? 0;
$currentBalance = $previousBalance + $netResult;
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>আয়-ব্যয় রিপোর্ট - <?php echo htmlspecialchars($institution_name); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background-color: #f4f7f6;
            direction: ltr;
            text-align: left;
        }
        
        .institution-header {
            text-align: center;
            margin: 20px 0;
            padding: 15px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .institution-name-main {
            font-size: 28px;
            font-weight: bold;
            color: #d32f2f;
            margin-bottom: 8px;
        }
        
        .institution-address-main {
            font-size: 16px;
            color: #666;
        }
        
        /* Override RTL for specific elements */
        .card-header, .card-body, .table, .form-label, .form-control, .form-select, .btn {
            direction: ltr;
            text-align: left;
        }
        
        /* Ensure table headers and cells are left-aligned */
        .table th, .table td {
            text-align: left;
        }
        
        /* Fix form elements */
        .form-control, .form-select {
            text-align: left;
        }
        .navbar {
            background: linear-gradient(135deg, #d32f2f 0%, #c62828 100%);
        }
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            margin-bottom: 1.5rem;
        }
        .table th {
            background-color: #d32f2f;
            color: white;
        }
        .btn-primary {
            background-color: #d32f2f;
            border-color: #d32f2f;
        }
        .btn-primary:hover {
            background-color: #c62828;
            border-color: #c62828;
        }
        .summary-card {
            text-align: center;
            padding: 1.5rem;
            border-radius: 10px;
            color: white;
            margin-bottom: 1rem;
        }
        .summary-card-income {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }
        .summary-card-expense {
            background: linear-gradient(135deg,rgb(70, 2, 126) 0%,rgb(36, 2, 49) 100%);
        }
        .summary-card-profit {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }
        .summary-card-loss {
            background: linear-gradient(135deg, #dc3545 0%, #fd7e14 100%);
        }
        .positive {
            color: #28a745;
            font-weight: bold;
        }
        .negative {
            color: #dc3545;
            font-weight: bold;
        }
        .amount-text {
            font-weight: bold;
            font-size: 1.1em;
        }
        .chart-container {
            height: 300px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    </style>
</head>
<body>
    <?php include '../includes/header.php'; ?>

    <div class="container mt-4">
        <!-- Institution Header -->
        <div class="institution-header">
            <div class="institution-name-main"><?php echo htmlspecialchars($institution_name); ?></div>
            <div class="institution-address-main"><?php echo htmlspecialchars($institution_address); ?></div>
        </div>
        
        <!-- Navigation Buttons -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <a href="javascript:history.back()" class="btn btn-outline-secondary me-2">
                            <i class="fas fa-arrow-left"></i> Back
                        </a>
                        <a href="../index.php" class="btn btn-outline-success">
                            <i class="fas fa-home"></i> Home Page
                        </a>
                    </div>
                    <h2 class="mb-0">আয়-ব্যয় রিপোর্ট</h2>
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5><i class="fas fa-balance-scale"></i> আয়-ব্যয় রিপোর্ট</h5>
                        <button class="btn btn-primary" onclick="printCombinedReport()">
                            <i class="fas fa-print"></i> আয়-ব্যয় বিস্তারিত প্রিন্ট করুন
                        </button>
                    </div>
                    <div class="card-body">
                        <!-- Filters -->
                        <form method="GET" class="mb-4">
                            <div class="row">
                                <div class="col-md-4">
                                    <label class="form-label">শুরুর তারিখ</label>
                                    <input type="date" class="form-control" name="start_date" value="<?php echo $start_date; ?>">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">শেষের তারিখ</label>
                                    <input type="date" class="form-control" name="end_date" value="<?php echo $end_date; ?>">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">&nbsp;</label>
                                    <div>
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="fas fa-filter"></i> ফিল্টার
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>

                        <!-- Summary Cards -->
                        <div class="row mb-4">
                            <div class="col-md-3">
                                <div class="summary-card summary-card-income">
                                    <h5>প্রাপ্ত আয়</h5>
                                    <h2 class="amount-text">৳<?php echo number_format($receivedIncome, 2); ?></h2>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="summary-card summary-card-expense">
                                    <h5>মোট ব্যয়</h5>
                                    <h2 class="amount-text">৳<?php echo number_format($totalExpenses, 2); ?></h2>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="summary-card <?php echo $netResult >= 0 ? 'summary-card-profit' : 'summary-card-loss'; ?>">
                                    <h5>মুনাফা/ক্ষতি</h5>
                                    <h2 class="amount-text">
                                        <?php if ($netResult >= 0): ?>
                                            +৳<?php echo number_format($netResult, 2); ?>
                                        <?php else: ?>
                                            -৳<?php echo number_format(abs($netResult), 2); ?>
                                        <?php endif; ?>
                                    </h2>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="summary-card summary-card-expense">
                                    <h5>মোট ব্যয় বিল</h5>
                                    <h2><?php echo $expenseData['expense_count'] ?? 0; ?></h2>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Balance Cards -->
                        <div class="row mb-4">
                            <div class="col-md-3">
                                <div class="summary-card summary-card-expense">
                                    <h5>পূর্ববর্তী ব্যালেন্স</h5>
                                    <h2 class="amount-text">৳<?php echo number_format($previousBalance, 2); ?></h2>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="summary-card summary-card-profit">
                                    <h5>বর্তমান ব্যালেন্স</h5>
                                    <h2 class="amount-text">৳<?php echo number_format($currentBalance, 2); ?></h2>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="summary-card summary-card-income">
                                    <h5>তারিখ সীমা</h5>
                                    <h2 class="amount-text"><?php echo date('d/m/Y', strtotime($start_date)); ?> - <?php echo date('d/m/Y', strtotime($end_date)); ?></h2>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="summary-card summary-card-profit">
                                    <h5>একাউন্ট সংখ্যা</h5>
                                    <h2><?php 
                                    $accountStmt = $pdo->query("SELECT COUNT(*) as count FROM previous_balances");
                                    $accountData = $accountStmt->fetch();
                                    echo $accountData['count'] ?? 0; ?></h2>
                                </div>
                            </div>
                        </div>

                        <!-- Income vs Expense Chart (Text-based) -->
                        <div class="card mb-4 d-print-none">
                            <div class="card-header">
                                <h5><i class="fas fa-chart-bar"></i> আয় বনাম ব্যয় তুলনা</h5>
                            </div>
                            <div class="card-body">
                                <div class="chart-container">
                                    <div class="text-center w-100">
                                        <div class="row">
                                            <div class="col-md-4">
                                                <h6>প্রাপ্ত আয়</h6>
                                                <div class="progress mb-2" style="height: 30px;">
                                                    <div class="progress-bar bg-success" role="progressbar" 
                                                         style="width: <?php echo $receivedIncome > 0 ? min(100, ($receivedIncome / max($receivedIncome, $totalExpenses)) * 100) : 0; ?>%" 
                                                         aria-valuenow="<?php echo $receivedIncome; ?>" 
                                                         aria-valuemin="0" 
                                                         aria-valuemax="<?php echo max($receivedIncome, $totalExpenses); ?>">
                                                        ৳<?php echo number_format($receivedIncome, 2); ?>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <h6>মোট ব্যয়</h6>
                                                <div class="progress mb-2" style="height: 30px;">
                                                    <div class="progress-bar bg-danger" role="progressbar" 
                                                         style="width: <?php echo $totalExpenses > 0 ? min(100, ($totalExpenses / max($receivedIncome, $totalExpenses)) * 100) : 0; ?>%" 
                                                         aria-valuenow="<?php echo $totalExpenses; ?>" 
                                                         aria-valuemin="0" 
                                                         aria-valuemax="<?php echo max($receivedIncome, $totalExpenses); ?>">
                                                        ৳<?php echo number_format($totalExpenses, 2); ?>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <h6>মুনাফা/ক্ষতি</h6>
                                                <div class="progress mb-2" style="height: 30px;">
                                                    <div class="progress-bar <?php echo $netResult >= 0 ? 'bg-success' : 'bg-danger'; ?>" role="progressbar" 
                                                         style="width: <?php echo max($receivedIncome, $totalExpenses) > 0 ? (abs($netResult) / max($receivedIncome, $totalExpenses)) * 100 : 0; ?>%" 
                                                         aria-valuenow="<?php echo abs($netResult); ?>" 
                                                         aria-valuemin="0" 
                                                         aria-valuemax="<?php echo max($receivedIncome, $totalExpenses); ?>">
                                                        <?php if ($netResult >= 0): ?>
                                                            +৳<?php echo number_format($netResult, 2); ?>
                                                        <?php else: ?>
                                                            -৳<?php echo number_format(abs($netResult), 2); ?>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Current Balance Summary -->
                        <div class="card mb-4 d-print-none">
                            <div class="card-header">
                                <h5><i class="fas fa-wallet"></i> বর্তমান ব্যালেন্স বিস্তারিত</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <div class="card h-100">
                                            <div class="card-body text-center">
                                                <h6 class="card-title text-muted">পূর্ববর্তী ব্যালেন্স</h6>
                                                <h3 class="text-primary">৳<?php echo number_format($previousBalance, 2); ?></h3>
                                                <small class="text-muted">রিপোর্টের আগের সময় পর্যন্ত</small>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <div class="card h-100">
                                            <div class="card-body text-center">
                                                <h6 class="card-title text-muted">চলতি মুনাফা/ক্ষতি</h6>
                                                <h3 class="<?php echo $netResult >= 0 ? 'text-success' : 'text-danger'; ?>">
                                                    <?php if ($netResult >= 0): ?>
                                                        +৳<?php echo number_format($netResult, 2); ?>
                                                    <?php else: ?>
                                                        -৳<?php echo number_format(abs($netResult), 2); ?>
                                                    <?php endif; ?>
                                                </h3>
                                                <small class="text-muted">নির্বাচিত তারিখ সীমার মধ্যে</small>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <div class="card h-100">
                                            <div class="card-body text-center">
                                                <h6 class="card-title text-muted">বর্তমান ব্যালেন্স</h6>
                                                <h3 class="text-success">৳<?php echo number_format($currentBalance, 2); ?></h3>
                                                <small class="text-muted">হালনাগাদ ব্যালেন্স</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="alert alert-info mt-3">
                                    <h6><i class="fas fa-info-circle"></i> ব্যালেন্স হিসাব পদ্ধতি:</h6>
                                    <ul class="mb-0">
                                        <li>বর্তমান ব্যালেন্স = পূর্ববর্তী ব্যালেন্স + (প্রাপ্ত আয় - মোট ব্যয়)</li>
                                        <li>পূর্ববর্তী ব্যালেন্স: <?php echo date('d/m/Y', strtotime($end_date)); ?> তারিখের আগ পর্যন্ত সব অ্যাকাউন্টের ব্যালেন্স</li>
                                        <li>চলতি মুনাফা/ক্ষতি: <?php echo date('d/m/Y', strtotime($start_date)); ?> থেকে <?php echo date('d/m/Y', strtotime($end_date)); ?> পর্যন্ত সময়কালের হিসাব</li>
                                    </ul>
                                </div>
                            </div>
                        </div>

                        <!-- Monthly Breakdown -->
                        <div class="card mb-4 d-print-none d-none d-md-block">
                            <div class="card-header">
                                <h5><i class="fas fa-calendar-alt"></i> মাসিক বিস্তারিত</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>মাস</th>
                                                <th>প্রাপ্ত আয় (৳)</th>
                                                <th>ব্যয় (৳)</th>
                                                <th>মুনাফা/ক্ষতি (৳)</th>
                                                <th>চলতি ব্যালেন্স (৳)</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $runningBalance = $previousBalance;
                                            foreach ($monthlyData as $row): 
                                                $monthNet = $row['received_income'] - $row['total_expense'];
                                                $runningBalance += $monthNet;
                                            ?>
                                            <tr>
                                                <td><?php echo $row['month']; ?></td>
                                                <td class="text-success">৳<?php echo number_format($row['received_income'], 2); ?></td>
                                                <td class="text-danger">৳<?php echo number_format($row['total_expense'], 2); ?></td>
                                                <td class="<?php echo $monthNet >= 0 ? 'text-success' : 'text-danger'; ?>">
                                                    <?php if ($monthNet >= 0): ?>
                                                        +৳<?php echo number_format($monthNet, 2); ?>
                                                    <?php else: ?>
                                                        -৳<?php echo number_format(abs($monthNet), 2); ?>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="<?php echo $runningBalance >= 0 ? 'text-success' : 'text-danger'; ?>">
                                                    <strong>৳<?php echo number_format($runningBalance, 2); ?></strong>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                            
                                            <?php if (empty($monthlyData)): ?>
                                            <tr>
                                                <td colspan="5" class="text-center">কোন তথ্য পাওয়া যায়নি</td>
                                            </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <!-- Combined Income and Expense Categories -->
                        <div class="card mb-4" id="combined-category-print">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5><i class="fas fa-exchange-alt"></i> আয়-ব্যয় বিভাগ অনুযায়ী বিস্তারিত</h5>
                                <button class="btn btn-sm btn-outline-primary" onclick="printCombinedReport()">
                                    <i class="fas fa-print"></i> প্রিন্ট
                                </button>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped" id="category-table-content">
                                        <thead>
                                            <tr>
                                                <th>বিভাগ</th>
                                                <th>ধরণ</th>
                                                <th>মোট পরিমান (৳)</th>
                                                <th>শতাংশ</th>
                                                <th>ব্যালেন্স প্রভাব (৳)</th>
                                                <th>বর্তমান ব্যালেন্স (৳)</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <!-- Income Categories -->
                                            <?php 
                                            // Get income by category (fee types)
                                            $incomeCategorySql = "
                                                SELECT 'ফি পেমেন্ট' as category_name, SUM(amount) as total_amount, COUNT(*) as count, 'আয়' as type
                                                FROM fee_payments 
                                                WHERE payment_date BETWEEN ? AND ?
                                            ";
                                            $incomeCategoryStmt = $pdo->prepare($incomeCategorySql);
                                            $incomeCategoryStmt->execute([$start_date, $end_date]);
                                            $incomeCategoryData = $incomeCategoryStmt->fetchAll(PDO::FETCH_ASSOC);
                                            
                                            $totalBalanceChange = $currentBalance - $previousBalance;
                                            $runningBalance = $previousBalance; // Start with previous balance
                                            
                                            // Display income categories
                                            foreach ($incomeCategoryData as $row): 
                                                $percentage = $receivedIncome > 0 ? ($row['total_amount'] / $receivedIncome) * 100 : 0;
                                                $impact = $row['total_amount'];
                                                $runningBalance += $impact; // Add income to running balance
                                            ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($row['category_name']); ?></td>
                                                <td><span class="badge bg-success">আয়</span></td>
                                                <td>৳<?php echo number_format($row['total_amount'], 2); ?></td>
                                                <td>
                                                    <div class="progress" style="height: 20px;">
                                                        <div class="progress-bar bg-success" role="progressbar" 
                                                             style="width: <?php echo $percentage; ?>%" 
                                                             aria-valuenow="<?php echo $percentage; ?>" 
                                                             aria-valuemin="0" 
                                                             aria-valuemax="100">
                                                            <?php echo number_format($percentage, 1); ?>%
                                                        </div>
                                                    </div>
                                                </td>
                                                <td class="text-success">
                                                    <strong>+৳<?php echo number_format($row['total_amount'], 2); ?></strong>
                                                </td>
                                                <td class="text-success">
                                                    <strong>৳<?php echo number_format($runningBalance, 2); ?></strong>
                                                    <small class="text-muted d-block">বর্তমান ব্যালেন্স</small>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                            
                                            <!-- Expense Categories -->
                                            <?php 
                                            // Display expense categories
                                            foreach ($categoryData as $row): 
                                                $percentage = $totalExpenses > 0 ? ($row['total_expense'] / $totalExpenses) * 100 : 0;
                                                $impact = -($row['total_expense']);
                                                $runningBalance += $impact; // Subtract expense from running balance
                                            ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($row['category_name']); ?></td>
                                                <td><span class="badge bg-danger">ব্যয়</span></td>
                                                <td>৳<?php echo number_format($row['total_expense'], 2); ?></td>
                                                <td>
                                                    <div class="progress" style="height: 20px;">
                                                        <div class="progress-bar bg-warning" role="progressbar" 
                                                             style="width: <?php echo $percentage; ?>%" 
                                                             aria-valuenow="<?php echo $percentage; ?>" 
                                                             aria-valuemin="0" 
                                                             aria-valuemax="100">
                                                            <?php echo number_format($percentage, 1); ?>%
                                                        </div>
                                                    </div>
                                                </td>
                                                <td class="text-danger">
                                                    <strong>-৳<?php echo number_format($row['total_expense'], 2); ?></strong>
                                                </td>
                                                <td class="text-<?php echo $runningBalance >= 0 ? 'success' : 'danger'; ?>">
                                                    <strong>৳<?php echo number_format($runningBalance, 2); ?></strong>
                                                    <small class="text-muted d-block">বর্তমান ব্যালেন্স</small>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                            
                                            <?php if (empty($incomeCategoryData) && empty($categoryData)): ?>
                                            <tr>
                                                <td colspan="6" class="text-center">কোন তথ্য পাওয়া যায়নি</td>
                                            </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>ব্যয় বিভাগ</th>
                                                <th>মোট ব্যয় (৳)</th>
                                                <th>শতাংশ</th>
                                                <th>ব্যালেন্স প্রভাব (৳)</th>
                                                <th>বর্তমান ব্যালেন্সে অবদান</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $categoryBalanceImpact = $currentBalance - $previousBalance;
                                            foreach ($categoryData as $row): 
                                                $percentage = $totalExpenses > 0 ? ($row['total_expense'] / $totalExpenses) * 100 : 0;
                                                // Calculate impact on balance (negative impact as expenses reduce balance)
                                                $impact = -($row['total_expense']);
                                                $impactPercentage = $categoryBalanceImpact != 0 ? (abs($impact) / abs($categoryBalanceImpact)) * 100 : 0;
                                            ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($row['category_name']); ?></td>
                                                <td>৳<?php echo number_format($row['total_expense'], 2); ?></td>
                                                <td>
                                                    <div class="progress" style="height: 20px;">
                                                        <div class="progress-bar bg-warning" role="progressbar" 
                                                             style="width: <?php echo $percentage; ?>%" 
                                                             aria-valuenow="<?php echo $percentage; ?>" 
                                                             aria-valuemin="0" 
                                                             aria-valuemax="100">
                                                            <?php echo number_format($percentage, 1); ?>%
                                                        </div>
                                                    </div>
                                                </td>
                                                <td class="text-danger">
                                                    <strong>-৳<?php echo number_format($row['total_expense'], 2); ?></strong>
                                                </td>
                                                <td>
                                                    <div class="progress" style="height: 20px;">
                                                        <div class="progress-bar bg-danger" role="progressbar" 
                                                             style="width: <?php echo $impactPercentage; ?>%" 
                                                             aria-valuenow="<?php echo $impactPercentage; ?>" 
                                                             aria-valuemin="0" 
                                                             aria-valuemax="100">
                                                            <?php echo number_format($impactPercentage, 1); ?>%
                                                        </div>
                                                    </div>
                                                    <small class="text-muted">ব্যালেন্স হ্রাস</small>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                            
                                            <?php if (empty($categoryData)): ?>
                                            <tr>
                                                <td colspan="5" class="text-center">কোন ব্যয় পাওয়া যায়নি</td>
                                            </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Function to print only the combined category table
        function printCombinedReport() {
            try {
                // Get the table content directly
                var tableElement = document.getElementById('category-table-content');
                if (!tableElement) {
                    alert('প্রিন্ট করার জন্য প্রয়োজনীয় তথ্য পাওয়া যাচ্ছে না।');
                    return;
                }
                
                // Get the complete table HTML
                var tableHTML = tableElement.outerHTML;
                
                // Create a new window for printing
                var printWindow = window.open('', '_blank', 'width=900,height=700');
                
                if (!printWindow) {
                    alert('পপ-আপ ব্লকার সক্রিয় আছে। দয়া করে পপ-আপ অনুমতি দিন এবং আবার চেষ্টা করুন।');
                    return;
                }
                
                // Create the complete HTML document for printing
                var printDocument = `
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>আয়-ব্যয় বিভাগ অনুযায়ী বিস্তারিত</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            margin: 20px;
            direction: ltr;
            background: white;
        }
        
        @media print {
            body {
                margin: 10px;
                font-size: 12px;
            }
            
            .report-header {
                text-align: center;
                margin-bottom: 25px;
                padding: 15px;
                border-bottom: 2px solid #333;
            }
            
            .institution-info {
                margin-bottom: 15px;
            }
            
            .institution-name {
                font-size: 24px;
                font-weight: bold;
                color: #d32f2f;
                margin-bottom: 5px;
            }
            
            .institution-address {
                font-size: 14px;
                color: #666;
            }
            
            .report-title {
                font-size: 20px;
                font-weight: bold;
                margin-bottom: 12px;
                color: #333;
            }
            
            .report-period {
                font-size: 14px;
                margin-bottom: 15px;
                color: #666;
            }
            
            .report-balances {
                display: flex;
                justify-content: center;
                gap: 40px;
                margin-bottom: 20px;
            }
            
            .balance-item {
                text-align: center;
                padding: 10px;
            }
            
            .balance-label {
                font-size: 12px;
                color: #666;
                margin-bottom: 5px;
            }
            
            .balance-amount {
                font-size: 16px;
                font-weight: bold;
            }
            
            .table {
                font-size: 11px;
                width: 100%;
                margin-bottom: 20px;
                border-collapse: collapse;
            }
            
            .table th {
                background-color: #f0f0f0;
                border: 1px solid #ddd;
                padding: 8px;
                text-align: left;
            }
            
            .table td {
                border: 1px solid #ddd;
                padding: 6px;
            }
            
            .badge {
                display: inline-block;
                padding: 0.35em 0.65em;
                font-size: 75%;
                font-weight: 700;
                text-align: center;
                white-space: nowrap;
                vertical-align: baseline;
                border-radius: 0.25rem;
            }
            
            .bg-success {
                background-color: #28a745 !important;
                color: white;
            }
            
            .bg-danger {
                background-color: #dc3545 !important;
                color: white;
            }
            
            .progress {
                height: 15px;
                margin-bottom: 0;
                background-color: #e9ecef;
                border-radius: 0.25rem;
            }
            
            .progress-bar {
                display: flex;
                flex-direction: column;
                justify-content: center;
                overflow: hidden;
                color: #fff;
                text-align: center;
                white-space: nowrap;
                background-color: #007bff;
                transition: width 0.6s ease;
            }
        }
    </style>
</head>
<body>
    <div class="report-header">
        <div class="institution-info">
            <div class="institution-name"><?php echo htmlspecialchars($institution_name); ?></div>
            <div class="institution-address"><?php echo htmlspecialchars($institution_address); ?></div>
        </div>
        <div class="report-title">আয়-ব্যয় বিভাগ অনুযায়ী বিস্তারিত</div>
        <div class="report-period">তারিখ সীমা: <?php echo date('d/m/Y', strtotime($start_date)); ?> - <?php echo date('d/m/Y', strtotime($end_date)); ?></div>
        <div class="report-balances">
            <div class="balance-item">
                <div class="balance-label">পূর্ববর্তী ব্যালেন্স</div>
                <div class="balance-amount">৳<?php echo number_format($previousBalance, 2); ?></div>
            </div>
            <div class="balance-item">
                <div class="balance-label">বর্তমান ব্যালেন্স</div>
                <div class="balance-amount text-success">৳<?php echo number_format($currentBalance, 2); ?></div>
            </div>
        </div>
    </div>
    
    <div class="table-responsive">
        ${tableHTML}
    </div>
</body>
</html>`;
                
                // Write content to print window
                printWindow.document.write(printDocument);
                printWindow.document.close();
                
                // Print after content is loaded
                printWindow.onload = function() {
                    printWindow.print();
                    setTimeout(function() {
                        printWindow.close();
                    }, 2000);
                };
                
                // Fallback print trigger
                setTimeout(function() {
                    if (printWindow && !printWindow.closed) {
                        printWindow.print();
                        setTimeout(function() {
                            printWindow.close();
                        }, 2000);
                    }
                }, 2000);
                
            } catch (error) {
                console.error('Print error:', error);
                alert('প্রিন্ট করার সময় ত্রুটি হয়েছে: ' + error.message);
            }
        }
        

    </script>
</body>
</html>