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

requireLogin();

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

$success = '';
$error = '';

$db = getDB();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['process_refund'])) {
        // Process refund
        $transactionId = trim($_POST['transaction_id']);
        $refundAmount = (float)$_POST['refund_amount'];
        $reason = trim($_POST['reason']);
        $notifyUser = isset($_POST['notify_user']);

        try {
            // Get transaction details
            $stmt = $db->prepare("
                SELECT pt.*, u.email, u.username, up.first_name, up.last_name,
                       c.title as course_title, e.title as exam_title
                FROM payment_transactions pt
                JOIN users u ON pt.user_id = u.id
                LEFT JOIN user_profiles up ON u.id = up.user_id
                LEFT JOIN courses c ON pt.item_type = 'course' AND pt.item_id = c.id
                LEFT JOIN exams e ON pt.item_type = 'exam' AND pt.item_id = e.id
                WHERE pt.transaction_id = ? OR pt.reference_number = ?
            ");
            $stmt->execute([$transactionId, $transactionId]);
            $transaction = $stmt->fetch();

            if (!$transaction) {
                throw new Exception('Transaction not found');
            }

            if ($transaction['status'] !== 'completed') {
                throw new Exception('Only completed transactions can be refunded');
            }

            if ($refundAmount <= 0 || $refundAmount > $transaction['final_amount']) {
                throw new Exception('Invalid refund amount');
            }

            // Check if refund already exists
            $stmt = $db->prepare("SELECT id FROM payment_refunds WHERE transaction_id = ? AND status IN ('pending', 'processing', 'completed')");
            $stmt->execute([$transaction['id']]);
            if ($stmt->fetch()) {
                throw new Exception('A refund is already pending or processed for this transaction');
            }

            // Generate refund reference
            $refundReference = 'REF_' . time() . '_' . rand(1000, 9999);

            // Create refund record
            $stmt = $db->prepare("
                INSERT INTO payment_refunds
                (transaction_id, refund_transaction_id, reference_number, amount, reason, status, processed_by, created_at)
                VALUES (?, NULL, ?, ?, ?, 'pending', ?, NOW())
            ");
            $stmt->execute([$transaction['id'], $refundReference, $refundAmount, $reason, $currentUser['id']]);

            $refundId = $db->lastInsertId();

            // Process refund through payment gateway
            $gateway = getPaymentGateway($transaction['gateway_name'], $transaction['gateway_type']);

            // For now, we'll mark as completed (actual gateway integration would be more complex)
            $stmt = $db->prepare("
                UPDATE payment_refunds
                SET status = 'completed', processed_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$refundId]);

            // Update transaction status
            $stmt = $db->prepare("
                UPDATE payment_transactions
                SET status = 'refunded', updated_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$transaction['id']]);

            // Log refund
            $stmt = $db->prepare("
                INSERT INTO payment_logs (transaction_id, action, level, message, context, created_at)
                VALUES (?, 'refund_processed', 'info', ?, ?, NOW())
            ");
            $stmt->execute([
                $transaction['id'],
                "Refund processed: {$refundAmount} {$transaction['currency']}",
                json_encode(['refund_id' => $refundId, 'reason' => $reason])
            ]);

            // Send refund processed notification
            sendPaymentNotification('refund_processed', $refundId);

            $success = 'Refund processed successfully!';

        } catch (Exception $e) {
            $error = 'Error processing refund: ' . $e->getMessage();
        }
    }
}

// Get refund requests and completed refunds
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;

// Get refunds with transaction details
$query = "
    SELECT pr.*, pt.transaction_id, pt.reference_number, pt.final_amount, pt.currency,
           pt.gateway_name, pt.user_id, pt.item_type, pt.item_id,
           u.username, u.email, up.first_name, up.last_name,
           c.title as course_title, e.title as exam_title,
           pb.username as processed_by_name
    FROM payment_refunds pr
    JOIN payment_transactions pt ON pr.transaction_id = pt.id
    JOIN users u ON pt.user_id = u.id
    LEFT JOIN user_profiles up ON u.id = up.user_id
    LEFT JOIN courses c ON pt.item_type = 'course' AND pt.item_id = c.id
    LEFT JOIN exams e ON pt.item_type = 'exam' AND pt.item_id = e.id
    LEFT JOIN users pb ON pr.processed_by = pb.id
    ORDER BY pr.created_at DESC
