<?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) {
        try {
            // Get current balance
            $row = $this->db->fetch("SELECT balance FROM wallets WHERE user_id = :uid", [':uid' => $userId]);
            
            if ($row) {
                $currentBalance = (float)$row['balance'];
                $newBalance = $currentBalance + (float)$amount;
                
                // Log the deduction for debugging
                error_log("WALLET UPDATE - User: $userId | Current: $currentBalance | Amount: $amount | New: $newBalance");
                
                $result = $this->db->update('wallets', ['balance' => $newBalance], 'user_id = :uid', [':uid' => $userId]);
                error_log("WALLET UPDATE RESULT: " . ($result ? "SUCCESS" : "FAILED"));
                return (bool)$result;
            } else {
                // Create wallet row if not exists
                $newBalance = max(0, (float)$amount);
                error_log("WALLET CREATE - User: $userId | Balance: $newBalance");
                
                $insertResult = $this->db->insert('wallets', ['user_id' => $userId, 'balance' => $newBalance]);
                error_log("WALLET INSERT RESULT: " . ($insertResult ? "SUCCESS (ID: $insertResult)" : "FAILED"));
                return (bool)$insertResult;
            }
        } catch (Exception $e) {
            error_log("WALLET ERROR - " . $e->getMessage());
            return false;
        }
    }


    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]
        );
    }
}
?>
