<?php
class User {
    private $db;

    public function __construct($db) {
        $this->db = $db;
    }

    public function getUserById($id) {
        return $this->db->fetch('SELECT id, name, email, role, is_active, created_at FROM users WHERE id = :id', [
            ':id' => $id
        ]);
    }

    public function getUserByEmail($email) {
        return $this->db->fetch('SELECT id, name, email, role, is_active, created_at FROM users WHERE email = :email', [
            ':email' => $email
        ]);
    }

    public function getAllUsers($limit = 50, $offset = 0) {
        return $this->db->fetchAll(
            'SELECT id, name, email, role, is_active, created_at 
             FROM users 
             ORDER BY created_at DESC 
             LIMIT :limit OFFSET :offset',
            [
                ':limit' => (int)$limit,
                ':offset' => (int)$offset
            ]
        );
    }

    public function updateProfile($id, $name, $email) {
        return $this->db->update('users', [
            'name' => $name,
            'email' => $email
        ], 'id = :id', [':id' => $id]);
    }

    public function updatePassword($id, $newPassword) {
        $hashed = password_hash($newPassword, PASSWORD_BCRYPT, ['cost' => 12]);
        return $this->db->update('users', [
            'password' => $hashed
        ], 'id = :id', [':id' => $id]);
    }

    public function toggleUserStatus($id) {
        $user = $this->getUserById($id);
        if ($user) {
            $newStatus = $user['is_active'] ? 0 : 1;
            return $this->db->update('users', ['is_active' => $newStatus], 'id = :id', [':id' => $id]);
        }
        return false;
    }

    // ✅ FIXED VERSION — uses $this->db->fetch() instead of prepare()
    public function getWalletBalance($userId) {
        $row = $this->db->fetch('SELECT balance FROM wallets WHERE user_id = :uid', [':uid' => $userId]);
        return $row ? (float)$row['balance'] : 0.00;
    }

    public function updateWalletBalance($userId, $amount) {
    // get current
    $row = $this->db->fetch("SELECT balance FROM wallets WHERE user_id = :uid", [':uid' => $userId]);
    if ($row) {
        $newBalance = (float)$row['balance'] + (float)$amount;
        $this->db->update('wallets', ['balance' => $newBalance], 'user_id = :uid', [':uid' => $userId]);
    } else {
        // create wallet row if not exists
        $newBalance = max(0, $amount);
        $this->db->insert('wallets', ['user_id' => $userId, 'balance' => $newBalance]);
    }
    return true;
}


    public function getPermissions($userId) {
        return $this->db->fetch('SELECT * FROM permissions WHERE user_id = :uid', [':uid' => $userId]);
    }

    public function updatePermissions($userId, $permissions) {
        return $this->db->update('permissions', $permissions, 'user_id = :uid', [':uid' => $userId]);
    }

    public function getSearchHistory($userId, $limit = 20) {
    // Convert limit to integer (safely)
    $limit = (int)$limit;

    // ✅ If $this->db is your custom Database wrapper
    if (method_exists($this->db, 'fetchAll')) {
        $sql = "SELECT id, type, query, cost, status, created_at
                FROM search_logs
                WHERE user_id = :uid
                ORDER BY created_at DESC
                LIMIT $limit";
        return $this->db->fetchAll($sql, [':uid' => $userId]);
    }

    // ✅ If $this->db is raw PDO object
    $stmt = $this->db->prepare("
        SELECT id, type, query, cost, status, created_at
        FROM search_logs
        WHERE user_id = :uid
        ORDER BY created_at DESC
        LIMIT $limit
    ");
    $stmt->execute([':uid' => $userId]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}


    public function getUnreadMessages($userId) {
        return $this->db->fetchAll(
            'SELECT id, title, body, created_at 
             FROM admin_messages 
             WHERE user_id = :uid AND read_status = 0 
             ORDER BY created_at DESC',
            [':uid' => $userId]
        );
    }

    public function markMessageAsRead($messageId, $userId) {
        return $this->db->update(
            'admin_messages',
            ['read_status' => 1],
            'id = :mid AND user_id = :uid',
            [':mid' => $messageId, ':uid' => $userId]
        );
    }
}
?>
