<?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 filter parameters
$period = $_GET['period'] ?? 'month';
$start_date = $_GET['start_date'] ?? date('Y-m-01');
$end_date = $_GET['end_date'] ?? date('Y-m-t');
$search_term = $_GET['search'] ?? '';

// Pagination settings
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$available_page_sizes = [10, 20, 50, 100, 200, 500, 1000];
$records_per_page = isset($_GET['per_page']) && in_array($_GET['per_page'], $available_page_sizes) ? intval($_GET['per_page']) : 20;
// Handle 'All' option
$show_all = (isset($_GET['per_page']) && $_GET['per_page'] === 'all') ? true : false;
if ($show_all) {
    $records_per_page = 999999; // Large number to show all records
}
$offset = ($page - 1) * $records_per_page;

// Calculate date ranges for different periods
switch($period) {
    case 'day':
        $group_by_expense = "DATE(e.expense_date)";
        $group_by_income = "DATE(fp.payment_date)";
        $date_format = "%Y-%m-%d";
        $display_format = "দিন";
        break;
    case 'week':
        $group_by_expense = "YEARWEEK(e.expense_date, 1)";
        $group_by_income = "YEARWEEK(fp.payment_date, 1)";
        $date_format = "%Y-%u";
        $display_format = "সপ্তাহ";
        break;
    case 'month':
        $group_by_expense = "DATE_FORMAT(e.expense_date, '%Y-%m')";
        $group_by_income = "DATE_FORMAT(fp.payment_date, '%Y-%m')";
        $date_format = "%Y-%m";
        $display_format = "মাস";
        break;
    case 'year':
        $group_by_expense = "YEAR(e.expense_date)";
        $group_by_income = "YEAR(fp.payment_date)";
        $date_format = "%Y";
        $display_format = "বছর";
        break;
    default:
        $group_by_expense = "DATE_FORMAT(e.expense_date, '%Y-%m')";
        $group_by_income = "DATE_FORMAT(fp.payment_date, '%Y-%m')";
        $date_format = "%Y-%m";
        $display_format = "মাস";
}

// Get expense summary by selected period
$expenseBaseSql = "
    SELECT 
        DATE_FORMAT(e.expense_date, '$date_format') as period,
        'expense' as type,
        COUNT(*) as transaction_count,
        SUM(e.amount) as total_amount,
        AVG(e.amount) as average_amount,
        MIN(e.amount) as min_amount,
        MAX(e.amount) as max_amount
    FROM expenses e
    WHERE e.expense_date BETWEEN ? AND ?";

$expenseParams = [$start_date, $end_date];

// Add search filter if specified
if (!empty($search_term)) {
    $expenseBaseSql .= " AND (e.title LIKE ? OR e.description LIKE ? OR e.receipt_no LIKE ?)";
    $search_param = "%" . trim($search_term) . "%";
    $expenseParams[] = $search_param;
    $expenseParams[] = $search_param;
    $expenseParams[] = $search_param;
}

$expenseBaseSql .= " GROUP BY $group_by_expense";

// Count total records for pagination
$expenseCountSql = "SELECT COUNT(DISTINCT $group_by_expense) as total FROM expenses e WHERE e.expense_date BETWEEN ? AND ?";
$expenseCountParams = [$start_date, $end_date];
if (!empty($search_term)) {
    $expenseCountSql .= " AND (e.title LIKE ? OR e.description LIKE ? OR e.receipt_no LIKE ?)";
    $expenseCountParams[] = $search_param;
    $expenseCountParams[] = $search_param;
    $expenseCountParams[] = $search_param;
}
$expenseCountStmt = $pdo->prepare($expenseCountSql);
$expenseCountStmt->execute($expenseCountParams);
$expenseTotalRecords = $expenseCountStmt->fetch()['total'];
$expenseTotalPages = $show_all ? 1 : ceil($expenseTotalRecords / $records_per_page);

// Add pagination to the main query
$expenseSql = $expenseBaseSql . " ORDER BY period DESC LIMIT ? OFFSET ?";
$expenseParams[] = $records_per_page;
$expenseParams[] = $offset;

$expenseStmt = $pdo->prepare($expenseSql);
$expenseStmt->execute($expenseParams);
$expenseData = $expenseStmt->fetchAll(PDO::FETCH_ASSOC);

