<?php
/**
 * Refunds API Endpoint
 * Fetches refunds from database with pagination and search
 */

require_once '../../includes/db_connection.php';
require_once '../includes/auth.php';

// Require authentication
requireAuth();

header('Content-Type: application/json');

// Only allow GET requests
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

try {
    $db = Database::getInstance()->getConnection();
    
    // Get parameters
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    $status = isset($_GET['status']) ? trim($_GET['status']) : '';
    $offset = ($page - 1) * $limit;
    
    // Build query
    $where = [];
    $params = [];
    
    // Base query for counting and fetching
    // We join with orders to get order number and customers to get customer name
    // If customer is deleted, we might want to fallback to order's customer name, but let's stick to left join
    
    $baseQuery = "
        FROM refunds r
        LEFT JOIN orders o ON r.order_id = o.id
        LEFT JOIN customers c ON r.customer_id = c.id
    ";
    
    if (!empty($search)) {
        $where[] = "(r.refund_number LIKE ? OR o.order_number LIKE ? OR c.first_name LIKE ? OR c.last_name LIKE ? OR c.email LIKE ?)";
        $searchTerm = "%{$search}%";
        $params[] = $searchTerm;
        $params[] = $searchTerm;
        $params[] = $searchTerm;
        $params[] = $searchTerm;
        $params[] = $searchTerm;
    }
    
    if (!empty($status)) {
        $where[] = "r.status = ?";
        $params[] = $status;
    }
    
    $whereClause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';
    
    // Get total count
    $countQuery = "SELECT COUNT(*) as total $baseQuery $whereClause";
    $stmt = $db->prepare($countQuery);
    $stmt->execute($params);
    $totalRefunds = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Get refunds
    $query = "
        SELECT 
            r.id,
            r.refund_number,
            r.refund_amount,
            r.status,
            r.refund_reason,
            r.created_at,
            o.id as order_id,
            o.order_number,
            c.first_name,
            c.last_name,
            c.email
        $baseQuery
        $whereClause
        ORDER BY r.created_at DESC
        LIMIT ? OFFSET ?
    ";
    
    $params[] = $limit;
    $params[] = $offset;
    
    $stmt = $db->prepare($query);
    $stmt->execute($params);
    $refunds = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format refunds
    $formattedRefunds = [];
    foreach ($refunds as $refund) {
        $customerName = $refund['first_name'] ? $refund['first_name'] . ' ' . $refund['last_name'] : 'Unknown Customer';
        
        $formattedRefunds[] = [
            'id' => $refund['id'],
            'refund_number' => $refund['refund_number'],
            'order_id' => $refund['order_id'],
            'order_number' => $refund['order_number'],
            'customer_name' => $customerName,
            'amount' => number_format($refund['refund_amount'], 2),
            'status' => $refund['status'],
            'reason' => $refund['refund_reason'] ?: 'No reason provided',
            'created_at' => date('M d \a\t h:i a', strtotime($refund['created_at']))
        ];
    }
    
    // Calculate pagination
    $totalPages = ceil($totalRefunds / $limit);
    
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'data' => $formattedRefunds,
        'pagination' => [
            'current_page' => $page,
            'total_pages' => $totalPages,
            'total_refunds' => $totalRefunds,
            'per_page' => $limit,
            'has_next' => $page < $totalPages,
            'has_prev' => $page > 1
        ]
    ]);
    
} catch (Exception $e) {
    error_log('Refunds API error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to fetch refunds'
    ]);
}
?>
