<?php
require 'stripe/init.php';

\Stripe\Stripe::setApiKey('sk_live_MLErt6vGShAsg5qrtwDVvvzq00TSQmVem4');

// Filters
$startDate = isset($_GET['from']) ? strtotime($_GET['from'] . ' 00:00:00') : strtotime('-30 days');
$endDate = isset($_GET['to']) ? strtotime($_GET['to'] . ' 23:59:59') : time();
$statusFilter = isset($_GET['status']) ? strtolower($_GET['status']) : 'all';
$descFilter = isset($_GET['desc']) ? $_GET['desc'] : 'all';
$exportCSV = isset($_GET['export']) && $_GET['export'] === '1';

// Fetch Stripe charges with refunds expanded
$charges = \Stripe\Charge::all([
    'limit' => 100,
    'created' => [
        'gte' => $startDate,
        'lte' => $endDate,
    ],
    'expand' => ['data.refunds'],
]);

$filteredData = [];

foreach ($charges->data as $charge) {
    $status = strtolower($charge->status);
    $description = $charge->description ?? 'N/A';

    // Apply status filter
    if ($statusFilter !== 'all' && $status !== $statusFilter) {
        continue;
    }

    // Apply description filter
    $matchDescription = false;
    switch ($descFilter) {
        case '2025-women':
            $matchDescription = stripos($description, "2025 Snipe Women's World Championship Entry Fee") !== false;
            break;
        case '2025-master':
            $matchDescription = stripos($description, "2025 Snipe Master World Championship Entry Fee") !== false;
            break;
        case 'others':
            $matchDescription =
                stripos($description, "2025 Snipe Women's World Championship Entry Fee") === false &&
                stripos($description, "2025 Snipe Master World Championship Entry Fee") === false;
            break;
        default:
            $matchDescription = true;
    }

    if (!$matchDescription) {
        continue;
    }

    $amount = $charge->amount / 100;
    $currency = strtoupper($charge->currency);
    $date = date('Y-m-d H:i:s', $charge->created);
    $clientName = $charge->billing_details->name ?? 'N/A';

    if (!$clientName && $charge->customer) {
        try {
            $customer = \Stripe\Customer::retrieve($charge->customer);
            $clientName = $customer->name ?? 'N/A';
        } catch (Exception $e) {
            $clientName = 'N/A';
        }
    }

    try {
        $balanceTx = \Stripe\BalanceTransaction::retrieve($charge->balance_transaction);
        $stripeFee = $balanceTx->fee / 100;
        $netReceived = $balanceTx->net / 100;
    } catch (Exception $e) {
        $stripeFee = 'Error';
        $netReceived = 'Error';
    }

    // Calculate refund amount
    $refundAmount = 0;
    if (!empty($charge->refunds->data)) {
        foreach ($charge->refunds->data as $refund) {
            $refundAmount += $refund->amount / 100;
        }
    }

    $filteredData[] = [
        'id' => $charge->id,
        'description' => $description,
        'date' => $date,
        'status' => ucfirst($status),
        'client_name' => $clientName,
        'currency' => $currency,
        'amount' => $amount,
        'stripe_fee' => $stripeFee,
        'net_received' => $netReceived,
        'refund' => $refundAmount,
    ];
}