// Get income summary by selected period
$incomeBaseSql = "
    SELECT 
        DATE_FORMAT(fp.payment_date, '$date_format') as period,
        'income' as type,
        COUNT(*) as transaction_count,
        SUM(fp.amount) as total_amount,
        AVG(fp.amount) as average_amount,
        MIN(fp.amount) as min_amount,
        MAX(fp.amount) as max_amount
    FROM fee_payments fp
    WHERE fp.payment_date BETWEEN ? AND ?";

$incomeParams = [$start_date, $end_date];

// Add search filter if specified
if (!empty($search_term)) {
    $incomeBaseSql .= " AND (fp.transaction_id LIKE ? OR fp.payment_method LIKE ?)";
    $search_param = "%" . trim($search_term) . "%";
    $incomeParams[] = $search_param;
    $incomeParams[] = $search_param;
}

$incomeBaseSql .= " GROUP BY $group_by_income";

// Count total records for pagination
$incomeCountSql = "SELECT COUNT(DISTINCT $group_by_income) as total FROM fee_payments fp WHERE fp.payment_date BETWEEN ? AND ?";
$incomeCountParams = [$start_date, $end_date];
if (!empty($search_term)) {
    $incomeCountSql .= " AND (fp.transaction_id LIKE ? OR fp.payment_method LIKE ?)";
    $incomeCountParams[] = $search_param;
    $incomeCountParams[] = $search_param;
}
$incomeCountStmt = $pdo->prepare($incomeCountSql);
$incomeCountStmt->execute($incomeCountParams);
$incomeTotalRecords = $incomeCountStmt->fetch()['total'];
$incomeTotalPages = $show_all ? 1 : ceil($incomeTotalRecords / $records_per_page);

// Add pagination to the main query
$incomeSql = $incomeBaseSql . " ORDER BY period DESC LIMIT ? OFFSET ?";
$incomeParams[] = $records_per_page;
$incomeParams[] = $offset;

$incomeStmt = $pdo->prepare($incomeSql);
$incomeStmt->execute($incomeParams);
$incomeData = $incomeStmt->fetchAll(PDO::FETCH_ASSOC);

// Combine and sort data
$summaryData = array_merge($expenseData, $incomeData);
usort($summaryData, function($a, $b) {
    return strcmp($b['period'], $a['period']);
});

// Get overall expense statistics
$overallExpenseSql = "
    SELECT 
        COUNT(*) as total_transactions,
        SUM(amount) as grand_total,
        AVG(amount) as overall_average,
        MIN(amount) as overall_min,
        MAX(amount) as overall_max
    FROM expenses 
    WHERE expense_date BETWEEN ? AND ?
";

$overallExpenseStmt = $pdo->prepare($overallExpenseSql);
$overallExpenseStmt->execute([$start_date, $end_date]);
$overallExpenseStats = $overallExpenseStmt->fetch();

// Get overall income statistics
$overallIncomeSql = "
    SELECT 
        COUNT(*) as total_transactions,
        SUM(amount) as grand_total,
        AVG(amount) as overall_average,
        MIN(amount) as overall_min,
        MAX(amount) as overall_max
    FROM fee_payments 
    WHERE payment_date BETWEEN ? AND ?
";

$overallIncomeStmt = $pdo->prepare($overallIncomeSql);
$overallIncomeStmt->execute([$start_date, $end_date]);
$overallIncomeStats = $overallIncomeStmt->fetch();

// Calculate net result
$netResult = $overallIncomeStats['grand_total'] - $overallExpenseStats['grand_total'];

// Combine overall statistics
$overallStats = [
    'total_expense_transactions' => $overallExpenseStats['total_transactions'],
    'total_income_transactions' => $overallIncomeStats['total_transactions'],
    'total_expense_amount' => $overallExpenseStats['grand_total'],
    'total_income_amount' => $overallIncomeStats['grand_total'],
    'net_result' => $netResult,
    'overall_expense_average' => $overallExpenseStats['overall_average'],
    'overall_income_average' => $overallIncomeStats['overall_average'],
    'overall_expense_min' => $overallExpenseStats['overall_min'],
    'overall_expense_max' => $overallExpenseStats['overall_max'],
    'overall_income_min' => $overallIncomeStats['overall_min'],
    'overall_income_max' => $overallIncomeStats['overall_max']
];

