<?php
session_start();
if(!isset($_SESSION['username'])) {
    header("Location: ../login.php");
    exit();
}

include('../includes/db.php');

$from_date = isset($_GET['from_date']) ? $_GET['from_date'] : date('Y-m-01');
$to_date = isset($_GET['to_date']) ? $_GET['to_date'] : date('Y-m-d');
$category_filter = isset($_GET['category']) ? mysqli_real_escape_string($conn, $_GET['category']) : '';

// Build where conditions
$where_conditions = ["DATE(date_time) BETWEEN '$from_date' AND '$to_date'"];
if(!empty($category_filter)) {
    $where_conditions[] = "category = '$category_filter'";
}
$where_clause = implode(" AND ", $where_conditions);

// Get all expenses with category breakdown
$expenses_sql = "SELECT id, title, category, COALESCE(amount, expense_amount) as amount, description, date_time
                 FROM expenses 
                 WHERE $where_clause
                 ORDER BY date_time DESC";
$expenses_result = mysqli_query($conn, $expenses_sql);

// Calculate totals and category-wise summary
$category_summary = [];
$total_expenses = 0;
$expense_list = [];

while($row = mysqli_fetch_assoc($expenses_result)) {
    $amount = floatval($row['amount']);
    $total_expenses += $amount;
    
    $category = !empty($row['category']) ? $row['category'] : 'Uncategorized';
    if(!isset($category_summary[$category])) {
        $category_summary[$category] = [
            'total' => 0,
            'count' => 0,
            'items' => []
        ];
    }
    $category_summary[$category]['total'] += $amount;
    $category_summary[$category]['count']++;
    $category_summary[$category]['items'][] = $row;
    
    $expense_list[] = $row;
}

// Sort categories by total (highest first)
arsort($category_summary);

// Get all unique categories for filter dropdown
$categories_sql = "SELECT DISTINCT 
                    CASE 
                        WHEN category = '' OR category IS NULL THEN 'Uncategorized'
                        ELSE category 
                    END as cat_name
                   FROM expenses 
                   ORDER BY cat_name";
$categories_result = mysqli_query($conn, $categories_sql);
?>

<?php include('../includes/log.php'); ?>
<?php include('../includes/sd.php'); ?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Expense Closing Report</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- PDF Generation Libraries -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <style>
        /* Expense Closing Report Styles - FULL WIDTH, NO EXTRA SPACING */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=Quicksand:wght@400;500;600;700&family=Poppins:wght@300;400;500;600;700&display=swap');

* {
    font-family: 'Poppins', sans-serif;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background: #f5f7fb;
    overflow-x: hidden;
}

h1, h2, h3, h4, h5, h6,
.page-header h2,
.category-header h4,
.expenses-header h4 {
    font-family: 'Poppins', sans-serif;
    font-weight: 600;
}

/* Main Content - FULL WIDTH, MINIMAL PADDING */
.main-content {
    margin-left: 280px;
    padding: 15px 20px;
    transition: all 0.3s;
    width: calc(100% - 280px);
    background: #f5f7fb;
}

.expense-closing-container {
    max-width: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
}

/* Page Header - COMPACT */
.page-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    border-radius: 16px;
    padding: 16px 24px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
    width: 100%;
}

.page-header h2 {
    margin: 0 0 4px 0;
    font-size: 22px;
}

.page-header p {
    margin: 0;
    font-size: 12px;
    opacity: 0.9;
}

.stats-badge {
    background: rgba(255,255,255,0.2);
    padding: 6px 16px;
    border-radius: 40px;
    font-weight: 500;
    font-size: 12px;
}

.btn-pdf-header {
    background: #dc3545;
    color: #fff;
    padding: 6px 18px;
    border-radius: 40px;
    border: none;
    font-weight: 600;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: all 0.3s;
    font-size: 12px;
}

.btn-pdf-header:hover {
    background: #c82333;
}

