<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/currency.php';
require_once '../includes/functions.php';

requireLogin();

// Check if user is admin
$currentUser = getCurrentUser();
if ($currentUser['role'] !== 'admin') {
    header('Location: dashboard.php');
    exit;
}

$db = getDB();

// Get date range parameters
$period = $_GET['period'] ?? '30d';
$startDate = $_GET['start_date'] ?? null;
$endDate = $_GET['end_date'] ?? null;
$gateway = $_GET['gateway'] ?? null;
$currency = $_GET['currency'] ?? null;

// Calculate date range
switch ($period) {
    case '7d':
        $startDate = date('Y-m-d', strtotime('-7 days'));
        break;
    case '30d':
        $startDate = date('Y-m-d', strtotime('-30 days'));
        break;
    case '90d':
        $startDate = date('Y-m-d', strtotime('-90 days'));
        break;
    case '1y':
        $startDate = date('Y-m-d', strtotime('-1 year'));
        break;
    case 'custom':
        // Use provided dates
        break;
    default:
        $startDate = date('Y-m-d', strtotime('-30 days'));
}

$endDate = $endDate ?: date('Y-m-d');

// Build analytics query
$query = "
    SELECT
        DATE_FORMAT(date, '%Y-%m-%d') as date,
        gateway_name,
        currency,
        SUM(total_transactions) as total_transactions,
        SUM(successful_transactions) as successful_transactions,
        SUM(failed_transactions) as failed_transactions,
        SUM(total_amount) as total_amount,
        SUM(refunded_amount) as refunded_amount,
        SUM(net_amount) as net_amount,
        AVG(average_transaction) as average_transaction
    FROM payment_analytics
    WHERE date BETWEEN ? AND ?
";

$params = [$startDate, $endDate];

if ($gateway) {
    $query .= " AND gateway_name = ?";
    $params[] = $gateway;
}

if ($currency) {
    $query .= " AND currency = ?";
    $params[] = $currency;
}

$query .= " GROUP BY date, gateway_name, currency ORDER BY date DESC";

$stmt = $db->prepare($query);
$stmt->execute($params);
$analytics = $stmt->fetchAll();

// Get summary statistics
$summaryQuery = "
    SELECT
        SUM(total_transactions) as total_transactions,
        SUM(successful_transactions) as successful_transactions,
        SUM(failed_transactions) as failed_transactions,
        SUM(total_amount) as total_amount,
        SUM(refunded_amount) as refunded_amount,
        SUM(net_amount) as net_amount,
        AVG(average_transaction) as average_transaction,
        COUNT(DISTINCT DATE(date)) as days_count
    FROM payment_analytics
    WHERE date BETWEEN ? AND ?
";

$summaryParams = [$startDate, $endDate];

if ($gateway) {
    $summaryQuery .= " AND gateway_name = ?";
    $summaryParams[] = $gateway;
}

if ($currency) {
    $summaryQuery .= " AND currency = ?";
    $summaryParams[] = $currency;
}

$stmt = $db->prepare($summaryQuery);
$stmt->execute($summaryParams);
$summary = $stmt->fetch();

// Get gateway breakdown
$gatewayQuery = "
    SELECT
        gateway_name,
        SUM(total_transactions) as transactions,
        SUM(net_amount) as revenue,
        AVG(average_transaction) as avg_transaction
    FROM payment_analytics
    WHERE date BETWEEN ? AND ?
    GROUP BY gateway_name
    ORDER BY revenue DESC
";

$stmt = $db->prepare($gatewayQuery);
$stmt->execute([$startDate, $endDate]);
$gatewayBreakdown = $stmt->fetchAll();

// Get currency breakdown
$currencyQuery = "
    SELECT
        currency,
        SUM(total_transactions) as transactions,
        SUM(net_amount) as revenue
    FROM payment_analytics
    WHERE date BETWEEN ? AND ?
    GROUP BY currency
    ORDER BY revenue DESC
";

$stmt = $db->prepare($currencyQuery);
$stmt->execute([$startDate, $endDate]);
$currencyBreakdown = $stmt->fetchAll();

// Get available gateways and currencies for filters
$availableGateways = $db->query("SELECT DISTINCT gateway_name FROM payment_analytics ORDER BY gateway_name")->fetchAll(PDO::FETCH_COLUMN);
$availableCurrencies = $db->query("SELECT DISTINCT currency FROM payment_analytics ORDER BY currency")->fetchAll(PDO::FETCH_COLUMN);

$page_title = 'Payment Analytics';
include 'includes/admin_header.php';
?>

