<?php
session_start();
require_once 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$error_message = '';
$success_message = '';

// Check if payment_refunds table exists, create if not
$check_table = $conn->query("SHOW TABLES LIKE 'payment_refunds'");
if ($check_table->num_rows == 0) {
    $create_sql = "CREATE TABLE `payment_refunds` (
        `refund_id` int NOT NULL AUTO_INCREMENT,
        `payment_id` int NOT NULL,
        `refund_amount` decimal(10,2) NOT NULL,
        `refund_reason` varchar(255) NOT NULL,
        `refund_notes` text,
        `processed_by` int NOT NULL,
        `processed_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
        `status` enum('PENDING','COMPLETED','FAILED','CANCELLED') DEFAULT 'COMPLETED',
        PRIMARY KEY (`refund_id`),
        KEY `fk_refund_payment` (`payment_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci";
    $conn->query($create_sql);
}

// Handle refund processing
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['process_refund'])) {
    try {
        $conn->begin_transaction();
        
        $payment_id = (int)$_POST['payment_id'];
        $refund_amount = floatval($_POST['refund_amount']);
        $refund_reason = $conn->real_escape_string($_POST['refund_reason']);
        $refund_notes = $conn->real_escape_string($_POST['refund_notes']);
        
        // Get payment details
        $sql_payment = "SELECT p.*, o.order_number, o.customer_id, c.first_name, c.last_name 
                       FROM payments p 
                       INNER JOIN orders o ON p.order_id = o.order_id 
                       INNER JOIN customers c ON o.customer_id = c.customer_id 
                       WHERE p.payment_id = ?";
        $stmt_payment = $conn->prepare($sql_payment);
        $stmt_payment->bind_param("i", $payment_id);
        $stmt_payment->execute();
        $payment = $stmt_payment->get_result()->fetch_assoc();
        
        if (!$payment) {
            throw new Exception('Payment not found');
        }
        
        if ($payment['status'] === 'REFUNDED') {
            throw new Exception('This payment has already been refunded');
        }
        
        if ($refund_amount > $payment['amount']) {
            throw new Exception('Refund amount cannot exceed the original payment amount');
        }
        
        // Create refund record
        $sql_refund = "INSERT INTO payment_refunds (payment_id, refund_amount, refund_reason, refund_notes, processed_by, processed_at, status) 
                      VALUES (?, ?, ?, ?, ?, NOW(), 'COMPLETED')";
        $stmt_refund = $conn->prepare($sql_refund);
        $stmt_refund->bind_param("idssi", $payment_id, $refund_amount, $refund_reason, $refund_notes, $user_id);
        $stmt_refund->execute();
        $refund_id = $conn->insert_id;
        
        // Update payment status
        if ($refund_amount >= $payment['amount']) {
            // Full refund
            $sql_update_payment = "UPDATE payments SET status = 'REFUNDED' WHERE payment_id = ?";
            $stmt_update_payment = $conn->prepare($sql_update_payment);
            $stmt_update_payment->bind_param("i", $payment_id);
            $stmt_update_payment->execute();
        } else {
            // Partial refund - create negative payment record
            $sql_negative = "INSERT INTO payments (payment_number, order_id, customer_id, payment_method_id, amount, payment_date, status, notes, processed_by) 
                           VALUES (?, ?, ?, ?, ?, NOW(), 'COMPLETED', ?, ?)";
            $stmt_negative = $conn->prepare($sql_negative);
            
            // Generate refund payment number
            $refund_payment_number = 'REF' . str_pad($refund_id, 6, '0', STR_PAD_LEFT);
            $negative_amount = -$refund_amount;
            $refund_note = "Partial refund for payment {$payment['payment_number']} - {$refund_reason}";
            
            $stmt_negative->bind_param("siiidsi", $refund_payment_number, $payment['order_id'], $payment['customer_id'], 
                                     $payment['payment_method_id'], $negative_amount, $refund_note, $user_id);
            $stmt_negative->execute();
        }
        
        // Update order balance
        $sql_update_order = "UPDATE orders SET 
                           paid_amount = paid_amount - ?, 
                           balance_amount = balance_amount + ?,
                           payment_status = CASE 
                               WHEN (paid_amount - ?) <= 0 THEN 'PENDING'
                               WHEN (paid_amount - ?) < total_amount THEN 'PARTIAL'
                               ELSE 'PAID'
                           END
                           WHERE order_id = ?";
        $stmt_update_order = $conn->prepare($sql_update_order);
        $stmt_update_order->bind_param("ddddi", $refund_amount, $refund_amount, $refund_amount, $refund_amount, $payment['order_id']);
        $stmt_update_order->execute();
        
        // Generate refund receipt
        $sql_receipt = "INSERT INTO receipts (receipt_number, order_id, customer_id, receipt_type, total_amount, payment_method, issued_by, issued_at) 
                       VALUES (?, ?, ?, 'REFUND', ?, ?, ?, NOW())";
        $stmt_receipt = $conn->prepare($sql_receipt);
        
        // Generate receipt number
        $receipt_number = 'RFD' . date('Ymd') . str_pad($refund_id, 4, '0', STR_PAD_LEFT);
        $payment_method_name = 'Refund to ' . $payment['payment_method'];
        
        $stmt_receipt->bind_param("siidsi", $receipt_number, $payment['order_id'], $payment['customer_id'], 
                                $refund_amount, $payment_method_name, $user_id);
        $stmt_receipt->execute();
        
        // Log activity
        $sql_log = "INSERT INTO activity_log (user_id, action, module, record_id, old_values, new_values, ip_address, user_agent, logged_at) 
                   VALUES (?, 'UPDATE', 'PAYMENTS', ?, ?, ?, ?, ?, NOW())";
        $stmt_log = $conn->prepare($sql_log);
        
        $old_values = json_encode(['payment_status' => $payment['status'], 'amount' => $payment['amount']]);
        $new_values = json_encode(['refund_amount' => $refund_amount, 'refund_reason' => $refund_reason]);
        
        $stmt_log->bind_param("iissss", $user_id, $payment_id, $old_values, $new_values, 
                             $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT']);
        $stmt_log->execute();
        
        $conn->commit();
        $success_message = "Refund processed successfully. Receipt number: {$receipt_number}";
        
    } catch (Exception $e) {
        $conn->rollback();
        $error_message = $e->getMessage();
    }
}

// Get payment ID from URL or form
$payment_id = isset($_GET['payment_id']) ? (int)$_GET['payment_id'] : (isset($_POST['payment_id']) ? (int)$_POST['payment_id'] : 0);

$payment_details = null;
if ($payment_id > 0) {
    // Get payment details
    $sql_payment = "SELECT 
        p.*,
        o.order_number,
        o.order_date,
        o.total_amount as order_total,
        o.balance_amount,
        c.customer_id,
        c.first_name,
        c.last_name,
        c.customer_code,
        c.phone,
        c.email,
        pm.method_name,
        u.full_name as processed_by_name,
        (SELECT SUM(refund_amount) FROM payment_refunds WHERE payment_id = p.payment_id) as total_refunded
    FROM payments p
    INNER JOIN orders o ON p.order_id = o.order_id
    INNER JOIN customers c ON o.customer_id = c.customer_id
    INNER JOIN payment_methods pm ON p.payment_method_id = pm.method_id
    INNER JOIN users u ON p.processed_by = u.user_id
    WHERE p.payment_id = ?";
    
    $stmt_payment = $conn->prepare($sql_payment);
    $stmt_payment->bind_param("i", $payment_id);
    $stmt_payment->execute();
    $payment_details = $stmt_payment->get_result()->fetch_assoc();
}

// Get recent refunds for reference
$sql_recent_refunds = "SELECT 
    pr.*,
    p.payment_number,
    p.amount as original_amount,
    o.order_number,
    CONCAT(c.first_name, ' ', c.last_name) as customer_name,
    u.full_name as processed_by_name
FROM payment_refunds pr
INNER JOIN payments p ON pr.payment_id = p.payment_id
INNER JOIN orders o ON p.order_id = o.order_id
INNER JOIN customers c ON o.customer_id = c.customer_id
INNER JOIN users u ON pr.processed_by = u.user_id
ORDER BY pr.processed_at DESC
LIMIT 10";

$result_recent_refunds = $conn->query($sql_recent_refunds);

// Get refundable payments (recent payments that can be refunded)
$sql_refundable = "SELECT 
    p.payment_id,
    p.payment_number,
    p.amount,
    p.payment_date,
    o.order_number,
    CONCAT(c.first_name, ' ', c.last_name) as customer_name,
    pm.method_name,
    p.status,
    COALESCE(SUM(pr.refund_amount), 0) as total_refunded
FROM payments p
INNER JOIN orders o ON p.order_id = o.order_id
INNER JOIN customers c ON o.customer_id = c.customer_id
INNER JOIN payment_methods pm ON p.payment_method_id = pm.method_id
LEFT JOIN payment_refunds pr ON p.payment_id = pr.payment_id
WHERE p.status IN ('COMPLETED', 'PARTIAL_REFUND') 
    AND p.amount > 0
    AND p.payment_date >= DATE_SUB(CURDATE(), INTERVAL 90 DAY)
GROUP BY p.payment_id, p.payment_number, p.amount, p.payment_date, o.order_number, customer_name, pm.method_name, p.status
HAVING (p.amount - total_refunded) > 0
ORDER BY p.payment_date DESC
LIMIT 20";

$result_refundable = $conn->query($sql_refundable);
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Process Refund - Laundry Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .page-content {
            background-color: #f8fafc;
        }
        
        .refund-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .card-header {
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
            padding: 1.5rem;
            border-radius: 12px 12px 0 0;
        }
        
        .card-body {
            padding: 1.5rem;
        }
        
        .card-title {
            font-size: 1.25rem;
            font-weight: 600;
            margin: 0;
            color: #1e293b;
        }
        
        .payment-info {
            background: #f0fdf4;
            border: 1px solid #bbf7d0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .customer-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: #059669;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 1.25rem;
        }
        
        .info-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.5rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .info-row:last-child {
            border-bottom: none;
        }
        
        .info-label {
            font-weight: 600;
            color: #64748b;
        }
        
        .info-value {
            color: #1e293b;
            font-weight: 500;
        }
        
        .form-control, .form-select {
            border: 1px solid #d1d5db;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #059669;
            box-shadow: 0 0 0 3px rgba(5, 150, 105, 0.1);
            outline: none;
        }
        
        .btn-primary {
            background: #059669;
            border-color: #059669;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 500;
        }
        
        .btn-primary:hover {
            background: #047857;
            border-color: #047857;
        }
        
        .btn-secondary {
            background: #64748b;
            border-color: #64748b;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 500;
        }
        
        .btn-danger {
            background: #dc2626;
            border-color: #dc2626;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 500;
        }
        
        .alert {
            border-radius: 8px;
            border: none;
            padding: 1rem 1.5rem;
            margin-bottom: 1.5rem;
        }
        
        .alert-success {
            background: #f0fdf4;
            color: #166534;
            border-left: 4px solid #059669;
        }
        
        .alert-danger {
            background: #fef2f2;
            color: #991b1b;
            border-left: 4px solid #dc2626;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            color: #64748b;
            font-size: 0.875rem;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .data-table tbody tr:hover {
            background: #f8fafc;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .status-completed { background: #dcfce7; color: #166534; }
        .status-refunded { background: #fee2e2; color: #991b1b; }
        .status-partial { background: #fef3c7; color: #92400e; }
        
        .refund-summary {
            background: #fef3c7;
            border: 1px solid #f59e0b;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .refund-amount {
            font-size: 1.5rem;
            font-weight: 700;
            color: #dc2626;
        }
        
        .search-section {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border: 1px solid #e2e8f0;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Process Refund</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_payments.php">Payments</a></li>
                                        <li class="breadcrumb-item active">Process Refund</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Success/Error Messages -->
                    <?php if ($success_message): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle me-2"></i>
                        <?php echo $success_message; ?>
                    </div>
                    <?php endif; ?>

                    <?php if ($error_message): ?>
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle me-2"></i>
                        <?php echo $error_message; ?>
                    </div>
                    <?php endif; ?>

                    <div class="row">
                        <!-- Refund Form -->
                        <div class="col-xl-8">
                            <?php if ($payment_details): ?>
                            <div class="refund-card">
                                <div class="card-header">
                                    <h5 class="card-title">Process Refund for Payment <?php echo $payment_details['payment_number']; ?></h5>
                                </div>
                                <div class="card-body">
                                    <!-- Payment Information -->
                                    <div class="payment-info">
                                        <h6 class="mb-3">Payment Information</h6>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="info-row">
                                                    <span class="info-label">Payment Number:</span>
                                                    <span class="info-value"><?php echo $payment_details['payment_number']; ?></span>
                                                </div>
                                                <div class="info-row">
                                                    <span class="info-label">Original Amount:</span>
                                                    <span class="info-value">KES <?php echo number_format($payment_details['amount'], 2); ?></span>
                                                </div>
                                                <div class="info-row">
                                                    <span class="info-label">Payment Method:</span>
                                                    <span class="info-value"><?php echo $payment_details['method_name']; ?></span>
                                                </div>
                                                <div class="info-row">
                                                    <span class="info-label">Payment Date:</span>
                                                    <span class="info-value"><?php echo date('M j, Y g:i A', strtotime($payment_details['payment_date'])); ?></span>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="info-row">
                                                    <span class="info-label">Order Number:</span>
                                                    <span class="info-value">
                                                        <a href="view_order.php?id=<?php echo $payment_details['order_id']; ?>" class="text-primary text-decoration-none">
                                                            <?php echo $payment_details['order_number']; ?>
                                                        </a>
                                                    </span>
                                                </div>
                                                <div class="info-row">
                                                    <span class="info-label">Customer:</span>
                                                    <span class="info-value"><?php echo $payment_details['first_name'] . ' ' . $payment_details['last_name']; ?></span>
                                                </div>
                                                <div class="info-row">
                                                    <span class="info-label">Already Refunded:</span>
                                                    <span class="info-value">KES <?php echo number_format($payment_details['total_refunded'] ?: 0, 2); ?></span>
                                                </div>
                                                <div class="info-row">
                                                    <span class="info-label">Available for Refund:</span>
                                                    <span class="info-value text-success">KES <?php echo number_format($payment_details['amount'] - ($payment_details['total_refunded'] ?: 0), 2); ?></span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Customer Information -->
                                    <div class="mb-4">
                                        <h6 class="mb-3">Customer Information</h6>
                                        <div class="d-flex align-items-center">
                                            <div class="customer-avatar me-3">
                                                <?php echo strtoupper(substr($payment_details['first_name'], 0, 1) . substr($payment_details['last_name'], 0, 1)); ?>
                                            </div>
                                            <div>
                                                <div class="fw-semibold"><?php echo $payment_details['first_name'] . ' ' . $payment_details['last_name']; ?></div>
                                                <div class="text-muted small"><?php echo $payment_details['customer_code']; ?></div>
                                                <div class="text-muted small"><?php echo $payment_details['phone']; ?></div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Refund Form -->
                                    <form method="POST" id="refundForm">
                                        <input type="hidden" name="payment_id" value="<?php echo $payment_details['payment_id']; ?>">
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label class="form-label">Refund Amount (KES) *</label>
                                                    <input type="number" class="form-control" name="refund_amount" 
                                                           step="0.01" min="0.01" 
                                                           max="<?php echo $payment_details['amount'] - ($payment_details['total_refunded'] ?: 0); ?>" 
                                                           required>
                                                    <div class="form-text">Maximum refundable: KES <?php echo number_format($payment_details['amount'] - ($payment_details['total_refunded'] ?: 0), 2); ?></div>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label class="form-label">Refund Reason *</label>
                                                    <select class="form-select" name="refund_reason" required>
                                                        <option value="">Select refund reason</option>
                                                        <option value="CUSTOMER_REQUEST">Customer Request</option>
                                                        <option value="SERVICE_ISSUE">Service Issue</option>
                                                        <option value="OVERCHARGE">Overcharge</option>
                                                        <option value="DAMAGED_ITEMS">Damaged Items</option>
                                                        <option value="LOST_ITEMS">Lost Items</option>
                                                        <option value="DELAYED_SERVICE">Delayed Service</option>
                                                        <option value="DUPLICATE_PAYMENT">Duplicate Payment</option>
                                                        <option value="CANCELLATION">Order Cancellation</option>
                                                        <option value="GOODWILL">Goodwill Refund</option>
                                                        <option value="OTHER">Other</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Additional Notes</label>
                                            <textarea class="form-control" name="refund_notes" rows="3" 
                                                      placeholder="Enter any additional notes about this refund..."></textarea>
                                        </div>

                                        <div class="refund-summary">
                                            <div class="d-flex justify-content-between align-items-center">
                                                <div>
                                                    <strong>Refund Summary</strong>
                                                    <div class="text-muted small">Please review before processing</div>
                                                </div>
                                                <div class="text-end">
                                                    <div class="refund-amount" id="refundAmountDisplay">KES 0.00</div>
                                                    <div class="text-muted small">Refund Amount</div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="d-flex gap-2">
                                            <button type="submit" name="process_refund" class="btn btn-danger">
                                                <i class="fas fa-undo me-2"></i>Process Refund
                                            </button>
                                            <a href="list_payments.php" class="btn btn-secondary">
                                                <i class="fas fa-arrow-left me-2"></i>Back to Payments
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                            <?php else: ?>
                            <!-- Search for Payment -->
                            <div class="search-section">
                                <h5 class="mb-3">Find Payment to Refund</h5>
                                <form method="GET" class="row g-3">
                                    <div class="col-md-8">
                                        <input type="number" class="form-control" name="payment_id" 
                                               placeholder="Enter Payment ID" value="<?php echo $payment_id; ?>">
                                    </div>
                                    <div class="col-md-4">
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="fas fa-search me-2"></i>Find Payment
                                        </button>
                                    </div>
                                </form>
                            </div>

                            <!-- Recent Refundable Payments -->
                            <div class="refund-card">
                                <div class="card-header">
                                    <h5 class="card-title">Recent Refundable Payments</h5>
                                </div>
                                <div class="card-body p-0">
                                    <div class="table-responsive">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Payment #</th>
                                                    <th>Customer</th>
                                                    <th>Order</th>
                                                    <th>Amount</th>
                                                    <th>Date</th>
                                                    <th>Status</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($payment = $result_refundable->fetch_assoc()): ?>
                                                <tr>
                                                    <td class="fw-semibold"><?php echo $payment['payment_number']; ?></td>
                                                    <td><?php echo $payment['customer_name']; ?></td>
                                                    <td>
                                                        <a href="view_order.php?order_number=<?php echo $payment['order_number']; ?>" 
                                                           class="text-primary text-decoration-none">
                                                            <?php echo $payment['order_number']; ?>
                                                        </a>
                                                    </td>
                                                    <td class="fw-semibold">KES <?php echo number_format($payment['amount'] - $payment['total_refunded'], 2); ?></td>
                                                    <td><?php echo date('M j, Y', strtotime($payment['payment_date'])); ?></td>
                                                    <td>
                                                        <?php
                                                        $status_class = match($payment['status']) {
                                                            'COMPLETED' => 'status-completed',
                                                            'REFUNDED' => 'status-refunded',
                                                            'PARTIAL_REFUND' => 'status-partial',
                                                            default => 'status-completed'
                                                        };
                                                        ?>
                                                        <span class="status-badge <?php echo $status_class; ?>">
                                                            <?php echo $payment['status']; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <a href="process_refund.php?payment_id=<?php echo $payment['payment_id']; ?>" 
                                                           class="btn btn-sm btn-outline-danger">
                                                            <i class="fas fa-undo me-1"></i>Refund
                                                        </a>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>

                        <!-- Recent Refunds -->
                        <div class="col-xl-4">
                            <div class="refund-card">
                                <div class="card-header">
                                    <h5 class="card-title">Recent Refunds</h5>
                                </div>
                                <div class="card-body">
                                    <?php while ($refund = $result_recent_refunds->fetch_assoc()): ?>
                                    <div class="d-flex justify-content-between align-items-start mb-3 pb-3 border-bottom">
                                        <div>
                                            <div class="fw-semibold"><?php echo $refund['payment_number']; ?></div>
                                            <div class="text-muted small"><?php echo $refund['customer_name']; ?></div>
                                            <div class="text-muted small"><?php echo $refund['order_number']; ?></div>
                                            <div class="text-muted small"><?php echo date('M j, g:i A', strtotime($refund['processed_at'])); ?></div>
                                        </div>
                                        <div class="text-end">
                                            <div class="fw-bold text-danger">KES <?php echo number_format($refund['refund_amount'], 2); ?></div>
                                            <div class="text-muted small"><?php echo ucfirst(str_replace('_', ' ', strtolower($refund['refund_reason']))); ?></div>
                                        </div>
                                    </div>
                                    <?php endwhile; ?>
                                </div>
                            </div>

                            <!-- Refund Guidelines -->
                            <div class="refund-card">
                                <div class="card-header">
                                    <h5 class="card-title">Refund Guidelines</h5>
                                </div>
                                <div class="card-body">
                                    <ul class="list-unstyled mb-0">
                                        <li class="mb-2">
                                            <i class="fas fa-check text-success me-2"></i>
                                            Verify customer identity before processing
                                        </li>
                                        <li class="mb-2">
                                            <i class="fas fa-check text-success me-2"></i>
                                            Document clear reason for refund
                                        </li>
                                        <li class="mb-2">
                                            <i class="fas fa-check text-success me-2"></i>
                                            Obtain manager approval for amounts > KES 5,000
                                        </li>
                                        <li class="mb-2">
                                            <i class="fas fa-check text-success me-2"></i>
                                            Process refunds within 24 hours when possible
                                        </li>
                                        <li class="mb-2">
                                            <i class="fas fa-check text-success me-2"></i>
                                            Provide receipt for all refund transactions
                                        </li>
                                        <li class="mb-0">
                                            <i class="fas fa-check text-success me-2"></i>
                                            Follow up with customer satisfaction
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <script>
        // Update refund amount display
        document.addEventListener('DOMContentLoaded', function() {
            const refundAmountInput = document.querySelector('input[name="refund_amount"]');
            const refundAmountDisplay = document.getElementById('refundAmountDisplay');
            
            if (refundAmountInput && refundAmountDisplay) {
                refundAmountInput.addEventListener('input', function() {
                    const amount = parseFloat(this.value) || 0;
                    refundAmountDisplay.textContent = 'KES ' + amount.toLocaleString('en-US', {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2
                    });
                });
            }
            
            // Form validation
            const refundForm = document.getElementById('refundForm');
            if (refundForm) {
                refundForm.addEventListener('submit', function(e) {
                    const refundAmount = parseFloat(document.querySelector('input[name="refund_amount"]').value);
                    const maxAmount = parseFloat(document.querySelector('input[name="refund_amount"]').max);
                    
                    if (refundAmount > maxAmount) {
                        e.preventDefault();
                        alert('Refund amount cannot exceed the available refundable amount');
                        return false;
                    }
                    
                    if (refundAmount <= 0) {
                        e.preventDefault();
                        alert('Please enter a valid refund amount');
                        return false;
                    }
                    
                    if (!confirm('Are you sure you want to process this refund? This action cannot be easily reversed.')) {
                        e.preventDefault();
                        return false;
                    }
                });
            }
        });
    </script>
</body>
</html>