<?php
require_once 'config/database.php';
secureSessionStart();
requireLogin();

$conn = getConnection();

// Get filters from query string
$user_id_filter = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$income_type_filter = isset($_GET['income_type']) ? sanitize($conn, $_GET['income_type']) : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$credit_debit_filter = isset($_GET['credit_debit']) ? intval($_GET['credit_debit']) : -1;
$search = isset($_GET['search']) ? sanitize($conn, $_GET['search']) : '';

// Build WHERE clause
$where = [];

if ($user_id_filter > 0) {
    $where[] = "ih.user_id = $user_id_filter";
}

if ($income_type_filter) {
    $where[] = "ih.income_type = '$income_type_filter'";
}

if ($credit_debit_filter >= 0) {
    $where[] = "ih.credit_debit = $credit_debit_filter";
}

if ($date_from) {
    $where[] = "DATE(ih.created_at) >= '$date_from'";
}

if ($date_to) {
    $where[] = "DATE(ih.created_at) <= '$date_to'";
}

if ($search) {
    $where[] = "(ih.description LIKE '%$search%' OR ih.transaction_id LIKE '%$search%')";
}

$where_clause = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";

// Get all data for export
$query = "SELECT ih.*, 
                 u.name as user_name, 
                 u.mobile as user_mobile,
                 fu.name as from_user_name,
                 tu.name as to_user_name
          FROM income_history ih
          LEFT JOIN users u ON ih.user_id = u.user_id
          LEFT JOIN users fu ON ih.from_user_id = fu.user_id
          LEFT JOIN users tu ON ih.to_user_id = tu.user_id
          $where_clause
          ORDER BY ih.id DESC";

$result = mysqli_query($conn, $query);

// Set headers for CSV download
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="income_history_' . date('Y-m-d') . '.csv"');

// Create output stream
$output = fopen('php://output', 'w');

// Add CSV headers
fputcsv($output, [
    'ID',
    'Date',
    'Time',
    'User ID',
    'User Name',
    'Mobile',
    'Type',
    'Credit/Debit',
    'Amount',
    'Description',
    'Transaction ID',
    'From User',
    'To User',
    'Level',
    'Source Type',
    'Package ID',
    'PIN Value'
]);

// Add data rows
while ($row = mysqli_fetch_assoc($result)) {
    fputcsv($output, [
        $row['id'],
        date('Y-m-d', strtotime($row['created_at'])),
        date('H:i:s', strtotime($row['created_at'])),
        $row['user_id'],
        $row['user_name'],
        $row['user_mobile'],
        $row['income_type'],
        $row['credit_debit'] == 1 ? 'Credit' : 'Debit',
        $row['amount'],
        $row['description'],
        $row['transaction_id'],
        $row['from_user_id'] . ' (' . $row['from_user_name'] . ')' ?: 'N/A',
        $row['to_user_id'] . ' (' . $row['to_user_name'] . ')' ?: 'N/A',
        $row['level'] ?: 'N/A',
        $row['source_type'] ?: 'N/A',
        $row['package_id'] ?: 'N/A',
        $row['pin_value'] ?: 'N/A'
    ]);
}

fclose($output);
mysqli_close($conn);
exit();
?>