<?php
// admin/accounts/export-transactions.php
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!isAdmin()) {
    exit('Unauthorized');
}

$type_filter = isset($_GET['type']) ? $_GET['type'] : 'all';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : date('Y-m-01');
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : date('Y-m-d');

// Get transactions (same logic as transactions.php)
$transactions = [];

// Income
$stmt = $pdo->prepare("SELECT 'income' as source, income_no as reference_no, customer_name as party_name, amount, payment_method, payment_date as transaction_date, note FROM income WHERE DATE(payment_date) BETWEEN ? AND ?");
$stmt->execute([$date_from, $date_to]);
$income = $stmt->fetchAll();
foreach ($income as $row) {
    $row['type'] = 'income';
    $transactions[] = $row;
}

// Expenses
$stmt = $pdo->prepare("SELECT 'expense' as source, expense_no as reference_no, category as party_name, amount, payment_method, expense_date as transaction_date, note FROM expenses WHERE DATE(expense_date) BETWEEN ? AND ?");
$stmt->execute([$date_from, $date_to]);
$expenses = $stmt->fetchAll();
foreach ($expenses as $row) {
    $row['type'] = 'expense';
    $transactions[] = $row;
}

// PO Payments
$stmt = $pdo->prepare("SELECT 'po_payment' as source, pp.payment_no as reference_no, v.name as party_name, pp.amount, pp.payment_method, pp.payment_date as transaction_date, pp.note FROM po_payments pp LEFT JOIN vendors v ON pp.vendor_id = v.id WHERE DATE(pp.payment_date) BETWEEN ? AND ?");
$stmt->execute([$date_from, $date_to]);
$po_payments = $stmt->fetchAll();
foreach ($po_payments as $row) {
    $row['type'] = 'po_payment';
    $transactions[] = $row;
}

// Sort
usort($transactions, function($a, $b) {
    return strtotime($b['transaction_date']) - strtotime($a['transaction_date']);
});

// Filter by type
if ($type_filter != 'all') {
    $transactions = array_filter($transactions, function($t) use ($type_filter) {
        return $t['type'] == $type_filter;
    });
}

// Create CSV
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="transactions_' . date('Y-m-d') . '.csv"');

$output = fopen('php://output', 'w');
fputcsv($output, ['Date', 'Reference', 'Type', 'Party', 'Method', 'Amount', 'Note']);

foreach ($transactions as $t) {
    fputcsv($output, [
        date('d M Y', strtotime($t['transaction_date'])),
        $t['reference_no'],
        ucfirst(str_replace('_', ' ', $t['type'])),
        $t['party_name'] ?? 'N/A',
        $t['payment_method'] ?? 'N/A',
        ($t['type'] == 'income' ? '+' : '-') . $t['amount'],
        $t['note'] ?? ''
    ]);
}

fclose($output);
exit;
?>