<?php
/**
 * Admin Panel - User Management Controller
 * Manages user accounts, balances, and permissions
 */

namespace App\Controller\Admin;

class UserManagementController extends AdminController {
    
    /**
     * List all users
     */
    public function listUsers($page = 1, $limit = 50) {
        $offset = ($page - 1) * $limit;
        
        // Get total count
        $countStmt = $this->db->query('SELECT COUNT(*) as total FROM users');
        $total = $countStmt->fetch(\PDO::FETCH_ASSOC)['total'];
        $totalPages = ceil($total / $limit);
        
        // Get users
        $stmt = $this->db->prepare('
            SELECT id, username, email, full_name, balance, primary_currency, account_type, status, created_at
            FROM users
            ORDER BY created_at DESC
            LIMIT ? OFFSET ?
        ');
        $stmt->execute([$limit, $offset]);
        $users = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        
        return [
            'users' => $users,
            'pagination' => [
                'current_page' => $page,
                'total_pages' => $totalPages,
                'total_users' => $total,
                'per_page' => $limit
            ]
        ];
    }
    
    /**
     * Get user details
     */
    public function getUserDetails($userId) {
        $stmt = $this->db->prepare('
            SELECT u.*, COUNT(DISTINCT o.id) as total_orders, SUM(o.price) as total_spent
            FROM users u
            LEFT JOIN orders o ON u.id = o.user_id
            WHERE u.id = ?
            GROUP BY u.id
        ');
        $stmt->execute([$userId]);
        $user = $stmt->fetch(\PDO::FETCH_ASSOC);
        
        if (!$user) {
            return null;
        }
        
        // Get recent orders
        $stmt = $this->db->prepare('
            SELECT o.*, s.name as service_name
            FROM orders o
            JOIN services s ON o.service_id = s.id
            WHERE o.user_id = ?
            ORDER BY o.created_at DESC
            LIMIT 10
        ');
        $stmt->execute([$userId]);
        $user['recent_orders'] = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        
        // Get recent transactions
        $stmt = $this->db->prepare('
            SELECT * FROM transactions
            WHERE user_id = ?
            ORDER BY created_at DESC
            LIMIT 10
        ');
        $stmt->execute([$userId]);
        $user['recent_transactions'] = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        
        return $user;
    }
    
    /**
     * Search users
     */
    public function searchUsers($query, $limit = 50) {
        $query = '%' . $query . '%';
        $stmt = $this->db->prepare('
            SELECT id, username, email, full_name, balance, status, account_type
            FROM users
            WHERE username LIKE ? OR email LIKE ? OR full_name LIKE ?
            LIMIT ?
        ');
        $stmt->execute([$query, $query, $query, $limit]);
        
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }
    
    /**
     * Adjust user balance
     */
    public function adjustBalance($userId, $amount, $reason = '', $transactionType = 'charge') {
        try {
            $this->db->beginTransaction();
            
            // Get current balance
            $stmt = $this->db->prepare('SELECT balance FROM users WHERE id = ?');
            $stmt->execute([$userId]);
            $user = $stmt->fetch(\PDO::FETCH_ASSOC);
            
            if (!$user) {
                throw new \Exception('User not found');
            }
            
            $previousBalance = $user['balance'];
            $newBalance = $previousBalance + $amount; // negative amount for deduction
            
            // Update user balance
            $stmt = $this->db->prepare('UPDATE users SET balance = ? WHERE id = ?');
            $stmt->execute([$newBalance, $userId]);
            
            // Log transaction
            $stmt = $this->db->prepare('
                INSERT INTO transactions 
                (user_id, transaction_type, description, amount, previous_balance, new_balance, status)
                VALUES (?, ?, ?, ?, ?, ?, "completed")
            ');
            $stmt->execute([
                $userId,
                $transactionType,
                $reason ?: 'Admin adjustment',
                $amount,
                $previousBalance,
                $newBalance
            ]);
            
            $this->db->commit();
            
            $this->logAdminAction('balance_adjustment', "User $userId: $amount (reason: $reason)");
            
            return [
                'success' => true,
                'previous_balance' => $previousBalance,
                'new_balance' => $newBalance
            ];
            
        } catch (\Exception $e) {
            $this->db->rollBack();
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Change user status
     */
    public function changeUserStatus($userId, $newStatus) {
        $validStatuses = ['active', 'inactive', 'suspended', 'banned'];
        
        if (!in_array($newStatus, $validStatuses)) {
            return ['success' => false, 'error' => 'Invalid status'];
        }
        
        $stmt = $this->db->prepare('UPDATE users SET status = ? WHERE id = ?');
        $result = $stmt->execute([$newStatus, $userId]);
        
        if ($result) {
            $this->logAdminAction('user_status_change', "User $userId status changed to $newStatus");
            return ['success' => true, 'new_status' => $newStatus];
        }
        
        return ['success' => false, 'error' => 'Failed to update status'];
    }
    
    /**
     * Reset user API key
     */
    public function resetApiKey($userId) {
        $newApiKey = bin2hex(random_bytes(32));
        
        $stmt = $this->db->prepare('UPDATE users SET api_key = ? WHERE id = ?');
        $result = $stmt->execute([$newApiKey, $userId]);
        
        if ($result) {
            $this->logAdminAction('api_key_reset', "User $userId API key reset");
            return ['success' => true, 'api_key' => $newApiKey];
        }
        
        return ['success' => false, 'error' => 'Failed to reset API key'];
    }
    
    /**
     * Delete user account
     */
    public function deleteUser($userId) {
        try {
            $this->db->beginTransaction();
            
            // Check if user has pending payments
            $stmt = $this->db->prepare('SELECT COUNT(*) as count FROM payments WHERE user_id = ? AND status = "pending"');
            $stmt->execute([$userId]);
            $pending = $stmt->fetch(\PDO::FETCH_ASSOC)['count'];
            
            if ($pending > 0) {
                throw new \Exception('Cannot delete user with pending payments');
            }
            
            // Delete user (cascade delete will handle related records)
            $stmt = $this->db->prepare('DELETE FROM users WHERE id = ?');
            $stmt->execute([$userId]);
            
            $this->db->commit();
            
            $this->logAdminAction('user_deletion', "User $userId deleted");
            
            return ['success' => true];
            
        } catch (\Exception $e) {
            $this->db->rollBack();
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Export users to CSV
     */
    public function exportUsersCSV() {
        $stmt = $this->db->query('
            SELECT id, username, email, full_name, balance, account_type, status, created_at
            FROM users
            ORDER BY created_at DESC
        ');
        $users = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        
        $csv = "ID,Username,Email,Full Name,Balance,Account Type,Status,Created At\n";
        foreach ($users as $user) {
            $csv .= implode(',', [
                $user['id'],
                '"' . $user['username'] . '"',
                $user['email'],
                '"' . $user['full_name'] . '"',
                $user['balance'],
                $user['account_type'],
                $user['status'],
                $user['created_at']
            ]) . "\n";
        }
        
        $this->logAdminAction('export_users', 'Exported user list to CSV');
        
        return $csv;
    }
}
?>
