<?php
/**
 * Admin Refund Management - COMPLETE FIXED VERSION
 * Digital Product Store
 */

require_once __DIR__ . '/includes/header.php';

$page_title = 'Refunds';

// Handle refund action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['process_refund'])) {
    $order_id = (int)($_POST['order_id'] ?? 0);
    $refund_amount = (float)($_POST['refund_amount'] ?? 0);
    $refund_reason = sanitize($_POST['refund_reason'] ?? '');
    
    if ($order_id && $refund_amount > 0) {
        try {
            // Get order details
            $stmt = $pdo->prepare("SELECT * FROM orders WHERE id = ?");
            $stmt->execute([$order_id]);
            $order = $stmt->fetch();
            
            if ($order) {
                // Update order status to refunded
                $stmt = $pdo->prepare("UPDATE orders SET payment_status = 'refunded' WHERE id = ?");
                $stmt->execute([$order_id]);
                
                // Log the refund
                $stmt = $pdo->prepare("INSERT INTO refunds (order_id, amount, reason, processed_by, processed_at) VALUES (?, ?, ?, ?, NOW())");
                $stmt->execute([$order_id, $refund_amount, $refund_reason, $admin_id]);
                
                log_admin_activity($pdo, $admin_id, 'process_refund', "Processed refund of " . format_price($refund_amount) . " for order #{$order['order_number']}");
                
                set_flash_message('Refund processed successfully.', 'success');
            } else {
                set_flash_message('Order not found.', 'error');
            }
        } catch (PDOException $e) {
            set_flash_message('Error processing refund: ' . $e->getMessage(), 'error');
        }
    } else {
        set_flash_message('Invalid refund amount or order ID.', 'error');
    }
    
    header('Location: ' . ADMIN_URL . '/refund.php');
    exit;
}

// Get filter parameters
$status_filter = $_GET['status'] ?? '';
$search = $_GET['search'] ?? '';
$page_num = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 20;
$offset = ($page_num - 1) * $per_page;

// Build query for orders that can be refunded
$where = ["payment_status = 'paid'"];
$params = [];

if ($status_filter) {
    $where[] = "order_status = ?";
    $params[] = $status_filter;
}