// Export to CSV
if ($exportCSV) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="stripe_transactions.csv"');
    $output = fopen('php://output', 'w');
    fputcsv($output, [
        'Charge ID', 'Description', 'Date', 'Status',
        'Client Name', 'Currency', 'Amount', 'Stripe Fee',
        'Net Received', 'Refund'
    ]);
    foreach ($filteredData as $row) {
        fputcsv($output, [
            $row['id'], $row['description'], $row['date'], $row['status'],
            $row['client_name'], $row['currency'], $row['amount'],
            $row['stripe_fee'], $row['net_received'], $row['refund']
        ]);
    }
    fclose($output);
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Stripe Transactions</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container mt-5">
    <h2 class="mb-4">Stripe Transactions Viewer</h2>

    <!-- Filter Form -->
    <form method="GET" class="row g-3 mb-4">
        <div class="col-md-2">
            <label class="form-label">From</label>
            <input type="date" name="from" class="form-control" value="<?= date('Y-m-d', $startDate) ?>" required>
        </div>
        <div class="col-md-2">
            <label class="form-label">To</label>
            <input type="date" name="to" class="form-control" value="<?= date('Y-m-d', $endDate) ?>" required>
        </div>
        <div class="col-md-2">
            <label class="form-label">Status</label>
            <select name="status" class="form-select">
                <option value="all" <?= $statusFilter == 'all' ? 'selected' : '' ?>>All</option>
                <option value="succeeded" <?= $statusFilter == 'succeeded' ? 'selected' : '' ?>>Succeeded</option>
                <option value="failed" <?= $statusFilter == 'failed' ? 'selected' : '' ?>>Failed</option>
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label">Event</label>
            <select name="desc" class="form-select">
                <option value="all" <?= $descFilter == 'all' ? 'selected' : '' ?>>All</option>
                <option value="2025-women" <?= $descFilter == '2025-women' ? 'selected' : '' ?>>2025 Snipe Women's</option>
                <option value="2025-master" <?= $descFilter == '2025-master' ? 'selected' : '' ?>>2025 Snipe Master</option>
                <option value="others" <?= $descFilter == 'others' ? 'selected' : '' ?>>Others</option>
            </select>
        </div>
        <div class="col-md-3 d-flex align-items-end">
            <button type="submit" class="btn btn-primary me-2">Filter</button>
            <button type="submit" name="export" value="1" class="btn btn-success">Export CSV</button>
        </div>
    </form>

    <!-- Table -->
    <div class="table-responsive">
        <table class="table table-bordered table-striped table-hover">
            <thead class="table-dark">
                <tr>
                    <th>Charge ID</th>
                    <th>Description</th>
                    <th>Date</th>
                    <th>Status</th>
                    <th>Client Name</th>
                    <th>Currency</th>
                    <th>Amount</th>
                    <th>Stripe Fee</th>
                    <th>Net Received</th>
                    <th>Refund</th>
                </tr>
            </thead>
<tbody>
    <?php
    $totalRefund = 0;
    foreach ($filteredData as $row):
        $totalRefund += $row['refund'];
        $refundType = '';
        if ($row['refund'] > 0) {
            $refundType = $row['refund'] == $row['amount'] ? 'Full' : 'Partial';
            $row['status']="Refund";
        }
    ?>
        <tr>
            <td><?= htmlspecialchars($row['id']) ?></td>
            <td><?= htmlspecialchars($row['description']) ?></td>
            <td><?= $row['date'] ?></td>
            <td>
                <span class="badge bg-<?= $row['status'] == 'Succeeded' ? 'success' : 'danger' ?>">
                    <?= $row['status'] ?>
                </span>
            </td>
            <td><?= htmlspecialchars($row['client_name']) ?></td>
            <td><?= $row['currency'] ?></td>
            <td><?= number_format($row['amount'], 2) ?></td>
            <td><?= is_numeric($row['stripe_fee']) ? number_format($row['stripe_fee'], 2) : $row['stripe_fee'] ?></td>
            <td><?= is_numeric($row['net_received']) ? number_format($row['net_received'], 2) : $row['net_received'] ?></td>
            <td><?= number_format($row['refund'], 2) ?><?= $refundType ? " <small class='text-muted'>($refundType)</small>" : '' ?></td>
        </tr>
    <?php endforeach; ?>

    <?php if (count($filteredData)): ?>
        <tr class="table-dark fw-bold">
            <td colspan="9" class="text-end">Total Refund</td>
            <td><?= number_format($totalRefund, 2) ?></td>
        </tr>
    <?php else: ?>
        <tr><td colspan="10" class="text-center text-muted">No transactions found.</td></tr>
    <?php endif; ?>
</tbody>

        </table>
    </div>
</div>
</body>
</html>