// Get expense category-wise breakdown
$expenseCategorySql = "
    SELECT 
        ec.name as category_name,
        'expense' as type,
        COUNT(*) as transaction_count,
        SUM(e.amount) as total_amount,
        AVG(e.amount) as average_amount
    FROM expenses e
    JOIN expense_categories ec ON e.category_id = ec.id
    WHERE e.expense_date BETWEEN ? AND ?
    GROUP BY ec.name
";

$expenseCategoryStmt = $pdo->prepare($expenseCategorySql);
$expenseCategoryStmt->execute([$start_date, $end_date]);
$expenseCategoryData = $expenseCategoryStmt->fetchAll(PDO::FETCH_ASSOC);

// Get income source breakdown (by fee type)
$incomeCategorySql = "
    SELECT 
        f.fee_type as category_name,
        'income' as type,
        COUNT(*) as transaction_count,
        SUM(fp.amount) as total_amount,
        AVG(fp.amount) as average_amount
    FROM fee_payments fp
    JOIN fees f ON fp.fee_id = f.id
    WHERE fp.payment_date BETWEEN ? AND ?
    GROUP BY f.fee_type
";

$incomeCategoryStmt = $pdo->prepare($incomeCategorySql);
$incomeCategoryStmt->execute([$start_date, $end_date]);
$incomeCategoryData = $incomeCategoryStmt->fetchAll(PDO::FETCH_ASSOC);

// Combine category data
$categoryData = array_merge($expenseCategoryData, $incomeCategoryData);
usort($categoryData, function($a, $b) {
    return $b['total_amount'] <=> $a['total_amount'];
});

// Get expense payment method breakdown
$expensePaymentSql = "
    SELECT 
        payment_method,
        'expense' as type,
        COUNT(*) as transaction_count,
        SUM(amount) as total_amount
    FROM expenses 
    WHERE expense_date BETWEEN ? AND ?
    GROUP BY payment_method
";

$expensePaymentStmt = $pdo->prepare($expensePaymentSql);
$expensePaymentStmt->execute([$start_date, $end_date]);
$expensePaymentData = $expensePaymentStmt->fetchAll(PDO::FETCH_ASSOC);

// Get income payment method breakdown
$incomePaymentSql = "
    SELECT 
        payment_method,
        'income' as type,
        COUNT(*) as transaction_count,
        SUM(amount) as total_amount
    FROM fee_payments 
    WHERE payment_date BETWEEN ? AND ?
    GROUP BY payment_method
";

$incomePaymentStmt = $pdo->prepare($incomePaymentSql);
$incomePaymentStmt->execute([$start_date, $end_date]);
$incomePaymentData = $incomePaymentStmt->fetchAll(PDO::FETCH_ASSOC);

// Combine payment data
$paymentData = array_merge($expensePaymentData, $incomePaymentData);
usort($paymentData, function($a, $b) {
    return $b['total_amount'] <=> $a['total_amount'];
});
?>