";

$stmt = $db->query($query);
$refunds = $stmt->fetchAll();

// Get refund statistics
$stats = $db->query("
    SELECT
        COUNT(*) as total_refunds,
        SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END) as total_refunded_amount,
        AVG(CASE WHEN status = 'completed' THEN amount ELSE NULL END) as avg_refund_amount
    FROM payment_refunds
    WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
")->fetch();

$page_title = 'Refund Management';
include 'includes/admin_header.php';
?>

<?php if ($error): ?>
    <div class="alert alert-error">
        <?php echo htmlspecialchars($error); ?>
    </div>
<?php endif; ?>

<?php if ($success): ?>
    <div class="alert alert-success">
        <?php echo htmlspecialchars($success); ?>
    </div>
<?php endif; ?>

<div class="refunds-section">
    <h2>Refund Management</h2>
    <p class="settings-description">Process and manage refund requests for completed transactions.</p>

    <!-- Statistics Cards -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-undo-alt"></i>
            </div>
            <div class="stat-info">
                <h3><?php echo number_format($stats['total_refunds']); ?></h3>
                <p>Total Refunds (30d)</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon refund">
                <i class="fas fa-dollar-sign"></i>
            </div>
            <div class="stat-info">
                <h3>$<?php echo number_format($stats['total_refunded_amount'], 2); ?></h3>
                <p>Total Refunded</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon average">
                <i class="fas fa-chart-line"></i>
            </div>
            <div class="stat-info">
                <h3>$<?php echo number_format($stats['avg_refund_amount'], 2); ?></h3>
                <p>Avg Refund Amount</p>
            </div>
        </div>
    </div>

    <!-- Process Refund Form -->
    <div class="settings-card">
        <h3>Process New Refund</h3>
        <form method="POST">
            <div class="row">
                <div class="col-md-4 mb-3">
                    <label for="transaction_id" class="form-label">Transaction ID or Reference *</label>
                    <input type="text" class="form-control" name="transaction_id" id="transaction_id" required
                           placeholder="Enter transaction ID or reference number">
                    <div class="form-text">Find this in the Payment History section</div>
                </div>
                <div class="col-md-3 mb-3">
                    <label for="refund_amount" class="form-label">Refund Amount *</label>
                    <input type="number" class="form-control" name="refund_amount" id="refund_amount" step="0.01" min="0" required>
                </div>
                <div class="col-md-5 mb-3">
                    <label for="reason" class="form-label">Reason for Refund *</label>
                    <input type="text" class="form-control" name="reason" id="reason" required
                           placeholder="e.g., Customer request, Technical issues">
                </div>
            </div>
            <div class="mb-3">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="notify_user" name="notify_user" checked>
                    <label class="form-check-label" for="notify_user">
                        Notify user via email about this refund
                    </label>
                </div>
            </div>
            <div class="form-actions">
                <button type="submit" name="process_refund" class="btn btn-primary">
                    <i class="fas fa-undo-alt me-2"></i>Process Refund
                </button>
            </div>
        </form>
    </div>

    <!-- Refunds History -->
    <div class="settings-card">
        <h3>Refund History</h3>
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Refund ID</th>
                        <th>Transaction</th>
                        <th>User</th>
                        <th>Item</th>
                        <th>Amount</th>
                        <th>Reason</th>
                        <th>Status</th>
                        <th>Processed</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($refunds)): ?>
                        <tr>
                            <td colspan="9" class="text-center py-4">
                                <i class="fas fa-undo-alt fa-3x text-muted mb-3"></i>
                                <p class="text-muted">No refunds found.</p>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($refunds as $refund): ?>
                            <tr>
                                <td>
                                    <code><?php echo htmlspecialchars(substr($refund['reference_number'], 0, 12)); ?>...</code>
                                </td>
                                <td>
                                    <code><?php echo htmlspecialchars(substr($refund['transaction_id'], 0, 12)); ?>...</code>
                                    <br>
                                    <small class="text-muted"><?php echo htmlspecialchars($refund['reference_number']); ?></small>
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($refund['first_name'] && $refund['last_name'] ? $refund['first_name'] . ' ' . $refund['last_name'] : $refund['username']); ?></strong>
                                    <br>
                                    <small class="text-muted"><?php echo htmlspecialchars($refund['email']); ?></small>
                                </td>
                                <td>
                                    <?php if ($refund['item_type'] === 'course'): ?>
                                        <i class="fas fa-graduation-cap text-primary me-1"></i>
                                        <?php echo htmlspecialchars(substr($refund['course_title'], 0, 25)); ?>...
                                    <?php elseif ($refund['item_type'] === 'exam'): ?>
                                        <i class="fas fa-file-alt text-warning me-1"></i>
                                        <?php echo htmlspecialchars(substr($refund['exam_title'], 0, 25)); ?>...
                                    <?php else: ?>
                                        <i class="fas fa-question-circle text-muted me-1"></i>
                                        <?php echo htmlspecialchars($refund['item_type']); ?>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($refund['currency']); ?> <?php echo number_format($refund['amount'], 2); ?></strong>
                                </td>
                                <td>
                                    <?php echo htmlspecialchars($refund['reason']); ?>
                                </td>
                                <td>
                                    <span class="badge status-<?php echo $refund['status']; ?>">
                                        <?php echo ucfirst(str_replace('_', ' ', $refund['status'])); ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if ($refund['processed_at']): ?>
                                        <?php echo date('M j, Y H:i', strtotime($refund['processed_at'])); ?>
                                        <br>
                                        <small class="text-muted">by <?php echo htmlspecialchars($refund['processed_by_name']); ?></small>
                                    <?php else: ?>
                                        <em>Not processed</em>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary" onclick="viewRefundDetails(<?php echo htmlspecialchars(json_encode($refund)); ?>)">
                                        <i class="fas fa-eye"></i> Details
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Refund Details Modal -->
<div class="modal fade" id="refundModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Refund Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="refundDetails">
                <!-- Refund details will be loaded here -->
            </div>
        </div>
    </div>