<div class="analytics-section">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Payment Analytics</h2>
        <div class="date-range-info">
            <small class="text-muted">
                Period: <?php echo date('M j, Y', strtotime($startDate)); ?> - <?php echo date('M j, Y', strtotime($endDate)); ?>
            </small>
        </div>
    </div>

    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-2">
                    <label for="period" class="form-label">Period</label>
                    <select class="form-select" id="period" name="period" onchange="toggleCustomDates()">
                        <option value="7d" <?php echo $period === '7d' ? 'selected' : ''; ?>>Last 7 days</option>
                        <option value="30d" <?php echo $period === '30d' ? 'selected' : ''; ?>>Last 30 days</option>
                        <option value="90d" <?php echo $period === '90d' ? 'selected' : ''; ?>>Last 90 days</option>
                        <option value="1y" <?php echo $period === '1y' ? 'selected' : ''; ?>>Last year</option>
                        <option value="custom" <?php echo $period === 'custom' ? 'selected' : ''; ?>>Custom range</option>
                    </select>
                </div>
                <div class="col-md-2 custom-dates" style="display: <?php echo $period === 'custom' ? 'block' : 'none'; ?>">
                    <label for="start_date" class="form-label">Start Date</label>
                    <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo $startDate; ?>">
                </div>
                <div class="col-md-2 custom-dates" style="display: <?php echo $period === 'custom' ? 'block' : 'none'; ?>">
                    <label for="end_date" class="form-label">End Date</label>
                    <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo $endDate; ?>">
                </div>
                <div class="col-md-2">
                    <label for="gateway" class="form-label">Gateway</label>
                    <select class="form-select" id="gateway" name="gateway">
                        <option value="">All Gateways</option>
                        <?php foreach ($availableGateways as $gw): ?>
                            <option value="<?php echo htmlspecialchars($gw); ?>" <?php echo $gateway === $gw ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars(ucfirst($gw)); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <label for="currency" class="form-label">Currency</label>
                    <select class="form-select" id="currency" name="currency">
                        <option value="">All Currencies</option>
                        <?php foreach ($availableCurrencies as $curr): ?>
                            <option value="<?php echo htmlspecialchars($curr); ?>" <?php echo $currency === $curr ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($curr); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary w-100">Apply Filters</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="summary-card">
                <div class="card-icon revenue">
                    <i class="fas fa-dollar-sign"></i>
                </div>
                <div class="card-content">
                    <h3><?php echo formatCurrency($summary['net_amount'] ?? 0); ?></h3>
                    <p>Total Revenue</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="summary-card">
                <div class="card-icon transactions">
                    <i class="fas fa-credit-card"></i>
                </div>
                <div class="card-content">
                    <h3><?php echo number_format($summary['successful_transactions'] ?? 0); ?></h3>
                    <p>Successful Transactions</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="summary-card">
                <div class="card-icon average">
                    <i class="fas fa-chart-line"></i>
                </div>
                <div class="card-content">
                    <h3><?php echo formatCurrency($summary['average_transaction'] ?? 0); ?></h3>
                    <p>Average Transaction</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="summary-card">
                <div class="card-icon conversion">
                    <i class="fas fa-percentage"></i>
                </div>
                <div class="card-content">
                    <h3>
                        <?php
                        $total = $summary['total_transactions'] ?? 0;
                        $successful = $summary['successful_transactions'] ?? 0;
                        $rate = $total > 0 ? ($successful / $total) * 100 : 0;
                        echo number_format($rate, 1) . '%';
                        ?>
                    </h3>
                    <p>Success Rate</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Row -->
    <div class="row mb-4">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Revenue Trend</h5>
                </div>
                <div class="card-body">
                    <canvas id="revenueChart" width="400" height="200"></canvas>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Gateway Performance</h5>
                </div>
                <div class="card-body">
                    <canvas id="gatewayChart" width="200" height="200"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Breakdown Tables -->
    <div class="row">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Revenue by Gateway</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Gateway</th>
                                    <th>Transactions</th>
                                    <th>Revenue</th>
                                    <th>Avg Transaction</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($gatewayBreakdown as $gw): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars(ucfirst($gw['gateway_name'])); ?></td>
                                        <td><?php echo number_format($gw['transactions']); ?></td>
                                        <td><?php echo formatCurrency($gw['revenue']); ?></td>
                                        <td><?php echo formatCurrency($gw['avg_transaction']); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Revenue by Currency</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Currency</th>
                                    <th>Transactions</th>
                                    <th>Revenue</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($currencyBreakdown as $curr): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($curr['currency']); ?></td>
                                        <td><?php echo number_format($curr['transactions']); ?></td>
                                        <td><?php echo formatCurrency($curr['revenue'], $curr['currency']); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Detailed Analytics Table -->
    <div class="card mt-4">
        <div class="card-header">
            <h5 class="mb-0">Detailed Analytics</h5>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Gateway</th>
                            <th>Currency</th>
                            <th>Transactions</th>
                            <th>Successful</th>
                            <th>Failed</th>
                            <th>Revenue</th>
                            <th>Refunds</th>
                            <th>Net Revenue</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($analytics)): ?>
                            <tr>
                                <td colspan="9" class="text-center py-4">
                                    <i class="fas fa-chart-bar fa-3x text-muted mb-3"></i>
                                    <p class="text-muted">No analytics data available for the selected period.</p>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($analytics as $row): ?>
                                <tr>
                                    <td><?php echo date('M j, Y', strtotime($row['date'])); ?></td>
                                    <td><?php echo htmlspecialchars(ucfirst($row['gateway_name'] ?: 'N/A')); ?></td>
                                    <td><?php echo htmlspecialchars($row['currency']); ?></td>
                                    <td><?php echo number_format($row['total_transactions']); ?></td>
                                    <td><?php echo number_format($row['successful_transactions']); ?></td>
                                    <td><?php echo number_format($row['failed_transactions']); ?></td>
                                    <td><?php echo formatCurrency($row['total_amount'], $row['currency']); ?></td>
                                    <td><?php echo formatCurrency($row['refunded_amount'], $row['currency']); ?></td>
                                    <td><?php echo formatCurrency($row['net_amount'], $row['currency']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
function toggleCustomDates() {
    const period = document.getElementById('period').value;
    const customDates = document.querySelectorAll('.custom-dates');
    customDates.forEach(el => {
        el.style.display = period === 'custom' ? 'block' : 'none';
    });
}

// Prepare data for charts
<?php
$chartLabels = [];
$chartRevenue = [];
$chartTransactions = [];

foreach (array_reverse($analytics) as $row) {
    $chartLabels[] = date('M j', strtotime($row['date']));
    $chartRevenue[] = (float)$row['net_amount'];
    $chartTransactions[] = (int)$row['successful_transactions'];
}

$gatewayLabels = [];
$gatewayData = [];
foreach ($gatewayBreakdown as $gw) {
    $gatewayLabels[] = ucfirst($gw['gateway_name']);
    $gatewayData[] = (float)$gw['revenue'];
}
?>

// Revenue Chart
const revenueCtx = document.getElementById('revenueChart').getContext('2d');
new Chart(revenueCtx, {
    type: 'line',
    data: {
        labels: <?php echo json_encode($chartLabels); ?>,
        datasets: [{
            label: 'Net Revenue',
            data: <?php echo json_encode($chartRevenue); ?>,
            borderColor: '#2563eb',
            backgroundColor: 'rgba(37, 99, 235, 0.1)',
            tension: 0.4
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: {
                display: false
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    callback: function(value) {
                        return '$' + value.toLocaleString();
                    }
                }
            }
        }
    }
});

// Gateway Performance Chart
const gatewayCtx = document.getElementById('gatewayChart').getContext('2d');
new Chart(gatewayCtx, {
    type: 'doughnut',
    data: {
        labels: <?php echo json_encode($gatewayLabels); ?>,
        datasets: [{
            data: <?php echo json_encode($gatewayData); ?>,
            backgroundColor: [
                '#2563eb',
                '#10b981',
                '#f59e0b',
                '#ef4444',
                '#8b5cf6'
            ]
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: {
                position: 'bottom'
            }
        }
    }
});
</script>

<style>
.analytics-section {
    max-width: 1400px;
}

.summary-card {
    background: white;
    border-radius: 0.75rem;
    padding: 1.5rem;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    gap: 1rem;
    height: 100%;
}

.card-icon {
    width: 3rem;
    height: 3rem;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.25rem;
}

.card-icon.revenue {
    background-color: #dbeafe;
    color: #2563eb;
}

.card-icon.transactions {
    background-color: #d1fae5;
    color: #10b981;
}

.card-icon.average {
    background-color: #fef3c7;
    color: #f59e0b;
}

.card-icon.conversion {
    background-color: #fce7f3;
    color: #ec4899;
}

.card-content h3 {
    font-size: 1.5rem;
    font-weight: 700;
    color: #1f2937;
    margin: 0;
}

.card-content p {
    color: #6b7280;
    font-size: 0.875rem;
    margin: 0.25rem 0 0 0;
}

.card {
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    border: none;
    border-radius: 0.75rem;
}

.card-header {
    background-color: #f8f9fa;
    border-bottom: 1px solid #e9ecef;
    padding: 1rem 1.5rem;
    border-radius: 0.75rem 0.75rem 0 0 !important;
}

.card-header h5 {
    color: #1f2937;
    margin: 0;
}

.card-body {
    padding: 1.5rem;
}

.table {
    margin-bottom: 0;
}

.table th {
    background-color: #f8f9fa;
    font-weight: 600;
    color: #374151;
    border-top: none;
    padding: 1rem;
}

.table td {
    padding: 1rem;
    vertical-align: middle;
}

.btn {
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 0.375rem;
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
    text-decoration: none;
    display: inline-block;
}

.btn-primary {
    background-color: #2563eb;
    color: white;
}

.btn-primary:hover {
    background-color: #1d4ed8;
}

.form-label {
    font-weight: 600;
    color: #374151;
    margin-bottom: 0.5rem;
}

.form-select,
.form-control {
    padding: 0.5rem;
    border: 1px solid #d1d5db;
    border-radius: 0.375rem;
    font-size: 0.875rem;
}

.date-range-info {
    background-color: #f8f9fa;
    padding: 0.5rem 1rem;
    border-radius: 0.375rem;
}

@media (max-width: 768px) {
    .row {
        flex-direction: column;
    }

    .col-md-3,
    .col-md-8,
    .col-md-4,
    .col-md-6 {
        margin-bottom: 1rem;
    }

    .summary-card {
        flex-direction: column;
        text-align: center;
    }
}
</style>

<?php include 'includes/admin_footer.php'; ?>