<?php
session_start();
require_once '../config.php';
use App\classes\AdminAuth;

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=verified_payments_' . date('Ymd_His') . '.csv');

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    http_response_code(401);
    echo "Unauthorized";
    exit;
}

$network = isset($_GET['network']) ? trim($_GET['network']) : '';
$date_from = isset($_GET['date_from']) ? trim($_GET['date_from']) : '';
$date_to = isset($_GET['date_to']) ? trim($_GET['date_to']) : '';
$time_from = isset($_GET['time_from']) ? trim($_GET['time_from']) : '';
$time_to = isset($_GET['time_to']) ? trim($_GET['time_to']) : '';

$where = [];
$params = [];
$types = '';

if ($network !== '') {
    $where[] = 'v.network_type = ?';
    $params[] = $network;
    $types .= 's';
}

// Detect timestamp column for verified table
$tsCol = 'payment_verified_at';
$chk = $conn->query("SHOW COLUMNS FROM verified_databundle_orders LIKE 'payment_verified_at'");
if (!$chk || $chk->num_rows === 0) {
    $tsCol = 'created_at';
}
if ($chk) { $chk->close(); }

// Build datetime filters
if ($date_from !== '' && $time_from !== '') {
    $where[] = "v.`$tsCol` >= ?";
    $params[] = $date_from . ' ' . $time_from;
    $types .= 's';
} elseif ($date_from !== '') {
    $where[] = "DATE(v.`$tsCol`) >= ?";
    $params[] = $date_from;
    $types .= 's';
}

if ($date_to !== '' && $time_to !== '') {
    $where[] = "v.`$tsCol` <= ?";
    $params[] = $date_to . ' ' . $time_to;
    $types .= 's';
} elseif ($date_to !== '') {
    $where[] = "DATE(v.`$tsCol`) <= ?";
    $params[] = $date_to;
    $types .= 's';
}

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$sql = "SELECT v.id, v.momo_name, v.momo_number, v.package, v.package_mb, v.amount_paid, v.reference, v.megabytes, v.received, v.network_type, v.external_transaction_id, v.$tsCol
        FROM verified_databundle_orders v $whereSql ORDER BY v.$tsCol DESC";

$stmt = $conn->prepare($sql);
if ($types !== '') { $stmt->bind_param($types, ...$params); }
$stmt->execute();
$res = $stmt->get_result();

$out = fopen('php://output', 'w');
fputcsv($out, ['ID','Name','MoMo Number','Package','Package MB','Amount Paid','Reference','Megabytes','Received','Network','External Txn ID','Verified At']);
while ($row = $res->fetch_assoc()) {
    fputcsv($out, [
        $row['id'], $row['momo_name'], $row['momo_number'], $row['package'], $row['package_mb'],
        $row['amount_paid'], $row['reference'], $row['megabytes'], $row['received'], $row['network_type'],
        $row['external_transaction_id'], $row[$tsCol]
    ]);
}
fclose($out);
exit;
?>


