<?php
/**
 * Admin Customers API
 * Customer management for admin
 */

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/Database.php';
require_once __DIR__ . '/../../includes/Auth.php';
require_once __DIR__ . '/../../includes/User.php';
require_once __DIR__ . '/../../includes/B2B.php';

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

// Check admin authentication
$auth = new Auth();
if (!$auth->isAdmin()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$user = new User();
$b2b = new B2B();
$db = Database::getInstance();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    switch ($method) {
        case 'GET':
            if ($action === 'list') {
                $page = $_GET['page'] ?? 1;
                $perPage = $_GET['per_page'] ?? 20;
                $search = $_GET['search'] ?? '';
                
                $sql = "SELECT u.*, bg.name as b2b_group_name
                        FROM users u
                        LEFT JOIN b2b_group_users bgu ON u.id = bgu.user_id
                        LEFT JOIN b2b_groups bg ON bgu.b2b_group_id = bg.id
                        WHERE 1=1";
                $params = [];
                
                if ($search) {
                    $sql .= " AND (u.first_name LIKE ? OR u.last_name LIKE ? OR u.email LIKE ? OR u.phone LIKE ?)";
                    $searchTerm = '%' . $search . '%';
                    $params[] = $searchTerm;
                    $params[] = $searchTerm;
                    $params[] = $searchTerm;
                    $params[] = $searchTerm;
                }
                
                $sql .= " GROUP BY u.id ORDER BY u.created_at DESC";
                $sql .= " LIMIT ? OFFSET ?";
                $params[] = $perPage;
                $params[] = ($page - 1) * $perPage;
                
                $customers = $db->fetchAll($sql, $params);
                
                // Get total count
                $countSql = "SELECT COUNT(*) as total FROM users WHERE 1=1";
                $countParams = [];
                if ($search) {
                    $countSql .= " AND (first_name LIKE ? OR last_name LIKE ? OR email LIKE ? OR phone LIKE ?)";
                    $searchTerm = '%' . $search . '%';
                    $countParams[] = $searchTerm;
                    $countParams[] = $searchTerm;
                    $countParams[] = $searchTerm;
                    $countParams[] = $searchTerm;
                }
                $totalResult = $db->fetchOne($countSql, $countParams);
                $total = $totalResult['total'] ?? 0;
                
                echo json_encode([
                    'success' => true,
                    'customers' => $customers,
                    'total' => $total,
                    'page' => $page,
                    'per_page' => $perPage
                ]);
            } elseif ($action === 'get') {
                $id = $_GET['id'] ?? 0;
                $customer = $user->getUserById($id);
                
                if ($customer) {
                    // Get B2B group
                    $b2bGroup = $b2b->getUserB2BGroup($id);
                    $customer['b2b_group'] = $b2bGroup;
                    
                    // Get product-specific prices
                    $productPrices = $b2b->getUserProductPrices($id);
                    $customer['product_prices'] = $productPrices;
                    
                    // Get addresses
                    $addresses = $user->getAddresses($id);
                    $customer['addresses'] = $addresses;
                    
                    // Get orders count
                    $ordersCount = $db->fetchOne(
                        "SELECT COUNT(*) as total FROM orders WHERE user_id = ?",
                        [$id]
                    );
                    $customer['orders_count'] = $ordersCount['total'] ?? 0;
                    
                    echo json_encode(['success' => true, 'customer' => $customer]);
                } else {
                    http_response_code(404);
                    echo json_encode(['success' => false, 'message' => 'Customer not found']);
                }
            }
            break;

        case 'POST':
            $data = json_decode(file_get_contents('php://input'), true);
            
            if ($action === 'update') {
                $id = $data['id'] ?? 0;
                $result = $user->updateProfile($id, $data);
                echo json_encode(['success' => $result]);
            } elseif ($action === 'set-b2b-group') {
                $userId = $data['user_id'] ?? 0;
                $groupId = $data['b2b_group_id'] ?? null;
                
                if ($groupId) {
                    $b2b->addUserToGroup($userId, $groupId);
                } else {
                    // Remove from all groups
                    $currentGroup = $b2b->getUserB2BGroup($userId);
                    if ($currentGroup) {
                        $b2b->removeUserFromGroup($userId, $currentGroup['id']);
                    }
                }
                
                echo json_encode(['success' => true]);
            } elseif ($action === 'set-product-price') {
                $userId = $data['user_id'] ?? 0;
                $productId = $data['product_id'] ?? 0;
                $priceData = [
                    'discount_percent' => $data['discount_percent'] ?? null,
                    'custom_price' => $data['custom_price'] ?? null
                ];
                
                $b2b->setProductPriceForUser($userId, $productId, $priceData);
                echo json_encode(['success' => true]);
            } elseif ($action === 'remove-product-price') {
                $userId = $data['user_id'] ?? 0;
                $productId = $data['product_id'] ?? 0;
                $b2b->removeProductPriceForUser($userId, $productId);
                echo json_encode(['success' => true]);
            }
            break;

        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>

