<?php
require 'element/connection.php';
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Get user ID from session
$my_id = $_SESSION['user_id'];

// Fetch user details
$user_query = mysqli_query($conn, "SELECT * FROM users WHERE user_id = '$my_id'");
$user_data = mysqli_fetch_assoc($user_query);

// Get date filters
$filter_type = isset($_GET['filter']) ? $_GET['filter'] : 'all';
$from_date = isset($_GET['from_date']) ? $_GET['from_date'] : date('Y-m-d', strtotime('-30 days'));
$to_date = isset($_GET['to_date']) ? $_GET['to_date'] : date('Y-m-d');

// Build query based on filters with proper handling of all fields
$income_query = "SELECT *, 
                        COALESCE(tds, 0) as tds, 
                        COALESCE(admin_charges, 0) as admin_charges,
                        COALESCE(income_type, 'Transaction') as income_type
                 FROM income_history 
                 WHERE user_id = '$my_id'";

if ($filter_type == 'today') {
    $income_query .= " AND DATE(processed_at) = CURDATE()";
} elseif ($filter_type == 'week') {
    $income_query .= " AND processed_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
} elseif ($filter_type == 'month') {
    $income_query .= " AND processed_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
} elseif ($filter_type == 'custom' && $from_date && $to_date) {
    $income_query .= " AND DATE(processed_at) BETWEEN '$from_date' AND '$to_date'";
}

$income_query .= " ORDER BY processed_at DESC";

$income_result = mysqli_query($conn, $income_query);

// Calculate totals
$total_credited = 0;
$total_debited = 0;
$total_tds = 0;
$total_admin = 0;
$total_withdrawals = 0;

$temp_result = mysqli_query($conn, $income_query);
while ($row = mysqli_fetch_assoc($temp_result)) {
    // Cast all numeric values to float to avoid type issues
    $amount = (float)($row['amount'] ?? 0);
    $tds = (float)($row['tds'] ?? 0);
    $admin = (float)($row['admin_charges'] ?? 0);
    
    // Check if it's a withdrawal
    if ($row['income_type'] == 'Withdrawal' || $row['income_type'] == 'Withdraw' || $row['credit_debit'] == 1) {
        $total_debited += $amount;
        if ($row['income_type'] == 'Withdrawal' || $row['income_type'] == 'Withdraw') {
            $total_withdrawals += $amount;
        }
    } else {
        $total_credited += $amount;
    }
    
    $total_tds += $tds;
    $total_admin += $admin;
}

// Get income by type (excluding withdrawals for separate display)
$type_query = "SELECT income_type, COUNT(*) as count, SUM(amount) as total 
               FROM income_history 
               WHERE user_id = '$my_id' 
               AND income_type NOT IN ('Withdrawal', 'Withdraw')
               AND credit_debit = 0
               GROUP BY income_type";
$type_result = mysqli_query($conn, $type_query);
$income_types = [];
while ($row = mysqli_fetch_assoc($type_result)) {
    $income_types[] = $row;
}

// Get withdrawals separately
$withdrawal_query = "SELECT COUNT(*) as count, SUM(amount) as total 
                    FROM income_history 
                    WHERE user_id = '$my_id' 
                    AND (income_type = 'Withdrawal' OR income_type = 'Withdraw' OR credit_debit = 1)";
$withdrawal_result = mysqli_query($conn, $withdrawal_query);
$withdrawal_data = mysqli_fetch_assoc($withdrawal_result);

// Get monthly income for chart
$monthly_query = "SELECT DATE_FORMAT(processed_at, '%Y-%m') as month, 
                         SUM(CASE WHEN credit_debit = 0 THEN amount ELSE 0 END) as credited,
                         SUM(CASE WHEN credit_debit = 1 THEN amount ELSE 0 END) as debited
                  FROM income_history 
                  WHERE user_id = '$my_id' AND processed_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
                  GROUP BY DATE_FORMAT(processed_at, '%Y-%m')
                  ORDER BY month DESC";