</div>

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

.settings-description {
    color: #64748b;
    margin-bottom: 2rem;
    font-size: 0.875rem;
}

.settings-card {
    background: white;
    padding: 2rem;
    border-radius: 0.75rem;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 2rem;
}

.settings-card h3 {
    font-size: 1.25rem;
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 1.5rem;
}

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

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

.stat-icon {
    width: 3rem;
    height: 3rem;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #e5e7eb;
    color: #6b7280;
    font-size: 1.25rem;
}

.stat-icon.refund {
    background-color: #fee2e2;
    color: #dc2626;
}

.stat-icon.average {
    background-color: #dbeafe;
    color: #2563eb;
}

.stat-info h3 {
    font-size: 1.875rem;
    font-weight: 700;
    color: #1f2937;
    margin: 0;
}

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

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

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

.form-text {
    color: #6b7280;
    font-size: 0.75rem;
    margin-top: 0.25rem;
}

.form-actions {
    margin-top: 1.5rem;
    padding-top: 1.5rem;
    border-top: 1px solid #e5e7eb;
}

.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;
}

.btn-outline-primary {
    color: #2563eb;
    border: 1px solid #2563eb;
    background-color: transparent;
}

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

.btn-sm {
    padding: 0.25rem 0.5rem;
    font-size: 0.75rem;
}

.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;
}

.badge {
    display: inline-block;
    padding: 0.25rem 0.5rem;
    font-size: 0.75rem;
    font-weight: 600;
    border-radius: 0.25rem;
}

.status-pending {
    background-color: #fef3c7;
    color: #f59e0b;
}

.status-processing {
    background-color: #dbeafe;
    color: #2563eb;
}

.status-completed {
    background-color: #d1fae5;
    color: #10b981;
}