/* Filter Card - COMPACT */
.filter-card {
    background: #fff;
    border-radius: 16px;
    margin-bottom: 20px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0,0,0,0.03);
    border: 1px solid #f0f0f0;
    width: 100%;
}

.filter-header {
    background: linear-gradient(135deg, #A04657, #6b2a36);
    padding: 10px 20px;
    color: #fff;
    font-weight: 600;
    font-size: 13px;
}

.filter-body {
    padding: 16px;
}

.filter-row {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    align-items: flex-end;
}

.filter-group {
    flex: 1;
    min-width: 160px;
}

.filter-group label {
    display: block;
    font-size: 10px;
    font-weight: 600;
    text-transform: uppercase;
    color: #666;
    margin-bottom: 4px;
}

.form-control-modern {
    width: 100%;
    padding: 8px 12px;
    border: 1.5px solid #e8e8e8;
    border-radius: 10px;
    font-size: 12px;
    background: #fafafa;
}

.form-control-modern:focus {
    border-color: #A04657;
    outline: none;
}

.filter-actions {
    display: flex;
    gap: 8px;
}

.btn-search, .btn-reset, .btn-print {
    padding: 8px 18px;
    border-radius: 10px;
    font-weight: 600;
    font-size: 12px;
    cursor: pointer;
    border: none;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: all 0.3s;
}

.btn-search {
    background: linear-gradient(135deg, #A04657, #6b2a36);
    color: #fff;
}

.btn-search:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(160,70,87,0.3);
}

.btn-reset {
    background: #f0f0f0;
    color: #555;
    text-decoration: none;
}

.btn-reset:hover {
    background: #e0e0e0;
}

.btn-print {
    background: #dc3545;
    color: #fff;
}

.btn-print:hover {
    background: #c82333;
}

/* Period Info - COMPACT */
.period-info {
    background: #e3f2fd;
    padding: 10px 16px;
    border-radius: 10px;
    margin-bottom: 20px;
    font-size: 12px;
    color: #1565c0;
    display: inline-block;
}

.filter-badge {
    background: #1565c0;
    color: #fff;
    padding: 3px 10px;
    border-radius: 20px;
    font-size: 10px;
    margin-left: 12px;
    display: inline-block;
}

/* Summary Cards - COMPACT GRID */
.summary-cards {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: 20px;
    width: 100%;
}

.summary-card {
    background: #fff;
    border-radius: 16px;
    padding: 16px;
    display: flex;
    align-items: center;
    gap: 14px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.03);
    transition: all 0.3s;
    border: 1px solid #f0f0f0;
}

.summary-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 18px rgba(160,70,87,0.1);
}

