<?php
session_start();
require_once '../config/database.php';
require_once '../includes/site_settings.php';

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

// Get site settings for header
$settings = get_all_settings($pdo);
$institution_name = $settings['site_name'] ?? 'প্রতিষ্ঠানের নাম';
$institution_address = $settings['site_address'] ?? 'ঠিকানা';
$logo_image = $settings['logo_image'] ?? null;

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

// Pagination settings
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$available_page_sizes = [10, 25, 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;

// Build base query with filters
$base_sql = "SELECT e.*, ec.name as category_name, u.username as created_by_name 
        FROM expenses e 
        LEFT JOIN expense_categories ec ON e.category_id = ec.id 
        LEFT JOIN users u ON e.created_by = u.id 
        WHERE e.expense_date BETWEEN ? AND ?";
$base_params = [$start_date, $end_date];

if ($category_id) {
    $base_sql .= " AND e.category_id = ?";
    $base_params[] = $category_id;
}

// Add search filter if specified
if (!empty($search_term)) {
    $base_sql .= " AND (e.title LIKE ? OR e.description LIKE ? OR e.receipt_no LIKE ? OR ec.name LIKE ? OR u.username LIKE ? OR e.payment_method LIKE ?)";
    $search_param = "%" . trim($search_term) . "%";
    $base_params[] = $search_param;
    $base_params[] = $search_param;
    $base_params[] = $search_param;
    $base_params[] = $search_param;
    $base_params[] = $search_param;
    $base_params[] = $search_param;
}

// Count total records for pagination
$count_sql = "SELECT COUNT(*) as total FROM (" . $base_sql . ") as counted_records";
$count_stmt = $pdo->prepare($count_sql);
$count_stmt->execute($base_params);
$total_records = $count_stmt->fetch()['total'];
$total_pages = $show_all ? 1 : ceil($total_records / $records_per_page);

// Add ordering and pagination to the main query
$sql = $base_sql . " ORDER BY e.expense_date DESC, e.id DESC LIMIT ? OFFSET ?";
$params = array_merge($base_params, [$records_per_page, $offset]);

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$expenses = $stmt->fetchAll();

// Calculate totals
$total_expenses = 0;
$category_totals = [];
foreach ($expenses as $expense) {
    $total_expenses += $expense['amount'];
    if (!isset($category_totals[$expense['category_name']])) {
        $category_totals[$expense['category_name']] = 0;
    }
    $category_totals[$expense['category_name']] += $expense['amount'];
}

// Get all expense categories for filter
$categoryStmt = $pdo->query("SELECT * FROM expense_categories WHERE status = 'active' ORDER BY name ASC");
$categories = $categoryStmt->fetchAll();
?>

<!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-income {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }
        .summary-card-expense {
            background: linear-gradient(135deg, #dc3545 0%, #fd7e14 100%);
        }
        .summary-card-balance {
            background: linear-gradient(135deg, #007bff 0%, #6f42c1 100%);
        }
        .amount-text {
            font-weight: bold;
            color: #dc3545;
        }
        .print-btn {
            position: fixed;
            top: 20px;
            left: 20px;
            z-index: 1000;
        }
        
        /* 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;
            }
        }
        
        /* Print-specific styles */
        @media print {
            .no-print {
                display: none !important;
            }
            
            body {
                font-size: 12px;
                background: white;
                margin: 0;
                padding: 20px;
            }
            
            .container {
                max-width: 100% !important;
                padding: 0;
                margin: 0;
            }
            
            .print-header {
                text-align: center;
                margin-bottom: 20px;
                border-bottom: 2px solid #000;
                padding-bottom: 15px;
            }
            
            .print-logo {
                max-height: 80px;
                margin-bottom: 10px;
            }
            
            .print-institution-name {
                font-size: 20px;
                font-weight: bold;
                margin-bottom: 5px;
            }
            
            .print-institution-address {
                font-size: 14px;
                margin-bottom: 10px;
            }
            
            .print-title {
                font-size: 18px;
                font-weight: bold;
                margin: 15px 0;
                text-align: center;
            }
            
            .table {
                font-size: 11px;
            }
            
            .table th, .table td {
                padding: 4px;
            }
            
            .card {
                border: 1px solid #000;
                box-shadow: none;
                margin-bottom: 15px;
            }
            
            .card-header {
                background: #f0f0f0;
                border-bottom: 1px solid #000;
                padding: 8px;
            }
            
            .print-only {
                display: block !important;
            }
            
            .btn, .form-control, .form-select, .pagination {
                display: none !important;
            }
            
            .row > div {
                width: 100% !important;
            }
        }
        
        .print-only {
            display: none;
        }
    </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>
        
        <!-- Print Header (Visible only when printing) -->
        <div class="print-header print-only">
            <?php if ($logo_image): ?>
                <img src="<?php echo htmlspecialchars($logo_image); ?>" alt="Logo" class="print-logo">
            <?php endif; ?>
            <div class="print-institution-name"><?php echo htmlspecialchars($institution_name); ?></div>
            <div class="print-institution-address"><?php echo htmlspecialchars($institution_address); ?></div>
            <div class="print-title">বিয়োগ রিপোর্ট</div>
            <div style="font-size: 12px; margin-top: 5px;">
                তারিখ পরিসর: <?php echo date('d/m/Y', strtotime($start_date)); ?> থেকে <?php echo date('d/m/Y', strtotime($end_date)); ?>
            </div>
        </div>
        
        <div class="row no-print">
            <div class="col-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5><i class="fas fa-chart-bar"></i> বিয়োগ রিপোর্ট</h5>
                        <button class="btn btn-primary" onclick="window.print()">
                            <i class="fas fa-print"></i> প্রিন্ট করুন
                        </button>
                    </div>
                    <div class="card-body">
                        <!-- Filters -->
                        <form method="GET" class="mb-4 no-print">
                            <div class="row">
                                <div class="col-md-3">
                                    <label class="form-label">শুরুর তারিখ</label>
                                    <input type="date" class="form-control" name="start_date" value="<?php echo $start_date; ?>">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">শেষের তারিখ</label>
                                    <input type="date" class="form-control" name="end_date" value="<?php echo $end_date; ?>">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">বিভাগ</label>
                                    <select class="form-select" name="category_id">
                                        <option value="">সব বিভাগ</option>
                                        <?php foreach ($categories as $category): ?>
                                            <option value="<?php echo $category['id']; ?>" <?php echo $category_id == $category['id'] ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($category['name']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">অনুসন্ধান</label>
                                    <input type="text" class="form-control" name="search" placeholder="বিয়োগ শিরোনাম, বিভাগ, রশিদ নং..." value="<?php echo htmlspecialchars($search_term); ?>">
                                </div>
                                <div class="col-md-1">
                                    <label class="form-label">প্রতি পৃষ্ঠে</label>
                                    <select class="form-select" name="per_page">
                                        <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="25" <?php echo (!$show_all && $records_per_page == 25) ? 'selected' : ''; ?>>25</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>
                                </div>
                                <div class="col-md-1">
                                    <label class="form-label">&nbsp;</label>
                                    <div>
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="fas fa-search"></i> খুঁজুন
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>

                        <!-- Summary Cards -->
                        <div class="row mb-4 no-print">
                            <div class="col-md-4">
                                <div class="summary-card summary-card-expense">
                                    <h5>মোট বিয়োগ</h5>
                                    <h2>৳<?php echo number_format($total_expenses, 2); ?></h2>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="summary-card summary-card-income">
                                    <h5>মোট বিয়োগের সংখ্যা</h5>
                                    <h2><?php echo count($expenses); ?></h2>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="summary-card summary-card-balance">
                                    <h5>গড় বিয়োগ</h5>
                                    <h2>৳<?php echo count($expenses) > 0 ? number_format($total_expenses / count($expenses), 2) : '0.00'; ?></h2>
                                </div>
                            </div>
                        </div>

                        <!-- Category-wise breakdown -->
                        <div class="card mb-4 no-print">
                            <div class="card-header">
                                <h5><i class="fas fa-list"></i> বিভাগ অনুযায়ী বিস্তারিত</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>বিভাগ</th>
                                                <th>বিয়োগের সংখ্যা</th>
                                                <th>মোট পরিমাণ (৳)</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($category_totals as $cat_name => $total): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($cat_name); ?></td>
                                                <td>
                                                    <?php 
                                                        $count = 0;
                                                        foreach ($expenses as $exp) {
                                                            if ($exp['category_name'] == $cat_name) $count++;
                                                        }
                                                        echo $count;
                                                    ?>
                                                </td>
                                                <td class="amount-text">৳<?php echo number_format($total, 2); ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                        <tfoot>
                                            <tr>
                                                <th>সর্বমোট</th>
                                                <th><?php echo count($expenses); ?></th>
                                                <th class="amount-text">৳<?php echo number_format($total_expenses, 2); ?></th>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Expense details table (Visible in both normal and print view) -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-receipt"></i> বিয়োগের বিস্তারিত</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>তারিখ</th>
                                        <th>বিভাগ</th>
                                        <th>শিরোনাম</th>
                                        <th>পরিমাণ (৳)</th>
                                        <th>পদ্ধতি</th>
                                        <th>রশিদ</th>
                                        <th>তৈরিকারী</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($expenses as $expense): ?>
                                    <tr>
                                        <td><?php echo date('d/m/Y', strtotime($expense['expense_date'])); ?></td>
                                        <td><?php echo htmlspecialchars($expense['category_name']); ?></td>
                                        <td><?php echo htmlspecialchars($expense['title']); ?></td>
                                        <td class="amount-text">৳<?php echo number_format($expense['amount'], 2); ?></td>
                                        <td><?php echo $expense['payment_method'] == 'cash' ? 'নগদ' : ($expense['payment_method'] == 'bank_transfer' ? 'ব্যাংক ট্রান্সফার' : ($expense['payment_method'] == 'mobile_banking' ? 'মোবাইল ব্যাংকিং' : 'চেক')); ?></td>
                                        <td><?php echo htmlspecialchars($expense['receipt_no'] ?? '-'); ?></td>
                                        <td><?php echo htmlspecialchars($expense['created_by_name'] ?? 'N/A'); ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                    
                                    <?php if (empty($expenses)): ?>
                                    <tr>
                                        <td colspan="7" class="text-center">কোন বিয়োগ পাওয়া যায়নি</td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th colspan="3" class="text-end">সর্বমোট:</th>
                                        <th class="amount-text">৳<?php echo number_format($total_expenses, 2); ?></th>
                                        <th colspan="3"></th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                        
                        <?php if (!empty($expenses)): ?>
                        <div class="mt-3 d-flex flex-column flex-md-row justify-content-between align-items-center no-print">
                            <div class="mb-2 mb-md-0">
                                <strong>মোট রেকর্ড:</strong> <?php echo $total_records; ?> টি (<?php echo $page; ?>/<?php echo $total_pages; ?> পৃষ্ঠা)
                            </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="?start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&category_id=<?php echo $category_id; ?>&search=<?php echo urlencode($search_term); ?>&per_page=<?php echo isset($_GET['per_page']) ? $_GET['per_page'] : '20'; ?>&page=<?php echo $page - 1; ?>">
                                            <i class="fas fa-chevron-left"></i> পূর্ববর্তী
                                        </a>
                                    </li>
                                    
                                    <!-- Page Numbers -->
                                    <?php
                                    $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="?start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&category_id=<?php echo $category_id; ?>&search=<?php echo urlencode($search_term); ?>&per_page=<?php echo isset($_GET['per_page']) ? $_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="?start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&category_id=<?php echo $category_id; ?>&search=<?php echo urlencode($search_term); ?>&per_page=<?php echo isset($_GET['per_page']) ? $_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="?start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&category_id=<?php echo $category_id; ?>&search=<?php echo urlencode($search_term); ?>&per_page=<?php echo isset($_GET['per_page']) ? $_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="?start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&category_id=<?php echo $category_id; ?>&search=<?php echo urlencode($search_term); ?>&per_page=<?php echo isset($_GET['per_page']) ? $_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>
            </div>
        </div>
    </div>

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