<?php
/**
 * Customers API Endpoint
 * Fetches customers 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']) : '';
    $offset = ($page - 1) * $limit;
    
    // Build query
    $where = [];
    $params = [];
    
    if (!empty($search)) {
        $where[] = "(first_name LIKE ? OR last_name LIKE ? OR email LIKE ?)";
        $params[] = "%{$search}%";
        $params[] = "%{$search}%";
        $params[] = "%{$search}%";
    }
    
    $whereClause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';
    
    // Get total count
    $countQuery = "SELECT COUNT(*) as total FROM customers $whereClause";
    $stmt = $db->prepare($countQuery);
    $stmt->execute($params);
    $totalCustomers = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Get customers
    $query = "
        SELECT 
            id,
            first_name,
            last_name,
            email,
            country,
            total_orders,
            total_spent,
            avatar,
            created_at
        FROM customers
        $whereClause
        ORDER BY created_at DESC
        LIMIT ? OFFSET ?
    ";
    
    $params[] = $limit;
    $params[] = $offset;
    
    $stmt = $db->prepare($query);
    $stmt->execute($params);
    $customers = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format customers
    $formattedCustomers = [];
    foreach ($customers as $customer) {
        $formattedCustomers[] = [
            'id' => $customer['id'],
            'name' => $customer['first_name'] . ' ' . $customer['last_name'],
            'email' => $customer['email'],
            'country' => $customer['country'] ?: 'Unknown',
            'orders' => (int)$customer['total_orders'],
            'spent' => number_format($customer['total_spent'], 2),
            'avatar' => $customer['avatar'] ?: 'assets/images/users/avatar-1.jpg' // Default avatar
        ];
    }
    
    // Calculate pagination
    $totalPages = ceil($totalCustomers / $limit);
    
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'data' => $formattedCustomers,
        'pagination' => [
            'current_page' => $page,
            'total_pages' => $totalPages,
            'total_customers' => $totalCustomers,
            'per_page' => $limit,
            'has_next' => $page < $totalPages,
            'has_prev' => $page > 1
        ]
    ]);
    
} catch (Exception $e) {
    error_log('Customers API error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to fetch customers'
    ]);
}
?>