$monthly_result = mysqli_query($conn, $monthly_query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title><?php echo htmlspecialchars($user_data['name']); ?> || Income History</title>
    <meta content="" name="description">
    <meta content="" name="keywords">

    <!-- Favicons -->
    <link href="../img/logo/logo22222.png" rel="icon">

    <!-- Google Fonts -->
  <link href="https://fonts.gstatic.com" rel="preconnect">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">
<link rel="stylesheet" href="assets/styles/style.css">
  <!-- Vendor CSS Files -->
  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
  <link href="assets/vendor/quill/quill.snow.css" rel="stylesheet">
  <link href="assets/vendor/quill/quill.bubble.css" rel="stylesheet">
  <link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet">
  <link href="assets/vendor/simple-datatables/style.css" rel="stylesheet">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="assets/vendor/bootstrap/css/bootstrap.min.css">
    <link href="assets/vendor/fonts/circular-std/style.css" rel="stylesheet">
   
    <link rel="stylesheet" href="assets/vendor/fonts/fontawesome/css/fontawesome-all.css">
    <link rel="stylesheet" href="assets/vendor/charts/morris-bundle/morris.css">
    <link rel="stylesheet" href="..assets/vendor/fonts/material-design-iconic-font/css/materialdesignicons.min.css">

  <!-- Template Main CSS File -->
  <link href="assets/css/style.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs=" crossorigin="anonymous"></script>
   
  <link href="assets/img/apple-touch-icon.png" rel="apple-touch-icon">

  <!-- Google Fonts -->
  <link href="https://fonts.gstatic.com" rel="preconnect">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">

  <!-- Vendor CSS Files -->
  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
  <link href="assets/vendor/quill/quill.snow.css" rel="stylesheet">
  <link href="assets/vendor/quill/quill.bubble.css" rel="stylesheet">
  <link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet">
  <link href="assets/vendor/simple-datatables/style.css" rel="stylesheet">
<!-- Add this if not already present -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <!-- Template Main CSS File -->
  <link href="assets/css/style.css" rel="stylesheet">
  <link href="assets/styles/style.css" rel="stylesheet">
   <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --success-gradient: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            --danger-gradient: linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%);
            --primary-color: #667eea;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f8fafc;
        }

        /* Stats Cards */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            border-radius: 24px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
            border: 1px solid rgba(102, 126, 234, 0.1);
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 40px rgba(102, 126, 234, 0.15);
        }

        .stat-icon {
            width: 60px;
            height: 60px;
            border-radius: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 15px;
            font-size: 24px;
            color: white;
        }

        .stat-icon.credited { background: linear-gradient(135deg, #10b981 0%, #34d399 100%); }
        .stat-icon.debited { background: linear-gradient(135deg, #ef4444 0%, #f87171 100%); }
        .stat-icon.tds { background: linear-gradient(135deg, #f59e0b 0%, #fbbf24 100%); }
        .stat-icon.balance { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }

        .stat-value {
            font-size: 2rem;
            font-weight: 800;
            color: #1e293b;
            margin-bottom: 5px;
        }

        .stat-label {
            color: #64748b;
            font-size: 0.9rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        /* Filter Section */
        .filter-section {
            background: white;
            border-radius: 24px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
            margin-bottom: 30px;
        }

        .filter-tabs {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-bottom: 20px;
        }

        .filter-tab {
            padding: 10px 20px;
            border-radius: 40px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            background: #f1f5f9;
            color: #64748b;
            border: none;
            text-decoration: none;
            display: inline-block;
        }

        .filter-tab:hover,
        .filter-tab.active {
            background: var(--primary-gradient);
            color: white;
        }

        .date-range {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }

        .date-input {
            padding: 10px 15px;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            font-size: 0.95rem;
        }

        .apply-filter {
            padding: 10px 25px;
            border: none;
            border-radius: 12px;
            background: var(--primary-gradient);
            color: white;
            font-weight: 600;
            cursor: pointer;
        }

        /* Chart Container */
        .chart-container {
            background: white;
            border-radius: 24px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
            margin-bottom: 30px;
        }

        /* Income Types Grid */
        .types-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 30px;
        }

        .type-card {
            background: white;
            border-radius: 20px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            border-left: 4px solid #667eea;
        }

        .type-name {
            font-weight: 600;
            color: #64748b;
            margin-bottom: 5px;
        }

        .type-total {
            font-size: 1.3rem;
            font-weight: 700;
            color: #1e293b;
        }

        .type-count {
            font-size: 0.85rem;
            color: #94a3b8;
        }

        /* Table Styles */
        .table-container {
            background: white;
            border-radius: 24px;
            padding: 25px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.05);
            overflow-x: auto;
        }

        .income-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0 10px;
        }

        .income-table thead th {
            padding: 15px 20px;
            font-size: 0.9rem;
            font-weight: 700;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            background: #f8fafc;
            border-radius: 12px;
        }

        .income-table tbody tr {
            background: white;
            border-radius: 16px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.03);
            transition: all 0.3s ease;
        }

        .income-table tbody tr:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.15);
        }

        .income-table tbody td {
            padding: 20px;
            vertical-align: middle;
        }

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

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 12px;
            background: var(--primary-gradient);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
        }

        .badge-income {
            padding: 6px 12px;
            border-radius: 30px;
            font-size: 0.85rem;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .badge-credited {
            background: #dcfce7;
            color: #166534;
        }

        .badge-debited {
            background: #fee2e2;
            color: #991b1b;
        }

        .amount-positive {
            color: #10b981;
            font-weight: 700;
        }

        .amount-negative {
            color: #ef4444;
            font-weight: 700;
        }

        .transaction-id {
            font-family: 'Courier New', monospace;
            font-size: 0.85rem;
            color: #64748b;
        }

        /* Export Button */
        .export-btn {
            padding: 12px 25px;
            border: none;
            border-radius: 12px;
            background: var(--primary-gradient);
            color: white;
            font-weight: 600;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 20px;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .date-range {
                flex-direction: column;
                align-items: stretch;
            }
        }
    </style>
</head>

<body>

<!-- Header & Sidebar -->
<?php include 'element/header.php'; ?>
<?php include 'element/sidebar.php'; ?>

<main id="main" class="main">
    <div class="pagetitle">
        <h1>Income History</h1>
        <nav>
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                <li class="breadcrumb-item active">Income</li>
            </ol>
        </nav>
    </div>

   <!-- Stats Cards -->
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-icon balance">
            <i class="fas fa-wallet"></i>
        </div>
        <div class="stat-value">₹<?php echo number_format($user_data['wallet'] ?? 0, 2); ?></div>
        <div class="stat-label">Current Balance</div>
    </div>

    <div class="stat-card">
        <div class="stat-icon credited">
            <i class="fas fa-arrow-down"></i>
        </div>
        <div class="stat-value">₹<?php echo number_format($total_credited, 2); ?></div>
        <div class="stat-label">Total Income</div>
    </div>

    <div class="stat-card">
        <div class="stat-icon debited">
            <i class="fas fa-arrow-up"></i>
        </div>
        <div class="stat-value">₹<?php echo number_format($total_withdrawals, 2); ?></div>
        <div class="stat-label">Total Withdrawals</div>
        <small class="text-muted"><?php echo $withdrawal_data['count'] ?? 0; ?> transactions</small>
    </div>

    <div class="stat-card">
        <div class="stat-icon tds">
            <i class="fas fa-percent"></i>
        </div>
        <div class="stat-value">₹<?php echo number_format($total_tds + $total_admin, 2); ?></div>
        <div class="stat-label">Total Deductions</div>
    </div>
</div>

<!-- Income Types and Withdrawal Summary -->
<div class="row mb-4">
    <div class="col-md-8">
        <?php if (!empty($income_types)): ?>
        <div class="types-grid">
            <?php foreach ($income_types as $type): ?>
            <div class="type-card">
                <div class="type-name"><?php echo htmlspecialchars($type['income_type'] ?: 'Other Income'); ?></div>
                <div class="type-total">₹<?php echo number_format($type['total'], 2); ?></div>
                <div class="type-count"><?php echo $type['count']; ?> transactions</div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
    <div class="col-md-4">
        <div class="type-card" style="border-left-color: #ef4444;">
            <div class="type-name">
                <i class="fas fa-money-bill-wave me-2" style="color: #ef4444;"></i>
                Withdrawals
            </div>
            <div class="type-total" style="color: #ef4444;">₹<?php echo number_format($withdrawal_data['total'] ?? 0, 2); ?></div>
            <div class="type-count"><?php echo $withdrawal_data['count'] ?? 0; ?> withdrawal requests</div>
            <a href="withdrawal-history.php" class="btn btn-sm btn-outline-danger mt-2">View All Withdrawals</a>
        </div>
    </div>
</div>

    <!-- Chart -->
    <div class="chart-container">
        <canvas id="incomeChart"></canvas>
    </div>

    <!-- Filter Section -->
    <div class="filter-section">
        <div class="filter-tabs">
            <a href="?filter=all" class="filter-tab <?php echo $filter_type == 'all' ? 'active' : ''; ?>">All Time</a>
            <a href="?filter=today" class="filter-tab <?php echo $filter_type == 'today' ? 'active' : ''; ?>">Today</a>
            <a href="?filter=week" class="filter-tab <?php echo $filter_type == 'week' ? 'active' : ''; ?>">This Week</a>
            <a href="?filter=month" class="filter-tab <?php echo $filter_type == 'month' ? 'active' : ''; ?>">This Month</a>
            <a href="?filter=custom" class="filter-tab <?php echo $filter_type == 'custom' ? 'active' : ''; ?>">Custom Range</a>
        </div>

        <?php if ($filter_type == 'custom'): ?>
        <form method="GET" class="date-range">
            <input type="hidden" name="filter" value="custom">
            <input type="date" name="from_date" class="date-input" value="<?php echo $from_date; ?>" required>
            <span>to</span>
            <input type="date" name="to_date" class="date-input" value="<?php echo $to_date; ?>" required>
            <button type="submit" class="apply-filter">Apply</button>
        </form>
        <?php endif; ?>
    </div>

    <!-- Export Button -->
    <button class="export-btn" onclick="exportToExcel()">
        <i class="fas fa-file-excel"></i> Export to Excel
    </button>

    <!-- Income Table -->
    <div class="table-container">
        <table class="income-table" id="incomeTable">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Date & Time</th>
                    <th>From / To User</th>
                    <th>Description</th>
                    <th>Type</th>
                    <th>Amount</th>
                    <th>Deductions</th>
                    <th>Net Amount</th>
                    <th>Transaction ID</th>
                </tr>
            </thead>
            <tbody>
                <?php if (mysqli_num_rows($income_result) > 0): ?>
                    <?php $a = 1; ?>
                    <?php while ($row = mysqli_fetch_assoc($income_result)): 
                        // Get user details for from_user and to_user
                        $from_user_name = '';
                        $to_user_name = '';
                        
                        if ($row['from_user_id']) {
                            $from_query = mysqli_query($conn, "SELECT name, user_id FROM users WHERE user_id = '{$row['from_user_id']}'");
                            if ($from_query && mysqli_num_rows($from_query) > 0) {
                                $from = mysqli_fetch_assoc($from_query);
                                $from_user_name = $from['name'] . ' (ID: ' . $from['user_id'] . ')';
                            }
                        }
                        
                        if ($row['to_user_id']) {
                            $to_query = mysqli_query($conn, "SELECT name, user_id FROM users WHERE user_id = '{$row['to_user_id']}'");
                            if ($to_query && mysqli_num_rows($to_query) > 0) {
                                $to = mysqli_fetch_assoc($to_query);
                                $to_user_name = $to['name'] . ' (ID: ' . $to['user_id'] . ')';
                            }
                        }
                        
                        $net_amount = $row['amount'] - ($row['tds'] + $row['admin_charges']);

// Special handling for Level Income - always show as credited
if ($row['income_type'] == 'Level Income') {
    $is_credited = true;  // Force Level Income to show as credited
} else {
    $is_credited = ($row['credit_debit'] == 0);
}
                    ?>
                    <tr>
                        <td><?php echo $a++; ?></td>
                        <td>
                            <strong><?php echo date('d M Y', strtotime($row['processed_at'])); ?></strong><br>
                            <small class="text-muted"><?php echo date('h:i A', strtotime($row['processed_at'])); ?></small>
                        </td>
                        <td>
                            <?php if ($row['from_user_id'] && $row['from_user_id'] != $my_id): ?>
                                <div class="user-info">
                                    <div class="user-avatar">
                                        <?php echo strtoupper(substr($from_user_name, 0, 1)); ?>
                                    </div>
                                    <div>
                                        <strong>From:</strong> <?php echo $from_user_name; ?>
                                    </div>
                                </div>
                            <?php elseif ($row['to_user_id'] && $row['to_user_id'] != $my_id): ?>
                                <div class="user-info">
                                    <div class="user-avatar">
                                        <?php echo strtoupper(substr($to_user_name, 0, 1)); ?>
                                    </div>
                                    <div>
                                        <strong>To:</strong> <?php echo $to_user_name; ?>
                                    </div>
                                </div>
                            <?php else: ?>
                                <span class="text-muted">System</span>
                            <?php endif; ?>
                        </td>
                        <td><?php echo htmlspecialchars($row['description']); ?></td>
                        <td>
                            <span class="badge-income <?php echo $is_credited ? 'badge-credited' : 'badge-debited'; ?>">
                                <i class="fas fa-<?php echo $is_credited ? 'arrow-down' : 'arrow-up'; ?>"></i>
                                <?php echo $row['income_type'] ?: ($is_credited ? 'Credit' : 'Debit'); ?>
                            </span>
                        </td>
                        <td class="<?php echo $is_credited ? 'amount-positive' : 'amount-negative'; ?>">
                            <?php echo $is_credited ? '+' : '-'; ?>₹<?php echo number_format($row['amount'], 2); ?>
                        </td>
                        <td>
                            <?php if ($row['tds'] > 0): ?>
                                <div>TDS: -₹<?php echo number_format($row['tds'], 2); ?></div>
                            <?php endif; ?>
                            <?php if ($row['admin_charges'] > 0): ?>
                                <div>Admin: -₹<?php echo number_format($row['admin_charges'], 2); ?></div>
                            <?php endif; ?>
                        </td>
                        <td class="<?php echo $net_amount >= 0 ? 'amount-positive' : 'amount-negative'; ?>">
                            ₹<?php echo number_format($net_amount, 2); ?>
                        </td>
                        <td>
                            <?php if ($row['transaction_id']): ?>
                                <span class="transaction-id"><?php echo $row['transaction_id']; ?></span>
                            <?php else: ?>
                                <span class="transaction-id">TXN<?php echo str_pad($row['id'], 8, '0', STR_PAD_LEFT); ?></span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="9" class="text-center py-5">
                            <i class="fas fa-chart-line fa-4x text-muted mb-3"></i>
                            <h5 class="text-muted">No income transactions found</h5>
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</main>

<!-- Vendor JS Files -->
<script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/jquery/jquery-3.6.0.min.js"></script>
<script src="assets/js/main.js"></script>

<!-- Add DataTables for advanced features (optional) -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>

<!-- Chart Script -->
<script>
    // Prepare chart data
    const monthlyData = <?php 
        $months = [];
        $credited = [];
        $debited = [];
        
        $monthly_result = mysqli_query($conn, $monthly_query);
        while ($row = mysqli_fetch_assoc($monthly_result)) {
            $months[] = date('M Y', strtotime($row['month'] . '-01'));
            $credited[] = $row['credited'];
            $debited[] = $row['debited'];
        }
        
        echo json_encode([
            'months' => array_reverse($months),
            'credited' => array_reverse($credited),
            'debited' => array_reverse($debited)
        ]);
    ?>;

    // Create chart
    const ctx = document.getElementById('incomeChart').getContext('2d');
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: monthlyData.months,
            datasets: [{
                label: 'Credited',
                data: monthlyData.credited,
                borderColor: '#10b981',
                backgroundColor: 'rgba(16, 185, 129, 0.1)',
                tension: 0.4,
                fill: true
            }, {
                label: 'Debited',
                data: monthlyData.debited,
                borderColor: '#ef4444',
                backgroundColor: 'rgba(239, 68, 68, 0.1)',
                tension: 0.4,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: true,
                    position: 'top'
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return '₹' + value;
                        }
                    }
                }
            }
        }
    });

    // Export to Excel function
    function exportToExcel() {
        let table = document.getElementById('incomeTable');
        let html = table.outerHTML;
        
        // Create a blob with the HTML content
        let blob = new Blob([html], { type: 'application/vnd.ms-excel' });
        let url = window.URL.createObjectURL(blob);
        let a = document.createElement('a');
        
        a.href = url;
        a.download = 'income_history_<?php echo date('Y-m-d'); ?>.xls';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    }
</script>

<script>
    $(document).ready(function() {
        $('#incomeTable').DataTable({
            pageLength: 25,
            order: [[0, 'desc']],
            language: {
                search: "<i class='fas fa-search'></i>",
                searchPlaceholder: "Search transactions...",
                lengthMenu: "Show _MENU_ entries",
                info: "Showing _START_ to _END_ of _TOTAL_ entries"
            }
        });
    });
</script>

</body>
</html>