<?php
require('config.php');

// Check flag to determine filtering method
$flag = isset($_GET['flag']) ? $_GET['flag'] : 'specific';

// Allowed transaction types
$allowedTypes = ["Staff Credit", "Delegate Credit", "Excom Credit"];
$placeholders = implode(",", array_fill(0, count($allowedTypes), "?"));
$params = $allowedTypes;
$typeStr = str_repeat("s", count($allowedTypes));

// Construct SQL query
$query = "SELECT trans_id, trans_amount, takenBy, DATE(trans_date) AS trans_date, trans_type, paymentMethod FROM transactions";

if ($flag === 'specific' && isset($_GET['dateRange'])) {
    $dateRange = explode(" to ", $_GET['dateRange']);
    if (count($dateRange) === 2) {
        $startDate = trim($dateRange[0]);
        $endDate = trim($dateRange[1]);
        $query .= " WHERE trans_type IN ($placeholders) AND DATE(trans_date) BETWEEN ? AND ?";
        array_push($params, $startDate, $endDate);
        $typeStr .= "ss";
    }
} elseif ($flag === 'all') {
    // Extract all transactions without filtering
    $params = [];
    $typeStr = "";
} else {
    $query .= " WHERE trans_type IN ($placeholders)";
}

$query .= " ORDER BY trans_date ASC";

$stmt = $connect->prepare($query);
if (!$stmt) {
    echo json_encode(["error" => true, "message" => "Failed to prepare statement."]);
    exit;
}

// Bind parameters if needed
if (!empty($params)) {
    $stmt->bind_param($typeStr, ...$params);
}

$stmt->execute();
$result = $stmt->get_result();

// Check if results exist
$rows = $result->fetch_all(MYSQLI_ASSOC);
if ($flag === 'specific' && !empty($rows)) {
    $startDate = $rows[0]['trans_date'];
    $endDate = end($rows)['trans_date'];
}

// Create CSV file
$tempFile = sys_get_temp_dir() . "/transactions_" . uniqid() . ".csv";
$csvFile = fopen($tempFile, 'w');

// Write header row
$header = ["trans_id", "trans_amount", "takenBy", "trans_date", "trans_type", "paymentMethod"];
fputcsv($csvFile, $header);

// Write transaction data
foreach ($rows as $row) {
    fputcsv($csvFile, $row);
}

fclose($csvFile);

// Serve the CSV file for download
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="transactions.csv"');
header('Content-Length: ' . filesize($tempFile));
readfile($tempFile);

// Cleanup
unlink($tempFile);
exit;
?>