.summary-icon {
    width: 48px;
    height: 48px;
    border-radius: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.summary-icon i {
    font-size: 22px;
}

.total-expenses-icon { background: rgba(160,70,87,0.1); }
.total-expenses-icon i { color: #A04657; }

.total-amount-icon { background: rgba(220,53,69,0.1); }
.total-amount-icon i { color: #dc3545; }

.categories-icon { background: rgba(23,162,184,0.1); }
.categories-icon i { color: #17a2b8; }

.avg-icon { background: rgba(40,167,69,0.1); }
.avg-icon i { color: #28a745; }

.summary-content h4 {
    margin: 0;
    font-size: 20px;
    font-weight: 800;
}

.summary-content p {
    margin: 3px 0 0;
    font-size: 11px;
    color: #666;
}

.summary-content small {
    font-size: 9px;
    color: #999;
    display: block;
    margin-top: 2px;
}

/* Category Card - COMPACT */
.category-card {
    background: #fff;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0,0,0,0.03);
    border: 1px solid #f0f0f0;
    margin-bottom: 20px;
    width: 100%;
}

.category-header {
    background: #f8f9fc;
    padding: 12px 20px;
    border-bottom: 1px solid #e8e8e8;
    display: flex;
    align-items: center;
    gap: 8px;
}

.category-header i {
    font-size: 18px;
    color: #A04657;
}

.category-header h4 {
    margin: 0;
    font-size: 15px;
    font-weight: 600;
}

.category-body {
    padding: 0;
}

.table-responsive {
    overflow-x: auto;
    width: 100%;
}

.category-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
    min-width: 700px;
}

.category-table th {
    padding: 10px 14px;
    background: #fafbfc;
    font-weight: 700;
    color: #445566;
    font-size: 11px;
    text-transform: uppercase;
    border-bottom: 1px solid #e8e8e8;
}

.category-table td {
    padding: 10px 14px;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
}

.category-cell {
    display: flex;
    align-items: center;
    gap: 8px;
}

.category-cell i {
    color: #A04657;
    font-size: 14px;
}

.category-cell strong {
    font-size: 13px;
    color: #1a1a2e;
}

.transaction-count {
    font-size: 11px;
    color: #666;
    background: #f0f0f0;
    padding: 3px 8px;
    border-radius: 20px;
    display: inline-block;
}

.amount-cell {
    font-weight: 600;
    color: #dc3545;
}

.percentage-cell {
    display: flex;
    align-items: center;
    gap: 10px;
}

.progress-bar {
    flex: 1;
    height: 6px;
    background: #e0e0e0;
    border-radius: 10px;
    overflow: hidden;
}

.progress-fill {
    height: 100%;
    background: #A04657;
    border-radius: 10px;
    transition: width 0.5s ease;
}

.percentage-text {
    font-size: 11px;
    font-weight: 600;
    min-width: 45px;
}

.total-row {
    background: #e9ecef;
    font-weight: 700;
}

/* Expenses Card - COMPACT */
.expenses-card {
    background: #fff;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0,0,0,0.03);
    border: 1px solid #f0f0f0;
    margin-bottom: 20px;
    width: 100%;
}

.expenses-header {
    background: #f8f9fc;
    padding: 12px 20px;
    border-bottom: 1px solid #e8e8e8;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 12px;
}

.expenses-header i {
    font-size: 18px;
    color: #A04657;
}

.expenses-header h4 {
    margin: 0;
    font-size: 15px;
    font-weight: 600;
}

.table-search {
    position: relative;
}

.table-search i {
    position: absolute;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    color: #999;
    font-size: 12px;
}

.search-input {
    padding: 6px 10px 6px 32px;
    border: 1.5px solid #e8e8e8;
    border-radius: 30px;
    width: 200px;
    font-size: 11px;
}

.search-input:focus {
    border-color: #A04657;
    outline: none;
}

.expenses-body {
    padding: 0;
}

.expenses-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
    min-width: 800px;
}

.expenses-table th {
    padding: 10px 14px;
    background: #fafbfc;
    font-weight: 700;
    color: #445566;
    font-size: 11px;
    text-transform: uppercase;
    border-bottom: 1px solid #e8e8e8;
}

.expenses-table td {
    padding: 10px 14px;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
    font-size: 12px;
}

.expenses-table tbody tr:hover {
    background: #fef8f9;
}

.title-cell {
    display: flex;
    align-items: center;
    gap: 6px;
}

.title-cell i {
    color: #A04657;
    font-size: 13px;
}

.category-badge {
    display: inline-block;
    padding: 3px 10px;
    border-radius: 20px;
    font-size: 10px;
    font-weight: 600;
    background: #e3f2fd;
    color: #1565c0;
}

.expense-amount {
    font-weight: 700;
    color: #dc3545;
}

.desc-cell {
    font-size: 11px;
    color: #666;
    max-width: 180px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.total-footer {
    background: #e9ecef;
    font-weight: 700;
}

.empty-state {
    text-align: center;
    padding: 40px !important;
}

.empty-state i {
    font-size: 48px;
    color: #A04657;
    opacity: 0.3;
    margin-bottom: 12px;
    display: block;
}

.empty-state p {
    font-size: 13px;
    font-weight: 500;
    color: #666;
}

.empty-state small {
    font-size: 11px;
    color: #999;
}

/* Sidebar Styles */
.sidebar {
    width: 280px;
    background: #1a1a2e;
    color: #fff;
    transition: all 0.3s;
    position: fixed;
    height: 100vh;
    overflow-y: auto;
    z-index: 1000;
}

.sidebar-header {
    padding: 25px 20px;
    border-bottom: 1px solid rgba(255,255,255,0.1);
    text-align: center;
}

.sidebar-header h3 {
    color: #fff;
    font-size: 1.5rem;
    margin: 0;
}

.sidebar-header p {
    color: rgba(255,255,255,0.7);
    font-size: 0.75rem;
    margin: 5px 0 0;
}

.sidebar-nav {
    padding: 20px 0;
}

.nav-item {
    list-style: none;
}

.nav-link-custom {
    display: flex;
    align-items: center;
    padding: 12px 25px;
    color: rgba(255,255,255,0.8);
    text-decoration: none;
    transition: all 0.3s;
    gap: 12px;
    font-size: 0.9rem;
}

.nav-link-custom:hover, .nav-link-custom.active {
    background: rgba(160,70,87,0.3);
    color: #fff;
    border-left: 3px solid #A04657;
}

.nav-link-custom i {
    width: 22px;
    font-size: 1.1rem;
}

/* Top Header */
.top-header {
    background: #fff;
    border-radius: 16px;
    padding: 12px 20px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 10px rgba(0,0,0,0.03);
    width: 100%;
}

.welcome-text h4 {
    margin: 0;
    font-size: 1.1rem;
    color: #333;
}

.welcome-text p {
    margin: 0;
    font-size: 0.75rem;
    color: #777;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 20px;
}

.logout-btn {
    background: #A04657;
    color: #fff;
    padding: 6px 18px;
    border-radius: 30px;
    text-decoration: none;
    font-size: 0.8rem;
    transition: all 0.3s;
}

.logout-btn:hover {
    background: #6b2a36;
    color: #fff;
}

/* Footer */
.footer {
    background: #fff;
    border-radius: 12px;
    padding: 12px 20px;
    margin-top: 20px;
    text-align: center;
    font-size: 0.75rem;
    color: #666;
    box-shadow: 0 2px 10px rgba(0,0,0,0.03);
    width: 100%;
}

/* Print Styles */
@media print {
    .sidebar, .top-header, .footer, .filter-card, .stats-badge, .btn-print, .btn-reset, .btn-search,
    .page-header .header-right, .table-search, .btn-pdf-header {
        display: none !important;
    }
    .main-content {
        margin: 0;
        padding: 0;
        width: 100%;
    }
    .page-header {
        background: #A04657;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }
    .category-card, .expenses-card {
        box-shadow: none;
        border: 1px solid #ddd;
    }
    .progress-bar {
        border: 1px solid #ddd;
    }
}

/* Responsive */
@media (max-width: 1200px) {
    .summary-cards {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 992px) {
    .sidebar {
        margin-left: -280px;
    }
    .main-content {
        margin-left: 0;
        width: 100%;
        padding: 12px 15px;
    }
}

@media (max-width: 768px) {
    .main-content {
        padding: 10px 12px;
    }
    .expense-closing-container {
        padding: 0;
    }
    .page-header {
        flex-direction: column;
        text-align: center;
        gap: 12px;
        padding: 14px 18px;
    }
    .page-header h2 {
        font-size: 18px;
    }
    .filter-row {
        flex-direction: column;
        gap: 10px;
    }
    .filter-actions {
        flex-direction: row;
        flex-wrap: wrap;
    }
    .summary-cards {
        grid-template-columns: 1fr;
        gap: 12px;
    }
    .top-header {
        padding: 10px 15px;
        margin-bottom: 15px;
    }
    .footer {
        padding: 10px 15px;
        margin-top: 15px;
    }
    .expenses-table th {
        display: none;
    }
    .expenses-table td {
        display: block;
        text-align: right;
        padding-left: 50%;
        position: relative;
        border-bottom: none;
    }
    .expenses-table td::before {
        content: attr(data-label);
        position: absolute;
        left: 14px;
        width: 45%;
        text-align: left;
        font-weight: 700;
        font-size: 10px;
        color: #555;
    }
    .expenses-table tr {
        display: block;
        margin-bottom: 10px;
        border: 1px solid #e8e8e8;
        border-radius: 12px;
        overflow: hidden;
    }
    .expenses-table td:last-child {
        border-bottom: none;
    }
    .category-table th {
        display: none;
    }
    .category-table td {
        display: block;
        text-align: right;
        padding-left: 50%;
        position: relative;
        border-bottom: none;
    }
    .category-table td::before {
        content: attr(data-label);
        position: absolute;
        left: 14px;
        width: 45%;
        text-align: left;
        font-weight: 700;
        font-size: 10px;
        color: #555;
    }
    .category-table tr {
        display: block;
        margin-bottom: 10px;
        border-bottom: 1px solid #e8e8e8;
    }
    .percentage-cell {
        flex-direction: column;
        align-items: flex-end;
        gap: 5px;
    }
    .progress-bar {
        width: 100%;
    }
    .summary-card {
        padding: 12px;
    }
    .summary-icon {
        width: 42px;
        height: 42px;
    }
    .summary-icon i {
        font-size: 20px;
    }
    .summary-content h4 {
        font-size: 18px;
    }
}

/* Scrollbar */
::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb {
    background: #A04657;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
    background: #6b2a36;
}
    </style>
</head>
<body>
<div class="expense-closing-container">
    <!-- Page Header (outside PDF capture) -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-file-invoice-dollar"></i> Expense Closing Report</h2>
            <p>Complete summary of all expenses with category-wise breakdown</p>
        </div>
        <div class="header-right">
            <!--<button onclick="downloadPDF()" class="btn-pdf-header">-->
            <!--    <i class="fas fa-file-pdf"></i> Download PDF-->
            <!--</button>-->
            <div class="stats-badge">
                <i class="fas fa-calendar"></i>
                <span><?php echo date('d-m-Y H:i'); ?></span>
            </div>
        </div>
    </div>

    <!-- Filter Card (outside PDF capture) -->
    <div class="filter-card">
        <div class="filter-header">
            <i class="fas fa-filter"></i> Filter Report
        </div>
        <div class="filter-body">
            <form method="GET" action="" class="filter-form">
                <div class="filter-row">
                    <div class="filter-group">
                        <label><i class="fas fa-calendar-alt"></i> From Date</label>
                        <input type="date" name="from_date" class="form-control-modern" value="<?php echo $from_date; ?>">
                    </div>
                    <div class="filter-group">
                        <label><i class="fas fa-calendar-alt"></i> To Date</label>
                        <input type="date" name="to_date" class="form-control-modern" value="<?php echo $to_date; ?>">
                    </div>
                    <div class="filter-group">
                        <label><i class="fas fa-tag"></i> Category</label>
                        <select name="category" class="form-control-modern">
                            <option value="">-- All Categories --</option>
                            <?php 
                            mysqli_data_seek($categories_result, 0);
                            while($cat = mysqli_fetch_assoc($categories_result)): 
                            ?>
                                <option value="<?php echo htmlspecialchars($cat['cat_name']); ?>" <?php echo $category_filter == $cat['cat_name'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($cat['cat_name']); ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="filter-actions">
                        <button type="submit" class="btn-search">
                            <i class="fas fa-search"></i> Filter
                        </button>
                        <a href="expense_closing_report.php" class="btn-reset">
                            <i class="fas fa-sync-alt"></i> Reset
                        </a>
                        <button type="button" onclick="downloadPDF()" class="btn-print">
                            <i class="fas fa-file-pdf"></i> Download PDF
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- PDF Report Content -->
    <div id="report-content-expense">
        <!-- Period Info -->
        <div class="period-info">
            <i class="fas fa-calendar-week"></i>
            Report Period: <strong><?php echo date('d-m-Y', strtotime($from_date)); ?></strong> to <strong><?php echo date('d-m-Y', strtotime($to_date)); ?></strong>
            <?php if(!empty($category_filter)): ?>
                <span class="filter-badge"><i class="fas fa-tag"></i> Category: <?php echo htmlspecialchars($category_filter); ?></span>
            <?php endif; ?>
        </div>

        <!-- Summary Cards -->
        <div class="summary-cards">
            <div class="summary-card">
                <div class="summary-icon total-expenses-icon">
                    <i class="fas fa-chart-line"></i>
                </div>
                <div class="summary-content">
                    <h4><?php echo count($expense_list); ?></h4>
                    <p>Total Transactions</p>
                    <small>Number of expense entries</small>
                </div>
            </div>
            <div class="summary-card">
                <div class="summary-icon total-amount-icon">
                    <i class="fas fa-rupee-sign"></i>
                </div>
                <div class="summary-content">
                    <h4>Rs <?php echo number_format($total_expenses, 2); ?></h4>
                    <p>Total Expenses</p>
                    <small>Overall expense amount</small>
                </div>
            </div>
            <div class="summary-card">
                <div class="summary-icon categories-icon">
                    <i class="fas fa-tags"></i>
                </div>
                <div class="summary-content">
                    <h4><?php echo count($category_summary); ?></h4>
                    <p>Categories</p>
                    <small>Distinct expense categories</small>
                </div>
            </div>
            <div class="summary-card">
                <div class="summary-icon avg-icon">
                    <i class="fas fa-chart-bar"></i>
                </div>
                <div class="summary-content">
                    <h4>Rs <?php echo number_format(count($expense_list) > 0 ? $total_expenses / count($expense_list) : 0, 2); ?></h4>
                    <p>Average per Transaction</p>
                    <small>Avg expense amount</small>
                </div>
            </div>
        </div>

        <!-- Category-wise Breakdown -->
        <div class="category-card">
            <div class="category-header">
                <i class="fas fa-chart-pie"></i>
                <h4>Category-wise Expense Breakdown</h4>
            </div>
            <div class="category-body">
                <div class="table-responsive">
                    <table class="category-table">
                        <thead>
                            <tr>
                                <th width="35%">Category</th>
                                <th width="15%">Transactions</th>
                                <th width="25%">Amount (Rs)</th>
                                <th width="25%">Percentage</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(count($category_summary) > 0): ?>
                                <?php foreach($category_summary as $category => $data): 
                                    $percentage = $total_expenses > 0 ? ($data['total'] / $total_expenses) * 100 : 0;
                                ?>
                                    <tr>
                                        <td data-label="Category">
                                            <div class="category-cell">
                                                <i class="fas fa-folder-open"></i>
                                                <strong><?php echo htmlspecialchars($category); ?></strong>
                                            </div>
                                        </td>
                                        <td data-label="Transactions">
                                            <span class="transaction-count"><?php echo $data['count']; ?> transactions</span>
                                        </td>
                                        <td data-label="Amount">
                                            <div class="amount-cell">Rs <?php echo number_format($data['total'], 2); ?></div>
                                        </td>
                                        <td data-label="Percentage">
                                            <div class="percentage-cell">
                                                <div class="progress-bar">
                                                    <div class="progress-fill" style="width: <?php echo $percentage; ?>%;"></div>
                                                </div>
                                                <span class="percentage-text"><?php echo number_format($percentage, 2); ?>%</span>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" class="empty-state">No expense data found for this period</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                        <tfoot>
                            <tr class="total-row">
                                <td><strong>GRAND TOTAL</strong></td>
                                <td><strong><?php echo count($expense_list); ?> transactions</strong></td>
                                <td><strong>Rs <?php echo number_format($total_expenses, 2); ?></strong></td>
                                <td><strong>100%</strong></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>

        <!-- Detailed Expenses Table -->
        <div class="expenses-card">
            <div class="expenses-header">
                <i class="fas fa-list"></i>
                <h4>Detailed Expense List</h4>
                <div class="table-search">
                    <i class="fas fa-search"></i>
                    <input type="text" id="tableSearch" placeholder="Search expenses..." class="search-input">
                </div>
            </div>
            <div class="expenses-body">
                <div class="table-responsive">
                    <table class="expenses-table" id="expensesTable">
                        <thead>
                            <tr>
                                <th width="5%">#</th>
                                <th width="15%">Date</th>
                                <th width="25%">Title</th>
                                <th width="15%">Category</th>
                                <th width="20%">Amount (Rs)</th>
                                <th width="20%">Description</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(count($expense_list) > 0): ?>
                                <?php 
                                $sr_no = 1;
                                foreach($expense_list as $expense): 
                                    $exp_amount = floatval($expense['amount']);
                                ?>
                                    <tr>
                                        <td data-label="#"><?php echo $sr_no++; ?></td>
                                        <td data-label="Date"><?php echo date('d-m-Y', strtotime($expense['date_time'])); ?></td>
                                        <td data-label="Title">
                                            <div class="title-cell">
                                                <i class="fas fa-receipt"></i>
                                                <?php echo htmlspecialchars($expense['title']); ?>
                                            </div>
                                        </td>
                                        <td data-label="Category">
                                            <span class="category-badge">
                                                <?php echo htmlspecialchars(!empty($expense['category']) ? $expense['category'] : 'Uncategorized'); ?>
                                            </span>
                                        </td>
                                        <td data-label="Amount">
                                            <div class="amount-cell expense-amount">Rs <?php echo number_format($exp_amount, 2); ?></div>
                                        </td>
                                        <td data-label="Description">
                                            <div class="desc-cell">
                                                <?php echo htmlspecialchars($expense['description'] ?: '—'); ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6" class="empty-state">
                                        <i class="fas fa-file-invoice-dollar"></i>
                                        <p>No expenses found</p>
                                        <small>Try changing your filter criteria</small>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                        <tfoot>
                            <tr class="total-footer">
                                <td colspan="4"><strong>TOTAL</strong></td>
                                <td class="amount-cell"><strong>Rs <?php echo number_format($total_expenses, 2); ?></strong></td>
                                <td></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div><!-- end #report-content-expense -->
</div>

<!-- PDF Generation Script -->
<script>
// Pass filter info to JS for PDF header
const pdfDateFrom = '<?php echo date('d-m-Y', strtotime($from_date)); ?>';
const pdfDateTo   = '<?php echo date('d-m-Y', strtotime($to_date)); ?>';
const reportTitle = 'Expense Closing Report';

async function downloadPDF() {
    const element = document.getElementById('report-content-expense');
    if (!element) {
        alert('No report content to download.');
        return;
    }

    // Disable all PDF buttons
    const pdfBtns = document.querySelectorAll('.btn-pdf-header, .btn-print');
    const originalHTMLs = Array.from(pdfBtns).map(btn => btn.innerHTML);
    pdfBtns.forEach(btn => {
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating PDF...';
        btn.disabled = true;
    });

    try {
        // Capture the full content as one high-res canvas
        const canvas = await html2canvas(element, {
            scale: 2,
            useCORS: true,
            logging: false,
            allowTaint: true,
            backgroundColor: '#ffffff'
        });

        const { jsPDF } = window.jspdf;
        const pdf = new jsPDF('p', 'mm', 'a4');

        const pageWidthMM  = 210;
        const pageHeightMM = 297;
        const marginMM     = 10;
        const contentWidthMM = pageWidthMM - marginMM * 2;

        const headerHeightMM = 62;
        const bottomMarginMM = 10;
        const availHeightMM = pageHeightMM - headerHeightMM - bottomMarginMM;

        const pxPerMM = canvas.width / contentWidthMM;
        const totalImgHeightMM = canvas.height / pxPerMM;

        // ── Header drawing function ──────────────────────
        function addHeader() {
            pdf.setFont('helvetica', 'bold');
            pdf.setFontSize(18);
            pdf.setTextColor(160, 70, 87);
            pdf.text('ALFATEH PETROLEUM SERVICE', pageWidthMM / 2, 20, { align: 'center' });

            pdf.setFont('helvetica', 'normal');
            pdf.setFontSize(11);
            pdf.setTextColor(100, 100, 100);
            pdf.text('Complete Fuel Station Management Solution', pageWidthMM / 2, 27, { align: 'center' });

            pdf.setFontSize(10);
            pdf.setTextColor(80, 80, 80);
            pdf.text('Shaikh bhirkyo road Tando Muhammad khan', pageWidthMM / 2, 34, { align: 'center' });

            pdf.setDrawColor(160, 70, 87);
            pdf.setLineWidth(0.5);
            pdf.line(marginMM, 40, pageWidthMM - marginMM, 40);

            pdf.setFont('helvetica', 'bold');
            pdf.setFontSize(16);
            pdf.setTextColor(0, 0, 0);
            pdf.text(reportTitle, pageWidthMM / 2, 48, { align: 'center' });

            const periodText = `Period: ${pdfDateFrom} To ${pdfDateTo}`;
            pdf.setFont('helvetica', 'normal');
            pdf.setFontSize(10);
            pdf.setTextColor(80, 80, 80);
            pdf.text(periodText, pageWidthMM / 2, 55, { align: 'center' });

            pdf.setDrawColor(160, 70, 87);
            pdf.line(marginMM, 59, pageWidthMM - marginMM, 59);
        }

        // ── Slice-and-draw loop ──────────────────────────
        let remainingMM   = totalImgHeightMM;
        let sourceYpx     = 0;

        addHeader(); // header for page 1

        while (remainingMM > 0.5) {
            const sliceHeightMM = Math.min(remainingMM, availHeightMM);
            const sliceHeightPx = Math.round(sliceHeightMM * pxPerMM);

            const tmpCanvas = document.createElement('canvas');
            tmpCanvas.width  = canvas.width;
            tmpCanvas.height = sliceHeightPx;
            const ctx = tmpCanvas.getContext('2d');
            ctx.drawImage(
                canvas,
                0, sourceYpx,
                canvas.width, sliceHeightPx,
                0, 0,
                canvas.width, sliceHeightPx
            );

            const sliceDataURL = tmpCanvas.toDataURL('image/png');

            pdf.addImage(
                sliceDataURL, 'PNG',
                marginMM, headerHeightMM,
                contentWidthMM, sliceHeightMM
            );

            sourceYpx    += sliceHeightPx;
            remainingMM  -= sliceHeightMM;

            if (remainingMM > 0.5) {
                pdf.addPage();
                addHeader();
            }
        }

        const fileName = `Expense_Closing_Report_${pdfDateFrom}_to_${pdfDateTo}.pdf`.replace(/\s+/g, '_');
        pdf.save(fileName);

    } catch (error) {
        console.error('Error generating PDF:', error);
        alert('An error occurred while generating the PDF. Please try again.');
    } finally {
        pdfBtns.forEach((btn, i) => {
            btn.innerHTML = originalHTMLs[i];
            btn.disabled = false;
        });
    }
}

// Table search functionality
document.getElementById('tableSearch')?.addEventListener('keyup', function() {
    let searchValue = this.value.toLowerCase();
    let rows = document.querySelectorAll('#expensesTable tbody tr');
    rows.forEach(row => {
        let text = row.textContent.toLowerCase();
        row.style.display = text.includes(searchValue) ? '' : 'none';
    });
});
</script>

<?php include('../includes/ft.php'); ?>
</body>
</html>