<!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://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;
        }
        .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-transaction {
            background: linear-gradient(135deg, #17a2b8 0%, #20c997 100%);
        }
        .summary-card-amount {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }
        .summary-card-average {
            background: linear-gradient(135deg, #007bff 0%, #6f42c1 100%);
        }
        .summary-card-expense {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
        }
        .amount-text {
            font-weight: bold;
            font-size: 1.1em;
        }
        .period-selector {
            background: linear-gradient(135deg, #6f42c1 0%, #e83e8c 100%);
            color: white;
            padding: 1rem;
            border-radius: 10px;
            margin-bottom: 1.5rem;
        }
        .chart-container {
            height: 300px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        /* Pagination styles */
        .pagination {
            margin-bottom: 0;
        }
        
        .pagination .page-link {
            color: #d32f2f;
            border-color: #dee2e6;
        }
        
        .pagination .page-link:hover {
            color: #fff;
            background-color: #d32f2f;
            border-color: #d32f2f;
        }
        
        .pagination .page-item.active .page-link {
            background-color: #d32f2f;
            border-color: #d32f2f;
        }
        
        .pagination-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        @media (max-width: 767px) {
            .pagination-container {
                flex-direction: column;
                gap: 10px;
            }
            .pagination {
                margin-top: 10px;
            }
        }
    </style>
</head>
<body>
    <?php include '../includes/header.php'; ?>

    <div class="container mt-4">
        <!-- 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">
                <!-- Period Selection -->
                <div class="period-selector">
                    <div class="row align-items-center">
                        <div class="col-md-3">
                            <h5 class="mb-0">সময়কাল নির্বাচন:</h5>
                        </div>
                        <div class="col-md-6">
                            <form method="GET" class="d-flex flex-wrap">
                                <select name="period" class="form-select me-2 mb-2" onchange="this.form.submit()" style="flex: 1; min-width: 120px;">
                                    <option value="day" <?php echo $period == 'day' ? 'selected' : ''; ?>>দিন</option>
                                    <option value="week" <?php echo $period == 'week' ? 'selected' : ''; ?>>সপ্তাহ</option>
                                    <option value="month" <?php echo $period == 'month' ? 'selected' : ''; ?>>মাস</option>
                                    <option value="year" <?php echo $period == 'year' ? 'selected' : ''; ?>>বছর</option>
                                </select>
                                <input type="date" name="start_date" value="<?php echo $start_date; ?>" class="form-control me-2 mb-2" style="max-width: 150px;">
                                <input type="date" name="end_date" value="<?php echo $end_date; ?>" class="form-control me-2 mb-2" style="max-width: 150px;">
                                <input type="text" name="search" placeholder="অনুসন্ধান..." value="<?php echo htmlspecialchars($search_term); ?>" class="form-control me-2 mb-2" style="max-width: 150px;">
                                <select name="per_page" class="form-select me-2 mb-2" style="max-width: 100px;">
                                    <option value="20" <?php echo (!$show_all && $records_per_page == 20) ? 'selected' : ''; ?>>20</option>
                                    <option value="10" <?php echo (!$show_all && $records_per_page == 10) ? 'selected' : ''; ?>>10</option>
                                    <option value="50" <?php echo (!$show_all && $records_per_page == 50) ? 'selected' : ''; ?>>50</option>
                                    <option value="100" <?php echo (!$show_all && $records_per_page == 100) ? 'selected' : ''; ?>>100</option>
                                    <option value="200" <?php echo (!$show_all && $records_per_page == 200) ? 'selected' : ''; ?>>200</option>
                                    <option value="500" <?php echo (!$show_all && $records_per_page == 500) ? 'selected' : ''; ?>>500</option>
                                    <option value="1000" <?php echo (!$show_all && $records_per_page == 1000) ? 'selected' : ''; ?>>1000</option>
                                    <option value="all" <?php echo $show_all ? 'selected' : ''; ?>>সব</option>
                                </select>
                                <button type="submit" class="btn btn-light mb-2">
                                    <i class="fas fa-search"></i>
                                </button>
                            </form>
                        </div>
                        <div class="col-md-3 text-end">
                            <span class="badge bg-light text-dark fs-6"><?php echo $display_format; ?> ভিত্তিক রিপোর্ট</span>
                        </div>
                    </div>
                </div>

                <!-- Overall Summary Cards -->
                <div class="row mb-4">
                    <div class="col-md-2">
                        <div class="summary-card summary-card-transaction">
                            <h5>মোট আয় ট্র্যানজেকশন</h5>
                            <h2><?php echo number_format($overallStats['total_income_transactions']); ?></h2>
                            <small>টি</small>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="summary-card summary-card-amount">
                            <h5>মোট আয়</h5>
                            <h2 class="amount-text">৳<?php echo number_format($overallStats['total_income_amount'], 2); ?></h2>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="summary-card summary-card-average">
                            <h5>মোট ব্যয় ট্র্যানজেকশন</h5>
                            <h2><?php echo number_format($overallStats['total_expense_transactions']); ?></h2>
                            <small>টি</small>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="summary-card summary-card-average">
                            <h5>মোট ব্যয়</h5>
                            <h2 class="amount-text">৳<?php echo number_format($overallStats['total_expense_amount'], 2); ?></h2>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="summary-card <?php echo $overallStats['net_result'] >= 0 ? 'summary-card-amount' : 'summary-card-expense'; ?>">
                            <h5>মুনাফা/ক্ষতি</h5>
                            <h2 class="amount-text">
                                <?php if ($overallStats['net_result'] >= 0): ?>
                                    +৳<?php echo number_format($overallStats['net_result'], 2); ?>
                                <?php else: ?>
                                    -৳<?php echo number_format(abs($overallStats['net_result']), 2); ?>
                                <?php endif; ?>
                            </h2>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="summary-card summary-card-transaction">
                            <h5>নেট ট্র্যানজেকশন</h5>
                            <h2><?php echo number_format($overallStats['total_income_transactions'] + $overallStats['total_expense_transactions']); ?></h2>
                            <small>টি</small>
                        </div>
                    </div>
                </div>

                <!-- Period-wise Transaction Analysis -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5><i class="fas fa-chart-line"></i> <?php echo $display_format; ?> ভিত্তিক আয়-ব্যয় বিশ্লেষণ</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th><?php echo $display_format; ?></th>
                                        <th>ধরন</th>
                                        <th>ট্র্যানজেকশন সংখ্যা</th>
                                        <th>মোট পরিমাণ (৳)</th>
                                        <th>গড় পরিমাণ (৳)</th>
                                        <th>সর্বনিম্ন (৳)</th>
                                        <th>সর্বোচ্চ (৳)</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($summaryData as $row): ?>
                                    <tr>
                                        <td><strong><?php echo $row['period']; ?></strong></td>
                                        <td>
                                            <?php if ($row['type'] == 'income'): ?>
                                                <span class="badge bg-success">আয়</span>
                                            <?php else: ?>
                                                <span class="badge bg-danger">ব্যয়</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo number_format($row['transaction_count']); ?> টি</td>
                                        <td class="amount-text">৳<?php echo number_format($row['total_amount'], 2); ?></td>
                                        <td>৳<?php echo number_format($row['average_amount'], 2); ?></td>
                                        <td>৳<?php echo number_format($row['min_amount'], 2); ?></td>
                                        <td>৳<?php echo number_format($row['max_amount'], 2); ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                    
                                    <?php if (empty($summaryData)): ?>
                                    <tr>
                                        <td colspan="7" class="text-center">নির্বাচিত সময়কালে কোন ট্র্যানজেকশন পাওয়া যায়নি</td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <?php if (!empty($summaryData)): ?>
                        <div class="mt-3 d-flex flex-column flex-md-row justify-content-between align-items-center">
                            <div class="mb-2 mb-md-0">
                                <strong>মোট রেকর্ড:</strong> <?php echo ($expenseTotalRecords + $incomeTotalRecords); ?> টি (<?php echo $page; ?>/<?php echo max($expenseTotalPages, $incomeTotalPages); ?> পৃষ্ঠা)
                            </div>
                            <!-- Pagination Controls -->
                            <nav aria-label="Page navigation">
                                <ul class="pagination mb-0">
                                    <!-- Previous Button -->
                                    <li class="page-item <?php echo ($page <= 1) ? 'disabled' : ''; ?>">
                                        <a class="page-link" href="?period=<?php echo $period; ?>&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&search=<?php echo urlencode($search_term); ?>&per_page=<?php echo $_GET['per_page'] ?? '20'; ?>&page=<?php echo $page - 1; ?>">
                                            <i class="fas fa-chevron-left"></i> পূর্ববর্তী
                                        </a>
                                    </li>
                                    
                                    <!-- Page Numbers -->
                                    <?php
                                    $total_pages = max($expenseTotalPages, $incomeTotalPages);
                                    $start_page = max(1, $page - 2);
                                    $end_page = min($total_pages, $page + 2);
                                    
                                    if ($start_page > 1): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?period=<?php echo $period; ?>&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&search=<?php echo urlencode($search_term); ?>&per_page=<?php echo $_GET['per_page'] ?? '20'; ?>&page=1">1</a>
                                        </li>
                                        <?php if ($start_page > 2): ?>
                                            <li class="page-item disabled">
                                                <span class="page-link">...</span>
                                            </li>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                    
                                    <?php for ($i = $start_page; $i <= $end_page; $i++): ?>
                                        <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>">
                                            <a class="page-link" href="?period=<?php echo $period; ?>&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&search=<?php echo urlencode($search_term); ?>&per_page=<?php echo $_GET['per_page'] ?? '20'; ?>&page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                        </li>
                                    <?php endfor; ?>
                                    
                                    <?php if ($end_page < $total_pages): ?>
                                        <?php if ($end_page < $total_pages - 1): ?>
                                            <li class="page-item disabled">
                                                <span class="page-link">...</span>
                                            </li>
                                        <?php endif; ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?period=<?php echo $period; ?>&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&search=<?php echo urlencode($search_term); ?>&per_page=<?php echo $_GET['per_page'] ?? '20'; ?>&page=<?php echo $total_pages; ?>"><?php echo $total_pages; ?></a>
                                        </li>
                                    <?php endif; ?>
                                    
                                    <!-- Next Button -->
                                    <li class="page-item <?php echo ($page >= $total_pages) ? 'disabled' : ''; ?>">
                                        <a class="page-link" href="?period=<?php echo $period; ?>&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&search=<?php echo urlencode($search_term); ?>&per_page=<?php echo $_GET['per_page'] ?? '20'; ?>&page=<?php echo $page + 1; ?>">
                                            পরবর্তী <i class="fas fa-chevron-right"></i>
                                        </a>
                                    </li>
                                </ul>
                            </nav>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Category-wise Breakdown -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5><i class="fas fa-tags"></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>
                                        <th>শতাংশ</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($categoryData as $row): ?>
                                    <?php 
                                        $total_amount = $row['type'] == 'income' ? $overallStats['total_income_amount'] : $overallStats['total_expense_amount'];
                                        $percentage = $total_amount > 0 ? ($row['total_amount'] / $total_amount) * 100 : 0;
                                    ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($row['category_name']); ?></td>
                                        <td>
                                            <?php if ($row['type'] == 'income'): ?>
                                                <span class="badge bg-success">আয়</span>
                                            <?php else: ?>
                                                <span class="badge bg-danger">ব্যয়</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo number_format($row['transaction_count']); ?> টি</td>
                                        <td class="amount-text">৳<?php echo number_format($row['total_amount'], 2); ?></td>
                                        <td>৳<?php echo number_format($row['average_amount'], 2); ?></td>
                                        <td>
                                            <div class="progress" style="height: 20px;">
                                                <div class="progress-bar <?php echo $row['type'] == 'income' ? 'bg-success' : 'bg-info'; ?>" 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>
                                    </tr>
                                    <?php endforeach; ?>
                                    
                                    <?php if (empty($categoryData)): ?>
                                    <tr>
                                        <td colspan="6" class="text-center">কোন বিভাগ পাওয়া যায়নি</td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Payment Method Breakdown -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5><i class="fas fa-credit-card"></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 foreach ($paymentData as $row): ?>
                                    <?php 
                                        $total_amount = $row['type'] == 'income' ? $overallStats['total_income_amount'] : $overallStats['total_expense_amount'];
                                        $percentage = $total_amount > 0 ? ($row['total_amount'] / $total_amount) * 100 : 0;
                                        $method_name = '';
                                        switch($row['payment_method']) {
                                            case 'cash': $method_name = 'নগদ'; break;
                                            case 'bank_transfer': $method_name = 'ব্যাংক ট্রান্সফার'; break;
                                            case 'mobile_banking': $method_name = 'মোবাইল ব্যাংকিং'; break;
                                            case 'check': $method_name = 'চেক'; break;
                                            default: $method_name = $row['payment_method'];
                                        }
                                    ?>
                                    <tr>
                                        <td><?php echo $method_name; ?></td>
                                        <td>
                                            <?php if ($row['type'] == 'income'): ?>
                                                <span class="badge bg-success">আয়</span>
                                            <?php else: ?>
                                                <span class="badge bg-danger">ব্যয়</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo number_format($row['transaction_count']); ?> টি</td>
                                        <td class="amount-text">৳<?php echo number_format($row['total_amount'], 2); ?></td>
                                        <td>
                                            <div class="progress" style="height: 20px;">
                                                <div class="progress-bar <?php echo $row['type'] == 'income' ? 'bg-success' : 'bg-danger'; ?>" 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>
                                    </tr>
                                    <?php endforeach; ?>
                                    
                                    <?php if (empty($paymentData)): ?>
                                    <tr>
                                        <td colspan="5" class="text-center">কোন পরিশোধের পদ্ধতি পাওয়া যায়নি</td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Print Button -->
                <div class="text-center">
                    <button class="btn btn-primary" onclick="window.print()">
                        <i class="fas fa-print"></i> প্রিন্ট করুন
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>