<?php
require_once(__DIR__ . '/../config/config.php');
require_once(__DIR__ . '/../classes/Database.php');
require_once(__DIR__ . '/../classes/Payment.php');

session_start();

if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

$db = Database::getInstance();
$payment = new Payment();

// Get statistics
$totalRevenue = $db->fetch('SELECT SUM(amount) AS total FROM payment_orders WHERE status = "completed"')['total'] ?? 0;
$totalOrders = $db->fetch('SELECT COUNT(*) AS total FROM payment_orders')['total'] ?? 0;
$pendingOrders = $db->fetch('SELECT COUNT(*) AS total FROM payment_orders WHERE status = "pending"')['total'] ?? 0;

// Get recent payments
$recentPayments = $db->fetchAll(
    'SELECT po.*, u.name, u.email FROM payment_orders po 
     JOIN users u ON po.user_id = u.id 
     ORDER BY po.created_at DESC LIMIT 20'
);

// Handle payment approval
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'approve_payment') {
    $orderId = $_POST['order_id'] ?? null;
    
    if ($orderId) {
        $result = $payment->confirmPayment($orderId, 'MANUAL-APPROVAL-' . time(), 'manual_approval');
        $_SESSION['message'] = $result['status'] ? 'Payment approved successfully' : $result['message'];
    }
    
    header('Location: ' . $_SERVER['REQUEST_URI']);
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Management - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            background: #f8f9fa;
            padding: 20px;
        }

        .page-header {
            margin-bottom: 30px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            border-left: 4px solid #667eea;
        }

        .stat-card h6 {
            color: #666;
            margin: 0 0 10px 0;
            font-weight: 600;
        }

        .stat-card .amount {
            font-size: 32px;
            font-weight: 700;
            color: #333;
            margin: 0;
        }

        .table-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            overflow: hidden;
        }

        .table {
            margin: 0;
        }

        .table thead {
            background: #f8f9fa;
            font-weight: 600;
            color: #666;
        }

        .table td {
            vertical-align: middle;
            padding: 15px;
            border-color: #e8eaed;
        }

        .status-badge {
            display: inline-block;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }

        .status-pending {
            background: #fff3cd;
            color: #856404;
        }

        .status-completed {
            background: #d4edda;
            color: #155724;
        }

        .status-failed {
            background: #f8d7da;
            color: #721c24;
        }

        .action-btn {
            padding: 6px 12px;
            font-size: 12px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 600;
        }

        .btn-approve {
            background: #10b981;
            color: white;
        }

        .btn-approve:hover {
            background: #059669;
        }

        .btn-view {
            background: #667eea;
            color: white;
        }

        .btn-view:hover {
            background: #5568d3;
        }

        .alert-message {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="page-header">
            <h1><i class="fas fa-credit-card"></i> Payment Management</h1>
            <p class="text-muted">Manage user payments and transactions</p>
        </div>

        <?php if (isset($_SESSION['message'])): ?>
        <div class="alert alert-success alert-message alert-dismissible fade show">
            <?php echo htmlspecialchars($_SESSION['message']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php unset($_SESSION['message']); endif; ?>

        <!-- Statistics -->
        <div class="stats-grid">
            <div class="stat-card">
                <h6>Total Revenue</h6>
                <p class="amount">₹<?php echo number_format($totalRevenue, 2); ?></p>
            </div>
            <div class="stat-card">
                <h6>Total Orders</h6>
                <p class="amount"><?php echo $totalOrders; ?></p>
            </div>
            <div class="stat-card">
                <h6>Pending Orders</h6>
                <p class="amount"><?php echo $pendingOrders; ?></p>
            </div>
        </div>

        <!-- Recent Payments Table -->
        <div class="table-container">
            <div style="padding: 20px; border-bottom: 1px solid #e8eaed;">
                <h5 style="margin: 0;">Recent Payments</h5>
            </div>
            <table class="table">
                <thead>
                    <tr>
                        <th>Order ID</th>
                        <th>User</th>
                        <th>Package</th>
                        <th>Amount</th>
                        <th>Method</th>
                        <th>Status</th>
                        <th>Date</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($recentPayments) > 0): ?>
                        <?php foreach ($recentPayments as $payment): ?>
                        <tr>
                            <td>
                                <code><?php echo htmlspecialchars(substr($payment['order_id'], 0, 12)); ?>...</code>
                            </td>
                            <td>
                                <strong><?php echo htmlspecialchars($payment['name']); ?></strong><br>
                                <small class="text-muted"><?php echo htmlspecialchars($payment['email']); ?></small>
                            </td>
                            <td><?php echo htmlspecialchars($payment['package_name']); ?></td>
                            <td><strong>₹<?php echo number_format($payment['amount'], 2); ?></strong></td>
                            <td><?php echo ucfirst(str_replace('_', ' ', htmlspecialchars($payment['payment_method'] ?? 'N/A'))); ?></td>
                            <td>
                                <span class="status-badge status-<?php echo htmlspecialchars($payment['status']); ?>">
                                    <?php echo ucfirst(htmlspecialchars($payment['status'])); ?>
                                </span>
                            </td>
                            <td>
                                <small><?php echo date('d M Y H:i', strtotime($payment['created_at'])); ?></small>
                            </td>
                            <td>
                                <?php if ($payment['status'] === 'pending'): ?>
                                <form method="POST" style="display: inline;">
                                    <input type="hidden" name="action" value="approve_payment">
                                    <input type="hidden" name="order_id" value="<?php echo htmlspecialchars($payment['order_id']); ?>">
                                    <button type="submit" class="action-btn btn-approve" onclick="return confirm('Approve this payment?')">
                                        <i class="fas fa-check"></i> Approve
                                    </button>
                                </form>
                                <?php else: ?>
                                <button class="action-btn btn-view" disabled>
                                    <i class="fas fa-eye"></i> View
                                </button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                    <tr>
                        <td colspan="8" class="text-center text-muted py-4">
                            No payments found
                        </td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