if ($search) {
    $where[] = "(order_number LIKE ? OR customer_name LIKE ? OR customer_email LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$where_clause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

// Get total count
$count_sql = "SELECT COUNT(*) FROM orders $where_clause";
$stmt = $pdo->prepare($count_sql);
$stmt->execute($params);
$total_orders = $stmt->fetchColumn();
$total_pages = ceil($total_orders / $per_page);

// Get orders
$sql = "SELECT o.*, u.name as user_name, u.email as user_email 
        FROM orders o 
        LEFT JOIN users u ON o.user_id = u.id 
        $where_clause 
        ORDER BY o.created_at DESC 
        LIMIT $per_page OFFSET $offset";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$orders = $stmt->fetchAll();

// Get refunded orders
$stmt = $pdo->query("SELECT o.*, r.amount as refund_amount, r.reason as refund_reason, r.processed_at as refund_date 
                     FROM orders o 
                     JOIN refunds r ON o.id = r.order_id 
                     ORDER BY r.processed_at DESC LIMIT 10");
$refunded_orders = $stmt->fetchAll();
?>

<div class="page-header">
    <div>
        <h1>Refunds</h1>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="<?php echo ADMIN_URL; ?>/index.php">Dashboard</a></li>
                <li class="breadcrumb-item active">Refunds</li>
            </ol>
        </nav>
    </div>
</div>

<!-- Filters -->
<div class="card mb-4">
    <div class="card-body">
        <form method="GET" class="row g-3">
            <div class="col-md-4">
                <input type="text" name="search" class="form-control" placeholder="Search orders..." 
                       value="<?php echo htmlspecialchars($search); ?>">
            </div>
            <div class="col-md-3">
                <select name="status" class="form-select">
                    <option value="">All Order Status</option>
                    <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                    <option value="processing" <?php echo $status_filter === 'processing' ? 'selected' : ''; ?>>Processing</option>
                    <option value="completed" <?php echo $status_filter === 'completed' ? 'selected' : ''; ?>>Completed</option>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100">
                    <i class="fas fa-filter"></i> Filter
                </button>
            </div>
        </form>
    </div>
</div>

<div class="row">
    <!-- Eligible Orders for Refund -->
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header">
                <i class="fas fa-undo me-2"></i>Orders Eligible for Refund (<?php echo $total_orders; ?>)
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead>
                            <tr>
                                <th>Order #</th>
                                <th>Customer</th>
                                <th>Total</th>
                                <th>Date</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($orders)): ?>
                            <tr>
                                <td colspan="5" class="text-center py-4">
                                    <i class="fas fa-check-circle fa-3x text-success mb-3"></i>
                                    <p class="text-muted">No orders eligible for refund</p>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($orders as $order): ?>
                            <tr>
                                <td><strong><?php echo $order['order_number']; ?></strong></td>
                                <td>
                                    <?php echo htmlspecialchars($order['customer_name']); ?>
                                    <br><small class="text-muted"><?php echo htmlspecialchars($order['customer_email']); ?></small>
                                </td>
                                <td><?php echo format_price($order['total']); ?></td>
                                <td><?php echo time_ago($order['created_at']); ?></td>
                                <td>
                                    <button type="button" class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#refundModal<?php echo $order['id']; ?>">
                                        <i class="fas fa-undo"></i> Refund
                                    </button>
                                </td>
                            </tr>
                            
                            <!-- Refund Modal -->
                            <div class="modal fade" id="refundModal<?php echo $order['id']; ?>" tabindex="-1" aria-hidden="true">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <form method="POST">
                                            <?php echo csrf_field(); ?>
                                            <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                                            <div class="modal-header">
                                                <h5 class="modal-title">Process Refund</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                            </div>
                                            <div class="modal-body">
                                                <p><strong>Order:</strong> <?php echo $order['order_number']; ?></p>
                                                <p><strong>Customer:</strong> <?php echo htmlspecialchars($order['customer_name']); ?></p>
                                                <p><strong>Total Amount:</strong> <?php echo format_price($order['total']); ?></p>
                                                
                                                <div class="mb-3">
                                                    <label class="form-label">Refund Amount *</label>
                                                    <div class="input-group">
                                                        <span class="input-group-text"><?php echo get_setting('currency_symbol', '$'); ?></span>
                                                        <input type="number" name="refund_amount" class="form-control" step="0.01" min="0.01" max="<?php echo $order['total']; ?>" value="<?php echo $order['total']; ?>" required>
                                                    </div>
                                                    <small class="text-muted">Maximum: <?php echo format_price($order['total']); ?></small>
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <label class="form-label">Refund Reason</label>
                                                    <textarea name="refund_reason" class="form-control" rows="3" placeholder="Enter reason for refund..."></textarea>
                                                </div>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                <button type="submit" name="process_refund" class="btn btn-warning">
                                                    <i class="fas fa-undo me-2"></i>Process Refund
                                                </button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <div class="card-footer">
                <nav>
                    <ul class="pagination justify-content-center mb-0">
                        <?php if ($page_num > 1): ?>
                        <li class="page-item">
                            <a class="page-link" href="?page=<?php echo $page_num - 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status_filter; ?>">Previous</a>
                        </li>
                        <?php endif; ?>
                        
                        <?php for ($i = max(1, $page_num - 2); $i <= min($total_pages, $page_num + 2); $i++): ?>
                        <li class="page-item <?php echo $i === $page_num ? 'active' : ''; ?>">
                            <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status_filter; ?>"><?php echo $i; ?></a>
                        </li>
                        <?php endfor; ?>
                        
                        <?php if ($page_num < $total_pages): ?>
                        <li class="page-item">
                            <a class="page-link" href="?page=<?php echo $page_num + 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status_filter; ?>">Next</a>
                        </li>
                        <?php endif; ?>
                    </ul>
                </nav>
            </div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Recent Refunds -->
    <div class="col-lg-4">
        <div class="card">
            <div class="card-header">
                <i class="fas fa-history me-2"></i>Recent Refunds
            </div>
            <div class="card-body p-0">
                <div class="list-group list-group-flush">
                    <?php if (empty($refunded_orders)): ?>
                    <div class="text-center py-4">
                        <i class="fas fa-info-circle fa-2x text-muted mb-2"></i>
                        <p class="text-muted mb-0">No refunds processed yet</p>
                    </div>
                    <?php else: ?>
                    <?php foreach ($refunded_orders as $refund): ?>
                    <div class="list-group-item">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <strong><?php echo $refund['order_number']; ?></strong>
                                <br><small class="text-muted"><?php echo time_ago($refund['refund_date']); ?></small>
                            </div>
                            <span class="badge bg-warning"><?php echo format_price($refund['refund_amount']); ?></span>
                        </div>
                        <?php if ($refund['refund_reason']): ?>
                        <small class="text-muted d-block mt-1"><?php echo htmlspecialchars(truncate($refund['refund_reason'], 50)); ?></small>
                        <?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
