<?php
/**
 * User Class - WeaverSM
 */
class User {
    private $pdo;
    
    public function __construct() {
        $this->pdo = getDBConnection();
    }
    
    public function create($data) {
        try {
            $stmt = $this->pdo->prepare("INSERT INTO users (name, email, password, role, status, balance) VALUES (?, ?, ?, ?, ?, 0.00)");
            $stmt->execute([
                $data['name'], 
                $data['email'], 
                hashPassword($data['password']), 
                $data['role'] ?? 'user', 
                $data['status'] ?? 'active'
            ]);
            return ['success' => true, 'user_id' => $this->pdo->lastInsertId()];
        } catch (PDOException $e) {
            return ['success' => false, 'message' => 'Failed to create user'];
        }
    }
    
    public function getById($id) {
        $stmt = $this->pdo->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch();
    }
    
    public function getByEmail($email) {
        $stmt = $this->pdo->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$email]);
        return $stmt->fetch();
    }
    
    public function update($id, $data) {
        $fields = [];
        $values = [];
        foreach ($data as $key => $value) {
            if ($key !== 'id') {
                $fields[] = "$key = ?";
                $values[] = $value;
            }
        }
        $values[] = $id;
        $stmt = $this->pdo->prepare("UPDATE users SET " . implode(', ', $fields) . " WHERE id = ?");
        return $stmt->execute($values);
    }
    
    public function updatePassword($id, $newPassword) {
        $stmt = $this->pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
        return $stmt->execute([hashPassword($newPassword), $id]);
    }
    
    public function updateBalance($id, $amount, $type = 'add') {
        $operator = ($type === 'add') ? '+' : '-';
        $stmt = $this->pdo->prepare("UPDATE users SET balance = balance $operator ? WHERE id = ?");
        return $stmt->execute([$amount, $id]);
    }
    
    public function getBalance($id) {
        $stmt = $this->pdo->prepare("SELECT balance FROM users WHERE id = ?");
        $stmt->execute([$id]);
        $result = $stmt->fetch();
        return $result ? (float)$result['balance'] : 0.00;
    }
    
    public function emailExists($email, $excludeId = null) {
        $sql = "SELECT COUNT(*) FROM users WHERE email = ?";
        $params = [$email];
        if ($excludeId) {
            $sql .= " AND id != ?";
            $params[] = $excludeId;
        }
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchColumn() > 0;
    }
    
    public function getAll($page = 1, $perPage = 20, $filters = []) {
        $where = "WHERE 1=1";
        $params = [];
        
        if (!empty($filters['role'])) { 
            $where .= " AND role = ?"; 
            $params[] = $filters['role']; 
        }
        if (!empty($filters['status'])) { 
            $where .= " AND status = ?"; 
            $params[] = $filters['status']; 
        }
        if (!empty($filters['search'])) { 
            $where .= " AND (name LIKE ? OR email LIKE ?)"; 
            $params[] = '%' . $filters['search'] . '%'; 
            $params[] = '%' . $filters['search'] . '%'; 
        }
        
        $countStmt = $this->pdo->prepare("SELECT COUNT(*) FROM users $where");
        $countStmt->execute($params);
        $total = $countStmt->fetchColumn();
        
        $offset = ($page - 1) * $perPage;
        $stmt = $this->pdo->prepare("SELECT * FROM users $where ORDER BY created_at DESC LIMIT $perPage OFFSET $offset");
        $stmt->execute($params);
        
        return ['users' => $stmt->fetchAll(), 'total' => $total, 'pagination' => paginate($total, $page, $perPage)];
    }
    
    public function recordTransaction($userId, $type, $amount, $description = null, $reference = null) {
        $balanceBefore = $this->getBalance($userId);
        
        if (in_array($type, ['deposit', 'refund', 'bonus'])) {
            $balanceAfter = $balanceBefore + $amount;
            $this->updateBalance($userId, $amount, 'add');
        } else {
            $balanceAfter = $balanceBefore - $amount;
            $this->updateBalance($userId, $amount, 'subtract');
        }
        
        $stmt = $this->pdo->prepare("INSERT INTO transactions (user_id, type, amount, balance_before, balance_after, description, reference) VALUES (?, ?, ?, ?, ?, ?, ?)");
        return $stmt->execute([$userId, $type, $amount, $balanceBefore, $balanceAfter, $description, $reference ?: generateReference()]);
    }
    
    public function getTransactions($userId, $page = 1, $perPage = 20) {
        $offset = ($page - 1) * $perPage;
        $countStmt = $this->pdo->prepare("SELECT COUNT(*) FROM transactions WHERE user_id = ?");
        $countStmt->execute([$userId]);
        $total = $countStmt->fetchColumn();
        
        $stmt = $this->pdo->prepare("SELECT * FROM transactions WHERE user_id = ? ORDER BY created_at DESC LIMIT $perPage OFFSET $offset");
        $stmt->execute([$userId]);
        
        return ['transactions' => $stmt->fetchAll(), 'total' => $total, 'pagination' => paginate($total, $page, $perPage)];
    }
    
    public function setAssistantPermissions($userId, $permissions) {
        $stmt = $this->pdo->prepare("SELECT id FROM assistant_permissions WHERE user_id = ?");
        $stmt->execute([$userId]);
        
        $allPerms = ['can_view_users', 'can_manage_users', 'can_manage_smm', 'can_manage_sms', 'can_view_orders', 'can_manage_banners', 'can_manage_offers', 'can_view_transactions', 'can_manage_support'];
        
        if ($stmt->fetch()) {
            $fields = [];
            $values = [];
            foreach ($allPerms as $perm) {
                $fields[] = "$perm = ?";
                $values[] = isset($permissions[$perm]) ? 1 : 0;
            }
            $values[] = $userId;
            $stmt = $this->pdo->prepare("UPDATE assistant_permissions SET " . implode(', ', $fields) . " WHERE user_id = ?");
            return $stmt->execute($values);
        } else {
            $values = [$userId];
            foreach ($allPerms as $perm) {
                $values[] = isset($permissions[$perm]) ? 1 : 0;
            }
            $stmt = $this->pdo->prepare("INSERT INTO assistant_permissions (user_id, " . implode(', ', $allPerms) . ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            return $stmt->execute($values);
        }
    }
    
    public function getAssistantPermissions($userId) {
        $stmt = $this->pdo->prepare("SELECT * FROM assistant_permissions WHERE user_id = ?");
        $stmt->execute([$userId]);
        return $stmt->fetch();
    }
    
    public function getStatistics() {
        $stats = [];
        $stats['total_users'] = $this->pdo->query("SELECT COUNT(*) FROM users WHERE role = 'user'")->fetchColumn();
        $stats['active_users'] = $this->pdo->query("SELECT COUNT(*) FROM users WHERE role = 'user' AND status = 'active'")->fetchColumn();
        $stats['total_balance'] = $this->pdo->query("SELECT COALESCE(SUM(balance), 0) FROM users WHERE role = 'user'")->fetchColumn();
        $stats['new_today'] = $this->pdo->query("SELECT COUNT(*) FROM users WHERE role = 'user' AND DATE(created_at) = CURDATE()")->fetchColumn();
        return $stats;
    }
}