.status-failed {
    background-color: #fee2e2;
    color: #dc2626;
}

.status-cancelled {
    background-color: #f3f4f6;
    color: #6b7280;
}

.alert {
    padding: 1rem;
    border-radius: 0.5rem;
    margin-bottom: 1rem;
}

.alert-error {
    background-color: #fef2f2;
    border: 1px solid #fecaca;
    color: #dc2626;
}

.alert-success {
    background-color: #f0fdf4;
    border: 1px solid #bbf7d0;
    color: #16a34a;
}

@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }

    .row {
        flex-direction: column;
    }

    .col-md-4,
    .col-md-3,
    .col-md-5 {
        margin-bottom: 1rem;
    }
}
</style>

<script>
function viewRefundDetails(refund) {
    const details = `
        <div class="refund-details">
            <div class="row mb-3">
                <div class="col-md-6">
                    <h6>Refund Information</h6>
                    <table class="table table-sm">
                        <tr><td><strong>Refund ID:</strong></td><td><code>${refund.reference_number}</code></td></tr>
                        <tr><td><strong>Status:</strong></td><td><span class="badge status-${refund.status}">${refund.status.charAt(0).toUpperCase() + refund.status.slice(1)}</span></td></tr>
                        <tr><td><strong>Amount:</strong></td><td>${refund.currency} ${parseFloat(refund.amount).toFixed(2)}</td></tr>
                        <tr><td><strong>Reason:</strong></td><td>${refund.reason}</td></tr>
                        <tr><td><strong>Created:</strong></td><td>${new Date(refund.created_at).toLocaleString()}</td></tr>
                        ${refund.processed_at ? `<tr><td><strong>Processed:</strong></td><td>${new Date(refund.processed_at).toLocaleString()}</td></tr>` : ''}
                        ${refund.processed_by_name ? `<tr><td><strong>Processed By:</strong></td><td>${refund.processed_by_name}</td></tr>` : ''}
                    </table>
                </div>
                <div class="col-md-6">
                    <h6>Original Transaction</h6>
                    <table class="table table-sm">
                        <tr><td><strong>Transaction ID:</strong></td><td><code>${refund.transaction_id}</code></td></tr>
                        <tr><td><strong>Reference:</strong></td><td>${refund.reference_number}</td></tr>
                        <tr><td><strong>Gateway:</strong></td><td>${refund.gateway_name.charAt(0).toUpperCase() + refund.gateway_name.slice(1)}</td></tr>
                        <tr><td><strong>Original Amount:</strong></td><td>${refund.currency} ${parseFloat(refund.final_amount).toFixed(2)}</td></tr>
                    </table>
                </div>
            </div>

            <div class="row mb-3">
                <div class="col-md-6">
                    <h6>User Information</h6>
                    <table class="table table-sm">
                        <tr><td><strong>Name:</strong></td><td>${refund.first_name && refund.last_name ? refund.first_name + ' ' + refund.last_name : refund.username}</td></tr>
                        <tr><td><strong>Email:</strong></td><td>${refund.email}</td></tr>
                        <tr><td><strong>User ID:</strong></td><td>${refund.user_id}</td></tr>
                    </table>
                </div>
                <div class="col-md-6">
                    <h6>Item Information</h6>
                    <table class="table table-sm">
                        <tr><td><strong>Type:</strong></td><td>${refund.item_type.charAt(0).toUpperCase() + refund.item_type.slice(1)}</td></tr>
                        <tr><td><strong>Item ID:</strong></td><td>${refund.item_id}</td></tr>
                        ${refund.course_title ? `<tr><td><strong>Title:</strong></td><td>${refund.course_title}</td></tr>` : ''}
                        ${refund.exam_title ? `<tr><td><strong>Title:</strong></td><td>${refund.exam_title}</td></tr>` : ''}
                    </table>
                </div>
            </div>
        </div>
    `;

    document.getElementById('refundDetails').innerHTML = details;
    const modal = new bootstrap.Modal(document.getElementById('refundModal'));
    modal.show();
}
</script>

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